C#

Selected posts on CLR, threading, Internationalization and WPF

I have been professionally working in the software industry for over 9 years but I am relatively new to the blogging community. I have only started to blog around 5 months ago. I have selected some of my previous posts which I liked. Please find the links below

CLR Fun Stuff: How is my C# code converted into machine instructions?
This post decribes the process of MSIL being converted to binary instruction bt the JIT compiler.

WeakReference: GC knows the Best
A basic look at the Weak Reference class which helps to re-aquire data left for garbage collection.

Multi-core CPU Caching: What is volatile?
What is the impact of the volatile keyword in the world of multi-cored CPUs

Dll heaven: Executing multiple versions of the same assembly
How can you execute code from different versions of an assembly in a single process.

Spider's Web: Spawning threads in .NET, The Basics
A basic look at threading. It was going to be 1st part of a 5 part series, but it was discontinued as there was a good free e-book available on .NET threading.

Basic WPF: Stylize standard tabs into Aqua Gel
How can you change the look of the standard controls with styles in WPF

Fun with Generics: Using constraints to limit Generics applicability using the 'where' keyword
A less used but powerful architecture tool, type limiting in generics

Internationalization: Creating a custom culture
How can you add support for your language/culture if .NET does not have built in support for the language like my language ' Bangla'

kick it on DotNetKicks.com

SQLMetal woes: No sqlmetal.exe with VS 2008 Team Edition

Even despite all the performance issues I wanted to use LINQ queries for one of my pet projects. One of the design goals was to use Sql Server Compact edition 3.5 so that I get to use a file as a database and also that I can port the data access and code logic to compact framework so that it can be used with Windows Mobile devices. Using compact edition of sql server 2005 is kinda like using a comptible microsoft made firebird sql database. A few days ago I reinstalled my OS and wanted to try the Visual Studio 2008 team edition trial and that is when all the trouble started.

First, the linq to sql class generator SqlMetal.exe was nowhere to be found. It seemed that the Visual Studio 2008 Team Edition trial did not come with the SqlMetal.exe. Infact the folder 'C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\' where the executable resides with other executables is empty. But I have changes to my database schema and did not want to hand write the changes.

Then I tried generation by dragging the sql server compact dbatabase tables onto the linq to sql (dbml) designer, but got the message that "The selected object(s) use an unsupported data provider". This is annoying. Tomorrow I will try to download the Visual C# 2008 Express edition and install that to get a copy of SqlMetal.exe. I wish Microsoft were more careful with what content they have in their DVDs.


Strange C# 3.0 Feature: Partial Methods ... ... What ?!!

At first it was hard to believe or even think up of the concept of what might be a partial method. How can you have a partial method? How does one write it ... by omitting some code? Looks like the C# team have given birth to strange new language feature called partial methods.

Before I go any further there are 2 rules regarding partial methods that must be said.

1. Partial methods can only defined in a partial class

2. Partial method return type must be void and cannot contain any out parameter

Perhaps the naming of partial method has been wrong. It would have been better to call it skeleton method. A partial method is a method that can be called in a function and the signature of the function may be defined but may not have any body. It is like defining a method signature which we may implement later.

For example lets assume we have a class called Foo which has a method called do something and looks like code below

partial class Foo
{
    public void DoSomething(string someParam)
    {            
        // Do something important here ...some logic
        CallSomeMethodSomewhere(param);
    }
}

It is visible that the we are going to do something important inside the method. While we are writing this method we may decide that we want to log the input parameters but at the time we do not want to worry about the logging logic right now and and would rather worry about the method logic we are writing. Now this is where we might want to write a partial method. Let try to how a partial method is declared and used.

partial class Foo
{
    public void DoSomething(string someParam)
    {            
        // Log the input
        Log("DoSomething", someParam);
        // Do something important here
        CallSomeMethodSomewhere(param);
    }

    partial void Log(string functionName, string parameters); }

Now this is a perfectly valid code and will show no compilation errors. Since we have not yet defined the body of the function "Log" the C# 3.0 compiler will just ignore our function call. So a partial method lets us define a method signature and call it even when there is no implementation. Also compiler does not emit any IL for the call that we made. So the code shown below is fully ignored.

Log("DoSomething", someParam); 

Now after we are done with implementing out class, we have decided to write the function
and provide a function body. So now our code looks like this ...

partial class Foo
{     public void DoSomething(string someParam)     {                     // Log the input
        Log("DoSomething", someParam);         // Do something important here
        CallSomeMethodSomewhere(param)     }

    private void Log(string functionName, string parameters)     {
        Console.WriteLine(functionName + ":" + parameters);     }
}

So this way we are not changing the original code at all rather providing the implementation of the function later. One use of the function might be to write functions in you class and call them, while someone else may provide the concrete implementation in a function later. This will allow two persons co-ordinate and use virtual placeholders for code. This is a cleaner approach to write to-do functions later rather than providing a method body and throwing not implemented exception later.


Well ... anyway I found this to be a strange feature of C# 3.0. What did you think?

kick it on DotNetKicks.com


Timesaver: Awesome New C# Property Syntax Shortcut

I just could not believe this! No, this cannot be, how did Microsoft know that I wanted this feature!

Well ... today I discovered this new shortcut writing properties in C# 3.0 using Visual Studio (actually I was using the C# Express edition). Lets say we want to have a class called person who has age and name. In C# 3.0 there is no explicit need to declare a variable and write get and set methods for the property.

I could just declare the class like this ...

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

And then use it in code like this

 Person p = new Person();
p.Name = "Me";
p.Age = 31;

This saves so much time. I just love this ...awesome way to define properties. Well I could also use the named parameters style code like this ...

Person p = new Person() { Name = "Me", Age = 31 };

C# has just gone crazy ...

How does this work?

Well if I try to decompile the code using Reflector then we would see that we have this following code for the class Person

internal class Person
{
    // Fields
    [CompilerGenerated]
    private int <Age>k__BackingField;
    [CompilerGenerated]
    private string <Name>k__BackingField;

    // Methods
    public Person();

    // Properties
    public int Age { [CompilerGenerated] get; [CompilerGenerated] set; }
    public string Name { [CompilerGenerated] get; [CompilerGenerated] set; }
}

Looks the like the following code was generated by the compiler ... I am still not clear how the "<PropertyName>k__BackingField" expression is used in sync with the compiler generated attribute, but I am happy that I have such a shortcut.

kick it on DotNetKicks.com

.NET Basics : Explicit vs Implicit Interface Implementation

Nearly all of us know that we can implement an interface in 2 ways, one is explicit and the other one is implicit. In case of the implicit implementation the interface methods stay public and in explicit implementation the methods stay private in C#. Let me show a simple example

interface ICar
{
   void Start();
}

Now this method can be implemented in two ways, the first one is an example of the implicit implementation

class BMW : ICar
{
    public void Start()
    {
        // write code to start the BMW
    }
}

See the method is public, it can also be protected as well. Now the explicit implementation should look like this

class BMW : ICar
{
    void ICar.Start()
    {
        // write code to start the BMW
    }
}

As you can see there is no public or private keyword present for explicit implementation, and if we try to put a access modifier like public or private then we would get a compiler error. However the C# compiler will make this method private.

Well, except for private and public is there any other significance?

No Virtual

Well yes, there is. An explicit method implementation cannot be virtual. So we cannot override the method implementation in a child class. If we had declared the method virtual in the implicit implementation like the code below then we would have been able to override in a subclass.

public virtual void Start();

So you can see the that if we had a specific implementation of BMW that needed a different way to start then we would be able to override the virtual function and call it.

No direct access for Derived class

Also the derived class cannot call the method directly, we cannot call base.Start() in a child class. We would need to cast it to the interface. So a derived class has to write code like this for explicit implementation.

ICar car = this;
car.Start();

No abstract Implementation

I almost forgot another issue, which is ... we cannot use explicit implementation in an abstract form. If we had defined the class BMW an abstract class we could have left the implementation abstract for a derived class to implement like this

abstract void ICar.Start();

But with explicit implementation we cannot delay the implementation in a later derived class.

Hmm ... when is explicit implementation a must?

Well, lets say we had another interface that has the same method with the same signature and then it could be a problem. Let see this example below

interface IBoat
{
    void Start();
}

Now lets assume we have a amphibian car than can run in both land and water but engine for water and land are different so it would require two different methods to start. Since the implicit implementation can have one method the same name in both cases if IBoat and ICar the same method would be called.

class MyAmphibianCar : ICar, IBoat
{
    public void Start()
    {
        // write code to start the BMW
    }
}

This is a problem since we want to have 2 different code to start the engine. So we would have to go to implicit implementation and write code like this

class BMW : ICar, IBoat
{
    void ICar.Start()
    {
        // write code to start the BMW
    }

    void IBoat.Start()
    {
        // write code to start the BMW
    }
}

Now our problem is solved and we can use two different codes for the two implementations.

When is Explicit Implementation a Problem?

If we use explicitly implement a value type then if we need to access the interface methods then we would have to cast the value type to the interface type which would cause boxing and may hinder performance.

kick it on DotNetKicks.com

Controlling Windows Firewall using C# via COM Interop

Firewall Windows firewall is the built in firewall that ships with Windows XP and Windows Vista. This firewall can be controlled from any .NET language via COM interop. The windows firewall UI is a little clumsy to work with so anyone can make his own frontend using any .NET based language.

Setting up

Start by adding a reference to the COM dll that provides the functionality to control the windows firewall. The filename is hnetcfg.dll which can be found at the system32 folder inside windows. So add the file to your C# project.

File location: \Windows\System32\hnetcfg.dll
Then add these using statements to import the COM Objects

using NATUPNPLib;
using NETCONLib;
using NetFwTypeLib;

Obtaining a reference to the firewall manager

The first step toward controlling the windows firewall is to obtain a reference to the firewall manager class. For this we will use the CLSID of the class which is

   {304CE942-6E39-40D8-943A-B913C40C9CD4}

So our code looks like this

private const string CLSID_FIREWALL_MANAGER = 
      "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
    Type objectType = Type.GetTypeFromCLSID(
          new Guid(CLSID_FIREWALL_MANAGER));
    return Activator.CreateInstance(objectType)
          as NetFwTypeLib.INetFwMgr;
}

The above code shows how to get a reference to the firewall manager

Check if the firewall is turned on

If the firewall is not turned we should look into the current profile and find out then turn it on.

INetFwMgr manager = GetFirewallManager();
bool isFirewallEnabled =
    manager.LocalPolicy.CurrentProfile.FirewallEnabled;
if (isFirewallEnabled==false)
    manager.LocalPolicy.CurrentProfile.FirewallEnabled=true;

Give full trust to your executable

If we want to authorize some application with full trust then we need to create a FirewallAuthorizedApplication (INetFwAuthorizedApplication) object and add it to the authorized application list.

// ProgID for the AuthorizedApplication object
private const string PROGID_AUTHORIZED_APPLICATION =
    "HNetCfg.FwAuthorizedApplication";

public bool AuthorizeApplication(string title, string applicationPath,
    NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion )
{   
  // Create the type from prog id
  Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
  INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
      as INetFwAuthorizedApplication;
  auth.Name  = title;
  auth.ProcessImageFileName = applicationPath;
  auth.Scope = scope;
  auth.IpVersion = ipVersion;
  auth.Enabled = true;

  INetFwMgr manager = GetFirewallManager();
  try
  {
    manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
  }
  catch (Exception ex)
  {
    return false;
  }
  return true;
}

The above code is for a function that adds an authorized application. Let see the use by authorizing notepad full internet access!

AuthorizeApplication ("Notepad", @"C:\Windows\Notepad.exe", 
                NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
                NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY)

Walla! Now notepad has internet access.

Opening a Port Globally

Sometimes we may want to open a port for any application no matter what. Windows Firewall can be instructed to open a port globally for all applications by adding a port to the globally open ports list. Let try to write a function that opens up a port globally ...

private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";
public bool GloballyOpenPort(string title, int portNo,
    NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol,
    NET_FW_IP_VERSION_ ipVersion)
{
  Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
  INetFwOpenPort port = Activator.CreateInstance(type)
      as INetFwOpenPort;
  port.Name = title;
  port.Port = portNo;
  port.Scope = scope;
  port.Protocol = protocol;
  port.IpVersion = ipVersion;

  INetFwMgr manager = GetFirewallManagerCached();
  try
  {
    manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);
  }
  catch (Exception ex)
  {
    return false;
  }
  return true }

Going further

Since we have demonstrated how to access the windows firewall manager and control its various aspects, now anyone can explore the Windows Fireall API and do a lot more that presented in this post. I would like to point to several MSDN references for further read.

MSDN Windows Firewall Reference
Loads of VBScript samples to do various things, you can translate the code to C#

Since windows firewall can be controlled via COM, any application running in your system can enable/disable or modify the firewall settings. I would suggest to use a third party firewall. For real security geek I would recommend Outpost Firewall ( I use the Outpost Security Suite) as the paid firewall and Comodo Personal Firewall as the best free firewall. Both these firewalls are way superior to other available firewalls.

kick it on DotNetKicks.com

Fun with Generics: Using constraints to limit Generics applicability using the 'where' keyword

Generics was introduced in .NET with version 2.0. One feature that is very useful but rarely used is the constraints for Generics. Constraints allows the developer to limit the type that is used instead of any object. Let us try to understand this with a sample. Lets assume that we have a in memory cache class for a certain type of object which we will simulate in the sample using a dictionary. Lets look at the code sample

class MyCache<K, T>
{
    Dictionary<K, T> _store = new Dictionary<K ,T>();
    void CacheItem(K key, T obj)
    {
        _store[key] = obj;
    }

    T GetFromCache (K key)
    {
        if (_store.ContainsKey(key))
            return _store[key];
        else
            return default(T);
    }
}

Generics constraint for Reference Type

The above class looks pretty simple and easy to use. Now lets assume that we want to cache classes that are reference types and this MyCache class should not be use with any struct or value types. How can we do that? Here is how ...

class MyCache<K, T> where T: class

This 'where' keyword is telling the compiler that MyCache type can by applied on the reference types only.

Generics constraint for Value Type

Similarly we would use the following syntax for structs

class MyCache<K, T> where T: struct

Generics constraint for a specific interface

What if we have a specific requirement for the type to be disposable? For example when cache is disposed we want all the items that are in  the cache to be disposed as well. If we had no constraints in MyCahe class then we would have to write

public void Dispose()
{
    foreach (K key in _store.Keys)
    {
        IDisposable d = _store[key] as IDisposable;
        if (d != null) d.Dispose();
    }
}

Observe that we are casting to disposable type and then disposing the object. What if someone had used a type that does not implement IDisposable? Lets try to impose a constraint that says the the type T must be disposable.

class MyCache<K, T> : IDisposable where T:IDisposable

... and our dispose code should look like this ...

public void Dispose()
{
    foreach (K key in _store.Keys)
    {
        _store[key].Dispose();
    }
}

Please observe that since we have specified that the type T is a IDisposable type we can directly call the Dispose method.

Generics constraint on multiple types

Now suppose that I have a class named EntityBase that we are using for all our entity classes and the functionality of the MyCache to apply to the entity classes only. How do we tell generics to restrict MyCache to classes that derive from EntityBase and implements IDisposable? This is how ...

class MyCache<K, T> : IDisposable 
      where T:EntityBase, IDisposable

In the above code we are saying the that the type T must be subclass of EntityBase class and must be disposable. Please note that we would also be able to call methods and properties of the EntotyBase class directly without explicit casting as we have already shown in the disposable example.

Generics constraint on multiple items

What if we wanted the the key to always a value type? Let try to add that to our definition.

class MyCache<K, T> : IDisposable 
      where K:struct
      where T:EntityBase, IDisposable

Specifying a default constructor

Sometimes we might want to write code like new T() to instantiate a variable of type T. This will not work if the class do not have a default constructor. In order to make sure that T has such a default constructor we would write ...

class MyCache<K, T> : IDisposable 
     where K:struct
     where T:EntityBase, IDisposable, new()

The new() keyword will make sure that the T has such a default constructor, otherwise it will not compile.

An interesting tip : Aliasing

We can also use aliases to use generic types in our classes. Sometimes too much generic expression makes the code look bad with lots of <> and <>. This can be avoided via aliasing. You can give a alias or name to a certain generic type and use it from the class. See example below

using StringQueue = System.Collections.Generic.Queue<string>;

Here we are making a generic Queue class bound with string to be named as StringQueue which later used in code like this ...

StringQueue queue = new StringQueue();
queue.Enqueue("Sometext");

Fun, isn't it?

The Last Word

Unfortunately the above feature of generics is usually overlooked and rarely used in code. Better OO design can result from using these features. Lets try to use this when we design object model in our daily life.

kick it on DotNetKicks.com


Profile your performance worries with DotTrace 3.0 profiler

We have a large database for the website back at work and also we have a high amount of disk IO and we were using the ASP.NET membership provider that comes built-in. We replaced the ASP.NET provider as it is not suited to a large scale application and has quite a lot of performance issues. For example it creates an anonymous user if you just hit the site ... which is true for even bots. Think of the amount of garbage user you can get with ASP.NET membership.

After deploying the performance improvement to the site we saw that the CPU usage to the site became 3 times higher than usual ... not much of an improvement ..eh! However from the changes made to the code it was obvious that there should not be higher CPU usage rather it should be low.

I downloaded a version of the DotTrace profile from Jetbrains. Its an amazing profiling tool. We have several web servers, I took one of the servers out of the load balancer. When you profile an ASP.NET app, the profile restarts the IIS. During that time we do not want the users to experience error or no page so its best to take the web server out of the load balancer. Turned on the profiler and then put the server back into the load balancer so that it can serve pages and encounters real life load. After a few minutes took a snapshot of the server. All this time CPU was high.

DotTrace is an amazing tool and it shows amount of time and the amount of calls and % for all methods and all methods called by your application.

Note: Some of the method names in the images are renamed or hidden for security and copyright reasons.

Img_1

As one can see that the process request is taking 8.8% time which is normal but Application_AuthenticateRequest is taking 3.3% which is very strange.

Investigation showed that a method used to identify cookies from domain is taking huge time (see below). The code uses regular expressions.

Img_2

Since our website calls itself internally from the server side from various requests generating a cookie for server side call should be wrong and this method validates if this is not a localhost call.

 

Then I investigated the code and found the following

private static bool IsValidDomainName(string inputString)
{
    System.Text.RegularExpressions.Regex regex =
    new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$",
    System.Text.RegularExpressions.RegexOptions.IgnoreCase |
    System.Text.RegularExpressions.RegexOptions.Compiled);

    return regex.IsMatch(inputString);
}


There are 2 things with this code. First of all this is a static function with a static expression validate with so the regex object can be static.

Second, the regex.IsMatch is a expensive function when it is in a area with high code coverage.

We just replaced this code with simple string matching and we our CPU just went down, see the web server CPU usage.

Bad_good_cpu

Click on the image to the high CPU usage vs after the applying the patch.

Dotrace can both CPU profile or memory profile an application and also have some cool views that you find bug fast.

It is evident that entry point of the request must me properly optimized as it called so many times. There is no chance for mistake for a code with huge coverage like that.

kick it on DotNetKicks.com

Interesting attributes in CompilerServices namespace

The namespace System.CompilerServices has a few useful classes that can be used by a developer even though he is not working on compilers.

SuppressIldasm Attribute

One interesting element could be to stop disassembling your code by using this attribute. This does not obfuscate your code code rather tells the ILDASM to not show your code when IL is being decompiled. This can be applied on an Assembly.

Example

Just add this line to your code.

[assembly: System.Runtime.CompilerServices.SuppressIldasm()]

StringFreezing Attribute

If you apply this attribute to the assembly then all the strings used within the assembly is frozen when native generation is used. This is useful of a performance hungry application that uses a lot of strings. Warning, be sure to apply this to the assemblies that do not require unloading as the assembly with this attribute cannot be unloaded.

Example

Just add this line to your code.

[assembly: System.Runtime.CompilerServices.StringFreezing()]

Just add this line to your code.

 

Technorati Tags: ,

Independent Thought

The web development increases the door towards internet global world. This internet world enhances the field of MBA and affiliate marketing line for companies. Different companies enhance their promotion and marketing by website design holding their product promotion. Different famous companies enhance small firms by introducing affiliate program for them. These companies have started their separate computer department specially working for web hosting services. Different services are provided other than web hosting and this include internet marketing solutions for the firms. Due to all these services through internet the field of web design development becomes very famous.


Hack .NET Framework : Use private classes to fulfill your need

Lutz Roeder's Reflector is the most useful .NET utility ever built. It has helped me many times in the past to browse through compiled code and use it correctly. Since it decompiles the code and shows the code inside, it is actually better than help files or any other form of documentation on any assembly. If you use the Reflector then you can find that .NET framework itself has many private utility classes built into it which are used by the public classes but as a developer we cannot use it. Reflector will let you find a lot of those classes which can be instantiated and used via Reflection.

Lets take the example of System.Security.Util is a private namespace in mscorlib which has a class called Hex. This class can encode and decode hexadecimal string. Since it is a reusable class we should use it when required rather than writing a new class. See the Hex class below in Reflector

Reflector_hiddenclass

Now this looks like a pretty useful class. But its private, how do we use it? In order to do so we can get hold of the private type via reflection like this:

    Type type = Type.GetType("System.Security.Util.Hex, mscorlib");

Then we need to get a hold of the method ( in this case the class is static so are its method ).

    MethodInfo
encodeHexString = type.GetMethod("EncodeHexString", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

We now have the method and all we need to do is to invoke it. Since the method is static it will not need any object as reference when invoked.

    List<object> parms = new List<object>();
    parms.Add( Encoding.ASCII.GetBytes("This is to be converted to hex"));

    string encoded = (string)encodeHexString.Invoke(null, parms.ToArray());

Here we have invoked the method of a private class in an assembly and got output from it. Ain't that nice!

In order to make things simpler you can write a wrapper class around and use it to instantiate and call the private classes or private  methods of any class.

This sample contains such a class and here is how easy it is to use it. In the next code block we are converting a string to hexadecimal format and then getting it back to original format using the private Hex class.

HiddenType wrapper = new HiddenType("System.Security.Util.Hex,mscorlib");

string originalString = "This is a string";

Console.WriteLine("Original string is \t: {0}", originalString);

byte[] bytes = Encoding.ASCII.GetBytes (originalString);

string encodedString = (string) wrapper.InvokeStaticFunction("EncodeHexString", bytes);

Console.WriteLine("Encoded string is \t: {0}", encodedString);

byte[] decodedBytes = (byte[]) wrapper.InvokeStaticFunction("DecodeHexString", encodedString);

string decodedString = Encoding.ASCII.GetString(decodedBytes);

Console.WriteLine("Decoded string is \t: {0}", decodedString);

The code sample can be downloaded below. Keep on reflecting ...

Download PrivateClassDemo.zip

Technorati Tags: , ,

kick it on DotNetKicks.com