Archive for the ‘.net’ category

Use of the ‘@’ in C# code

September 3rd, 2008

The most common use of the ‘@’ is escape character for strings that contain backslashes in them [\]. So as things like code below is possible.

   1: string s = @"c:\windows\system32\";
   2: string s = @"this will retain my \r\n and not change to a line break";

 

But another usage is as an prefix for C# keywords.  In the code below you will notice that the keywords class static and bool are prefixed with the @ prefix.

   1: public class @class
   2: {
   3:     public static void @static(bool @bool)
   4:     {
   5:         if (@bool)
   6:             System.Console.WriteLine("true");
   7:         else
   8:             System.Console.WriteLine("false");
   9:     }
  10: }
  11: public class Class1
  12: {
  13:     [STAThread]
  14:     public static void Main()
  15:     {
  16:         cl\u0061ss.st\u0061tic(true);
  17:         @class.@static(false);
  18:         //class.static(true); //will not work 
  19:     }
  20: }

 

What this also enables is a scenario like the one below, which I do not like.

   1: public class @class
   2: {
   3:     public static void MyCoolMethod(bool @theBoolValue)
   4:     {
   5:         if (theBoolValue)
   6:             System.Console.WriteLine("true");
   7:         else
   8:             System.Console.WriteLine("false");
   9:     }
  10: }
  11: public class Class1
  12: {
  13:     [STAThread]
  14:     public static void Main()
  15:     {
  16:         cl\u0061ss.MyCoolMethod(true);
  17:         @class.MyCoolMethod(false);
  18:     }
  19: }

Spot the difference? In the method signature of MyCoolMethod the boolean parameter has the @ prefix however in the code below where the value of the boolean is being interrogated I have skipped using the identifier. This code will however work exactly the same. The reason for is simple

The identifiers are the same if ‘@’ prefix is removed when used, therefore @theBooleanValue and theBooleanValue are same

To quote

Two identifiers are considered the same if they are identical after the following transformations are applied, in order:

  • The prefix "@", if used, is removed.
  • Each unicode-escape-sequence is transformed into its corresponding Unicode character.
  • Any formatting-characters are removed

 

Most importantly the general advice on using the @ prefix on words that are not keywords  is NOT to use it. And having seen it in used in code have an instant distaste for it. I wonder if FxCop has a rule for checking the usage of the @ prefix for non keywords in identifiers?

 

Technorati Tags: ,,

Service Broker C# Wrapper Interface and Transactions

August 16th, 2008

Service Broker has a really good C# wrapper interface that comes part of the samples on Codeplex. If you need to work with service broker objects in the managed world then I would recommend using the interface from the .

Most samples I have seen demonstrate communicating within a single database, and hence use the SqlTransaction Class The code below is an example of sending a message to a SSB Service  in a SqlTransaction.

   1: private void SendMsgToSSB()
   2: {
   3:     SqlConnection conn = null;
   4:     SqlTransaction tran = null;
   5:     Conversation dialog = null;
   6:     Service client = null;
   7:     string connString = "Persist Security Info = False; Integrated Security = True; Initial Catalog = MyServiceBrokerDB; Data Source = .; Connect Timeout = 30;"
   8:     try
   9:     {
  10:         conn = new SqlConnection(connString);
  11:         conn.Open();
  12:  
  13:         // Begin a transaction
  14:         tran = conn.BeginTransaction();
  15:  
  16:         // Create a service object
  17:         client = new Service("MyCoolService", conn, tran);
  18:         client.FetchSize = 1;
  19:  
  20:         // Begin a dialog with the MyCoolService
  21:         dialog = client.BeginDialog(
  22:             "MyCoolServiceTarget", null, "DEFAULT",
  23:             TimeSpan.FromMinutes(1), false, conn, tran);
  24:  
  25:         // Create request message
  26:         string outgoingBody = "my really cool msg that broker understands";
  27:         Message request = new Message("DEFAULT",
  28:                                       new MemoryStream(Encoding.UTF8.GetBytes(outgoingBody)));
  29:  
  30:         // Send the message to the service
  31:         dialog.Send(request, conn, tran);
  32:  
  33:         dialog.End(conn, tran);
  34:         tran.Commit(); 
  35:     }
  36:     catch (ServiceException svcEx)
  37:     {//deal with this pesky service exceptions
  38:     }
  39:     finally
  40:     {//clean up here close connections etc.
  41:     }
  42: }

But in scenarios where the transaction needs to be elevated from a lightweight transaction to one that needs the aid of the DTC the SqlTransaction object is not going to cut it for you.

With a simple change (in bold and italicized) you can then support enlisting in a Distributed Transaction.

   1: public void SendMsgToSSB()
   2: {
   3:     SqlConnection conn = null;
   4:     Conversation dialog = null;
   5:     Service client = null;
   6:     string ConnectionString = "Persist Security Info = False; Integrated Security = True; Initial Catalog = MyServiceBrokerDB; Data Source = .; Connect Timeout = 30;";
   7:     try
   8:     {
   9:         conn = new SqlConnection(ConnectionString);
  10:         if (conn.State != ConnectionState.Open)
  11:         {
  12:             conn.Open();
  13:         }
  14:         conn.EnlistTransaction(Transaction.Current);
  15:  
  16:         // Create a service object
  17:         client = new Service("MyCoolService", conn, null);
  18:         client.FetchSize = 1;
  19:  
  20:         // Begin a dialog with the MyCoolService
  21:         dialog = client.BeginDialog(
  22:             "MyCoolServiceTarget", null, "DEFAULT",
  23:             TimeSpan.FromMinutes(1), false, conn, null);
  24:  
  25:         // Create request message
  26:         string outgoingBody = "my really cool msg that broker understands";
  27:         Message request = new Message("DEFAULT",
  28:                                       new MemoryStream(Encoding.UTF8.GetBytes(outgoingBody)));
  29:  
  30:         dialog.Send(request, conn, null);
  31:         dialog.End(conn, null);
  32:     }
  33:     catch (ServiceException ex)
  34:     { //deal with the exception
  35:     }
  36:     finally
  37:     { //clean up
  38:     }
  39: }

 

Again this code has a small issue what about if there is no Transaction available then sending a message without a transaction could be a bad thing. With one more change its ready to support both scenarios.

   1: public void SendMsgToSSB()
   2:   {   SqlTransaction tran = null;
   3:       SqlConnection conn = null;
   4:       Conversation dialog = null;
   5:       Service client = null;
   6:       string ConnectionString = "Persist Security Info = False; Integrated Security = True; Initial Catalog = MyServiceBrokerDB; Data Source = .; Connect Timeout = 30;";
   7:       try
   8:       {
   9:           conn = new SqlConnection(ConnectionString);
  10:           if (conn.State != ConnectionState.Open)
  11:           {
  12:               conn.Open();
  13:           }
  14:           if (Transaction.Current != null)
  15:           {
  16:               conn.EnlistTransaction(Transaction.Current);
  17:           }
  18:           else
  19:           {
  20:               tran = conn.BeginTransaction();
  21:           }
  22:  
  23:           // Create a service object
  24:           client = new Service("MyCoolService", conn, null);
  25:           client.FetchSize = 1;
  26:  
  27:           // Begin a dialog with the MyCoolService
  28:           dialog = client.BeginDialog(
  29:               "MyCoolServiceTarget", null, "DEFAULT",
  30:               TimeSpan.FromMinutes(1), false, conn, null);
  31:  
  32:           // Create request message
  33:           string outgoingBody = "my really cool msg that broker understands";
  34:           Message request = new Message("DEFAULT",
  35:                                         new MemoryStream(Encoding.UTF8.GetBytes(outgoingBody)));
  36:  
  37:           dialog.Send(request, conn, null);
  38:           dialog.End(conn, null);
  39:           if (tran != null)
  40:           {
  41:               tran.Commit();
  42:           }
  43:       }
  44:       catch (ServiceException ex)
  45:       { //deal with the exception
  46:       }
  47:       finally
  48:       { //clean up 
  49:       }
  50:   }

 

I have also been making a few changes to the interface that I intend to publish shortly.

Windows Forms Controls for Free

August 6th, 2008

While working on a client project earlier this year we used a free suite of controls from called Krypton Toolkit. This toolkit served us really well to provide a consistent UX. One of my favorite features of this toolkit was the ButtonSpecs which could be added to almost every other control so that we could have text boxes with embedded buttons etc. How does this help you ask or why does it matter. Well if your like me, totally clueless on how to deal with resizing docking and anchoring, you will love ButtonSpecs

 

The other benefits of ButtonSpecs are for context menus, validation, lookups and other such things.

So if your doing windows forms development and are in need of a consistent UX for nix you cant go past the Component Factory’s offerings.

Additionally if your a MVP or own a blog with significant subscribers then you will be able to get the Phil Wright is giving away the entire Component Factory suite for free for you.

 

Technorati Tags: ,,,

Joining Simon on the WPF quest

August 2nd, 2008

As Simon mentioned in his last post he felt that it was time to get started on learning WPF, I have decided to join him on the quest. So as of today I will be assisting him in developing the Point Case Estimation application as an XBAP.

Having used XAML in my last project I am sure that seeing the following will not freak me out too much

   1: <Path x:Name="DiamondShape"
   2:       Data="F1 M 256,32L 352,32L 416,192L 352,352L 256,352L 192,192L 256,32 Z "
   3:       Opacity="0.9"  Stretch="Fill"
   4:       Stroke="#FF2A8117"
   5:       Fill="White" >
   6: </Path>

Can anyone actually tell me what “F1 M 256,32L 352,32L 416,192L 352,352L 256,352L 192,192L 256,32 Z “ actually means without a some sort of reference guide? Maybe Chris Sells might be able to help me much like he did with Scott Hanselman

I guess that is the ultimate challenge.

Technorati Tags: ,

Using the CLR on SQL Server 2005 with 4GB Ram or More

July 14th, 2008

For most people using SQL Server CLR is not an issue however when you have more that 4GB or more of memory, the CLR does not just work.

Enter the –g startup switch, You can read more about the SQL Server 2005 startup options to get the fine detail. In order to make the required changes follow these steps

1.) Launch SQL Server Configuration Manger

image

2.) Under Sql Server 2005 Services choose the instance of SQL Server that you are targeting for the change and right click on it and select Properties.

3.) Move to the Advanced Tab and locate the Startup Parameters

image

4.) Add the –g option to the end by first closing the previous parameter with a ‘;’ then –g, not adding the ‘;’ to the end of the previous parameter will cause SQL server to fail on restart

image

5.) Click Apply /OK and restart the service. When the service restarts you should now have SQL CLR on your machine. A simple Hello World CLR stored proc should do tell you if your in business or not.

 

Vista UAC Visual Studio and Run As Administrator Gotcha’s

June 24th, 2008

Today one of my colleagues was working on piece of code that would turn a given mapped drive to full UNC path. The code to do implement the functionality is very simple and can be done in a variety of ways ranging from Win32 API to WMI (via System.Management) Below is a snippet of the code that was used.

   1: public static string GetUNCPath(string originalPath)
   2: {
   3:     string returnVal = originalPath;
   4:     foreach (DriveInfo drive in System.IO.DriveInfo.GetDrives())
   5:     {
   6:         if (Path.GetPathRoot(originalPath).ToLower().StartsWith(drive.RootDirectory.FullName.ToLower()))
   7:         {
   8:             if (drive.DriveType == DriveType.Network)
   9:             {
  10:                 System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(
  11:                     @"\\.\root\cimv2", "Select * From Win32_LogicalDisk Where DriveType = 4");
  12:  
  13:                 foreach (System.Management.ManagementObject obj in searcher.Get())
  14:                 {
  15:                     if (obj["DeviceID"].ToString().ToLower().StartsWith(drive.Name.ToLower().Substring(0, 2)))
  16:                     {
  17:                         returnVal = Path.Combine(obj["ProviderName"].ToString(),
  18:                             originalPath.ToLower().Replace(drive.Name.ToLower(), string.Empty));
  19:                         break;
  20:                     }
  21:                 }
  22:             }
  23:             else if (drive.DriveType == DriveType.Fixed)
  24:             {
  25:                 Console.WriteLine("The drive is not a network drive");
  26:             }
  27:             break;
  28:         }
  29:     }
  30:     return returnVal;
  31: }

 

This code can easily be tested using , a great tool that is pretty much a must have for any developer.  I have attached the code file that can be used with snippet compiler all that you will need to do is to change the mapped path that is passed into the method and  a reference to System.Management.dll in Snippet Compiler. You can then run the code with UAC turned on with Run As Administrator or just a normal use to see the difference.

When running this code on Windows Vista with UAC turned on and Visual Studio 2005 or 2008 in administrator mode will provide different results. While getting different results is the correct behavior, unless you are fully aware of the various areas that running applications in a secondary login has  impact on the notion of running your application in a different user context can cause a lot of wasted hours.

As a general rule when debugging code or running code on a machine that has UAC enabled my advice would be to spend a quick second to check if UAC has a part to play in the puzzle.

Plug-in, Add-in and Extension’s – The Managed Addin Framework

June 15th, 2008

The use of plug-ins or add-ins are a common way of extending any application, most people do not even know when they are using an extension.

I am currently using an add-in framework in a project that I am working on and It has proven its self invaluable. The framework I speak of here is baked right into the .net Framework from 3.5, The Managed Add-in Framework being fairly new and has a few glaring issues that need to be addressed like the naming conventions and directory structure that must be adhered to avoid making the entire framework come crashing down.

In order to use the framework easily you will need to download the which is the latest release at the time of writing, please check the or .

While there are annoyances with the state of its development, some of the features you get from using it out of the box are nice. The ability to launch add-ins either cross process or cross domain is great.

The add-in framework uses Adapters on either site of the add-in contract or isolation boundary as proxies. This is some of the magic that also enables efficient version control of the add-ins without the changing or breaking the add-ins.

 

image

For Additional information I would strongly recommend checking out these two videos

also further reading relating to the or MAF look here.