Wednesday, November 17, 2010

.NET 4 / C# Code Contracts

It has been hard to find good content on the new .NET 4 code contract stuff for C#. Here is a Microsoft "User Manual" I found dated Sep. 2010. It is pretty good.

Download the PDF here.

Monday, October 25, 2010

Fast and easy way to search files using C# TPL

I wanted to play around with the .NET 4 Task Parallel Library (TPL) a bit so I wrote a "Task" oriented app to perform a file name and/or content search. The UI is Windows Forms. It's nothing pretty, but I found it to be much faster than using Windows Explorer when recursing down big trees and across network shares. The code is written using Visual Studio 2010 and .NET 4.

Let me know if you have any features requests or find serious bugs.

Click here to download.

Sunday, September 12, 2010

Scraping web pages automatically with C#

I frequently find myself writing small applications to scrape a web page to track a package, keep tabs on a product price, etc. I finally broke down and wrote a generic .NET 4 C# application that will do this for me via and XML "task" file. I execute the console application via the Windows Task Manager each day.

Your task file can include as many tasks (page scrapes) as you want and the application will notify you (via email) when it finds a successful comparison.

The magic works by you providing a web page URL to visit, a regular expression to find a pattern on the page, and a value to compare that pattern against. You can be notified when that pattern is different, is the same, or when it changes. The console application is full of nice little features that are configured via the task XML file.

Remember, this requires .NET 4.

See the default "HowToUse.htm" and the "tasks.xml" file for help on getting started. The example task file notifies you if your external IP address changes.

Let me know if you find any bugs are have a feature wish!

Download here (just three files and no install to perform)

Saturday, August 7, 2010

Favorite Visual Studio 2010 Extensions

My favorite extensions for Visual Studio 2010...

Productivity Power Tools
If you are not using this, you have start! This has got all kinds of great extensions that really make your coding experience better.

AutoScroller
So I can click the middle mouse button and perform auto-scrolling.

Using HTTPS for WCF in Windows Service

These are instructions on how to use HTTPS in a Windows Service application hosting a WCF web service. The steps are a consolidation of information provided by Microsoft at:
http://msdn.microsoft.com/en-us/library/ms733791.aspx

I've tried to keep this as simple as possible.
  1. Set the endpoint of your application to HTTPS (i.e. your app.config file). Note that if you are going to use a root certificate that is for your COMPUTER, your endpoint will need to match your computer name…not “localhost”. Example:
    https://mycomputername:9010/mywebservice
  2. Verify HTTPS is not already configured by viewing ports configured for HTTPS (admin privs required):
    C:> netsh http show sslcert
  3. Generate an application guid; any guid will do. This can be done from a computer with Visual Studio tools installed. Example:
    C:> uuidgen
    429d0213-340b-44db-991e-1c0c1ed3d91f
  4. Find the thumbprint value for a machine/computer certificate in Personal store on local machine. Remove the spaces from the thumbprint. Example:
    b41dad508c2025eabe10f7d88b2c9a66983f950d
  5. Register the certificate for whatever port you want (any IP address=0.0.0.0), using the thumbprint and guid (admin privs):
    C:> netsh http add sslcert ipport=0.0.0.0:9010 certhash=b51dad508c2025eabe10f7d88b2c9a66983f950d appid={429d0213-340b-44db-991e-1c0c1ed3d91f}
  6. Verify the port is configured for HTTPS (admin privs):
    C:> netsh http show sslcert
  7. To remove HTTPS for a port use the following:
    C:> Netsh http delete sslcert ipport=0.0.0.0:9010

Tuesday, July 27, 2010

AnkhSVN - Subversion Support for Visual Studio

I've started using AnkhSVN for Visual Studio 2010 on some of my hobby projects and have been quite happy with it. You'll still need base SVN to create and manage your repositories, but I'd recommend AnkhSVN!

You can download it here.
http://ankhsvn.open.collab.net/

AnkSVN integrates nicely with Beyond Compare!

Monday, July 19, 2010

Entity Framework: How to log generated SQL in ASP.NET

If you want to log/view the generated T-SQL from your Entity Framework context instances to the output window in Visual Studio create a TextWriter derivation and use it like so:

using (MyEntityContext db = new MyEntityContext())
{
  db.Log = new OutputDebugWriter();
  ...
}

class OutputDebugWriter : System.IO.TextWriter
{
   public override void Write(char[] buffer, int index, int count)
   {
      System.Diagnostics.Debug.Write(new string(buffer, index, count));
   }

   public override void Write(string value)
   {
      System.Diagnostics.Debug.Write(value);
   }

   public override Encoding Encoding
   {
      get { return System.Text.Encoding.Default; }
   }
}

Sunday, June 20, 2010

Wake-on-LAN using C#

I recently set my personal computer to sleep after 30 minutes of inactivity. This seemed reasonable since I was normally only on the computer for a few hours a day.

I quickly realized that when I tried to remote desktop into it, if the computer was asleep it wouldn't connect (duh). I then modified the network interface settings to Wake-on-LAN and enhanced the security a bit by only waking on a "magic packet".

Then I wrote a interface where I can visit a web page and send the "magic packet" to my computer in order to wake it up. I won't go into the whole interface, but the code below demonstrates how to send the "magic packet" from C#. See the wiki article on details about what the "magic packet" is:

http://en.wikipedia.org/wiki/Wake-on-LAN

Also, don't forget to open any inbound or outbound ports on your firewall!

private void SendMagicPacket(string destinationHost, int destinationPort)
{
   // the header frame of 6 bytes of 255
   List<byte> datagram = new List<byte> { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

   // load the mac address (for demo purposes, set it to zeros)
   byte[] macAddress = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

   // 16 sequences of the MAC address
   for (int i = 0; i < 16; ++i)
   {
      datagram.AddRange(macAddress);
   }

   //
   // you don't have to do both below, but both are shown
   //

   // send directly to an IP address
   using (UdpClient client = new UdpClient())
   {
      client.Connect(destinationHost, destinationPort);
      client.Send(datagram.ToArray(), datagram.Count);
   }

   // broadcast it
   using (UdpClient client = new UdpClient())
   {
      client.Connect(IPAddress.Broadcast, destinationPort);
      client.Send(datagram.ToArray(), datagram.Count);
   }
}

Friday, June 18, 2010

Global.asax and precompiled web sites (aspnet_compiler.exe)

I recently deployed a precompiled VS 2010 (.NET 4) website using the aspnet_compiler. For the most part the site would start, but certain things would cause an exception when accessing objects in the Application object (which are initialized in the Application_Start of Global.asax.cs).

It turns out the issue was I didn't deploy the "precompiledApp.config" file that had been generated. For whatever reason, if you don't deploy this file, one of the things that occurs is the code of your Global.asax.cs isn't executed.

Lesson learned...always deploy the precompiledApp.config file.

Sunday, June 13, 2010

Visual Studio 2010 Pro Power Tools

I recently installed the Microsoft VS 2010 Pro Power Tools. You won't be disappointed in the many cool things it adds to Visual Studio 2010.

Visit Microsoft here to download.

Just a few of the items I really like:
  • Totally new window/tab interface with color-coding and sorting
  • Current line highlighting (finally!)
  • Move current line up or down with Alt-Up/Down arrow
  • Triple-click to select entire line
  • Syntax highlighting in method intellisense

Definitely download and give this a whirl! You won't be disappointed.

Sunday, March 7, 2010

SQL: Inserting a row column based on existing sequence number

Recently I needed to insert a row into a Microsoft SQL database that had a column value that had to be based on an increasing sequence number from other rows in the same table.

For example, each row in the table already might have a column called "SequenceNum" that represented an increasing number for each row. The sequence number would need to be specific to some other key in the table, for example, a "Message" column.

A MAX statement would need to be used to determine the next sequence number, but to ensure that two processes/threads don't each execute the SQL statement at the same time (and end up with the same SequenceNum), a lock would need to be used to isolate each process/thread. One possible SQL statement might be:

-- Assume you have a parameter for Message called @MessageKey
INSERT INTO TableA (SequenceNum, Message)
SELECT
ISNULL((SELECT MAX(SequenceNum) + 1 FROM TableA WITH (TABLOCKX) WHERE Message = @MessageKey), 1)
, @MessageKey

The ISNULL statement is used in case this is the first row inserted for a specific message.

Thursday, February 11, 2010

XML Utility: Remove comments and whitespace

Itching for that lil' utility to have your XML massaged a bit? This program will modify your XML by removing the whitespace and/or comments.

http://mathfactcafe.com/util/xmlstrip.aspx

Friday, February 5, 2010

WCF: appSettings values not seen in nested web.config files

I recently ran into an issue with an WCF application that had services in sub-folders AND each one had it's own web.config file. When the app pool was reloaded after a period of time, appSettings would appear to have vanished when using the standard ConfigurationManager to retrieve them.

The WCF services were derived from a common base class that used some appSettings values. I had to place each service in sub-folders so each service could have their own copy of the appSettings values used by the base class. There are other known problems with WCF and web.config files; these are resolved by adding the aspNetCompatibilityEnabled element to the ServiceModel section of the web.config. I had already done this to fix earlier issues.

This new problem seemed to occur after the app pool was reloaded after being idle. It is like the service didn't even see the web.config in the sub-folder.

To fix the issue I had to create a separate Configuration object and manually point it to use the web.config from the virtual path of the web service in the sub-folder. I created a tiny helper class to read the appSettings for the web services:
/// <summary>
/// This class is used to retreive appSettings values from a configuration file.  Special
/// support is provided when nested web.config files are used since pre .NET 4.0 are broken
/// in terms of nested web.config settings.
/// </summary>
public class WcfAppSettings
{
   private readonly Configuration _config;

   public WcfAppSettings()
   {
      VirtualPathExtension extension = OperationContext.Current.Host.Extensions.Find<VirtualPathExtension>();
      _config = WebConfigurationManager.OpenWebConfiguration(extension.VirtualPath);
   }

   public string this[string key]
   {
      get
      {
         return _config.AppSettings.Settings[key].Value;
      }
   }
}

Then I can then use the above class like:
WcfAppSettings appSettings = new WcfAppSettings();
string x = appSettings["MySettingKey"];

This appears to have fixed the issue. This is supposed to be fixed in .NET 4.0.

Wednesday, January 13, 2010

Word 2007 footnotes appearing on wrong page

I like to create a nice looking document when I'm tasked to do so. This includes using footnotes in Word 2007. I recently found that Word sometimes puts a footnote on the wrong page (especially if I have more than one footnote on a page). You can adjust the line spacing of the footnote to correct this (once I complete a document, I go back and modify all the footnotes even if they are on the correct page).
  1. Put your cursor in the footnote
  2. Modify the paragraph
  3. Set the Line Spacing to "Exactly" and "At" 10.5 pts which is a bit larger than the default footnote font size of 10 pts.
That should do it!

Friday, January 1, 2010

How do you handle configuration differences for environment (dev, QA, prod) using Visual Studio?

When executing a software application, there are always differences in configuration, depending on the environment. These configuration changes may include references to a database server, contact email addresses, or how exceptions are handled. I was recently doing some research on how Visual Studio 2010 handles this.

The question I would like to pose to folks is:

"What is your thoughts and/or model for building and deployment of the software bits? How do you use Visual Studio or other tools to build and deploy a "kit" to an environment?"

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...