Category Archives: .Net

.Net programming stuff/tips etc.


I have working on some reflection and CodeDom stuff in .net 2.0 . My requirement was to create  types at runtime by emitting in memory assemblies (i ll put the details later on) . At one place i encountered a naive and innocent looking function  Type.GetType(string) .  As i typed the method , intellisense popped in and suggested the usage of the method ” Get the Type with the specified name, performing a case-sensitive search.” (its in msdn), so i called  the method with  Type.GetType(“Font”) and to my amazement it returned. i was puzzled as  i was running a winform application and Font type is one of  important types  in winform apps.

I looked for the remarks section in msdn , it says  GetType method takes  a Type name and search for it in the current assembly or mscorlib, if you supply  Assembly Fully Qualified Name (AFQN), then it will load the assembly and search in it. i tried again by giving Typename, assembly name format , but i guess i made a mistake there, which led me to these pages

Type.GetType(string typeName) returns null !?  by  Haibo Lou
TypeName Grammar    by   Yiru

In summary , Type.AssemblyQualifiedName is the typename one should pass when calling Type.GetType(string) with public key token and culture. I think MS should update their documentation, so that API summary should state what it is expecting .

Advertisements 2005 ARrrghh!!

I have been using Visual Studio for a very long time as most of my development is targeted for windows platform (.net/win32). i have used VS6, Vs2002/2003 and VS2005. and i must say VS6 is the most superior of the 3, 🙂 , sorry if thats hurt , but i have my own reasons. Vs2005 is the one which disappointed me a lot ,

i would like to mention few of my concerns about VS2005, as i am using it these days. I have been using it for last one year.

The first thing you will notice about it is that it is incredibly slow , my machine is dual core intel 3 Ghz with 4 gb ram, scsi hdd, but still , startup loading is slow as snail, and if you command it load a solution with lots of projects( 10+ in my case) , it will let you stare on the blank screen for around 1-1.5 minutes. i am not looking for an IDE with ultra-lightening speed but this is too slow , 😦 , and if you have multiple solutions open in multiple IDE instances , then i can only pray for you. and did i mention PocketPC solution, that will make your pc crawl to death. Trust me.

ok File loading is a one time process. you can pass through it easily , when you come in the morning , just fire the VS and go fetch yourself a cup of coffee/tea , by the time you will be back the solution will be loaded , if not , try enjoying your drink with the solution loading.

next on the list is the Build /Debug cycle, the moment you start the build and there are lots of thing to build, the UI just dies and gets itself busy in building, it is no longer available to access menus, etc, and if you want to cancel the build then you should know the shortcut key Ctrl+Break, though you have to tap it repeatedly to get to the lucky moment. (btw msbuild is a nice addition, with lots of good features to customize your build. and its quite fast when used from command line 🙂 ) Again the Pocket PC support is something that should be revised , deploying and debugging a pocket pc app on an emulater is really painstaking and it seriously needs some revision.

btw there is a bug due to which VS hangs during debugging a PPC app , usually when  u hit a break point, though it does not happen frequently.

i have windows xp x64 version on my development machine, and i observed that sometimes while working with GUI controls on winform applications, the IDE crashes the os leading to BOSD, there might be some incompatiblities with the driver. i m not able to reproduce that bug, but it do happen a lot.

hmm, what next, refactoring support, well if u have ever used other refactoring tools , then u should know that VS’s refactoring support isn’t mature enough for their comparision. long time ago when i first started using vs2005 , i tried some refactoring features . i renamed one of my class, and the ide didn’t renamed the class file. 😦 , i had to rename the file manually.  i have used ReSharper for vs2003 and vs2005 both, and it is definitely a product you will love to have installed on your dev system, its a plugin for VS, with lots of cool features, and impressive  refactoring support. Might be , vs team left more advanced functionalities to be implemented by plug-in vendors.

Another thing that really motivated for this post is the SQL Editor, well you have to admit. that VS2005’s sql editor is pathetic. seriously, yesterday i have to update few tables on the data ,writing some queries, i got connected to sql server via server browser panel, and open a new query page, i wanted to write few queries on the same query page, and execute one at a time ,  but it wasn’t letting me to do so. The editor was trying to be a smart a$$ and parsing multiple queries into single query,  neither it was letting to comment using double single quote. It might be due to different writing style required in vs sql editor, i don’t know about that. But this is just hindering my productivity, that means, i have to spare some time looking for a solution to this, or get sql server client tools install on my machine. i dont like any of the solution. if vs is providing support for sql, it should do so properly or else no support :(. the later solution would lead to license issue.

this post might look like a vs bashing post, but seriously , vs is a great product, i love to see improvements in it, i use it on daily basis. it’s really a shame to fill such a great product with such preposterous issues only to ship it sooner. i think Vs2005 should be released atleast an year later , probably in Q2 ,2007. There are lots of great features which i haven’t used yet. i really appreciate the efforts of the VS team and hope some improvements in next version, probably something of the caliber of  vs6. 😉

btw there is a nice post on VS issues.



Rico Mariani’s articles collection

Rico Marini is a performance architect at Microsoft . he has written a lot about performance . Here you can find a compiled list of articles and papers by rico , these are really worth reading. His blog is also a great knowledge source for knowing your application inside out.



String.Format() made easy

          i have been browsing through the web as usual, and found some interesting articles regarding string.Format() . For a quick summary. string.format is similar to sprintf function from the world of C .you can put placeholders in the formatstring along with specifying the formatting of the data and then passes the data. it internally call the object.ToString method passing it the format string u just passed to it and prepares the final string for you .

placeholders are of the form {<argument index>[,<alignment>][:<formatString><zeros>]} alignment is specified as positive value for right justified and negative for left justified.

String.Format usually  performs better then concatenating different string together, due to the reason that during string concatenation ,intermediate strings are created and  also its more readable atleast to my. The only thing that ping me is in the case where there is a long list arguments so you will be counting each time to see what its format string is ,unless ur IDE aids you with some intellisense.

anways enjoy the two great links

String Formatting in C# by Steve Tibbett
.Net Format String 101    by Kathy Kam

Generic Comparer

well long time no c k here i m

some days ago i was working on my project , i felt a need to write a generic comparer, so i came up with this implementation, but the thing is that why i need this , have a look at my problem ,

i have some objects of different types, each type has a different set of properties, now i want to perform sorting and searching operation on the list of objects, the sorting and searching ke might be different at differetn times.

like we have a list of objects of type c1 widh p1 and p2 properties, i have 2 combos on my page each contains same list of objs, but sorted differently , one sorted on p1 and 2 sorted on p2, so what might be solution,

one possible solution might be that we impelement Icomparer for each properties of each type that we want to be sorted/searched ( I assume that we are going to use array.sort, array.Binarysearch wich requires IComparer object to perform the specified operation) , but that wuld be inefficient , infact, when new properties added to the type then we have to add new Icomparer implementations 😦 to much job for us 😛

so i came up wid this generic comparision ,

the idea is that we implement a single ICompareble impelemenation, and parametrizd it with the type of object that we are going to compare and the Property name on which the comparision is being performed . hold a default compare object, in compare method get the value of the property and compare it using default comparer, the default comparer will chk the type of value and perform comparision accordingly 🙂

Generic Comparer

here is the code


public class GenericComparer :IComparer


private PropertyInfo propertyInfo;

private Comparer comparer;

public PropertyInfo PropertyInfo




return this.propertyInfo;



private GenericComparer()



public GenericComparer(Type objectType, string comparisionProperty)




propertyInfo = objectType.GetProperty(comparisionProperty);

this.comparer = new Comparer(System.Globalization.CultureInfo.CurrentCulture);


catch (Exception ex)


throw new Exception(“Property ‘” + comparisionProperty + “‘ not found “+ex.Message);



public int Compare(object x, object y)


object valx= this.propertyInfo.GetValue(x,null);

object valy = this.propertyInfo.GetValue(y, null);

return this.comparer.Compare(valx, valy);





using this will be easier , a simple example ,


Class1 c = new Class1();

Class1 d = new Class1();

c.J = 5;

d.J = 2;

GenericComparer intComparer = new GenericComparer(typeof(Class1), “J”);


c.V = “C”;

d.V = “A”;

GenericComparer stringComparer = new GenericComparer(typeof(Class1), “V”);

Console.WriteLine(stringComparer.Compare(c, d));


hope that will help , let me know if there is an alternate way of doing this



NGENing some misconceptions,

NGen or Native code GENeration, is a utility that comes along with .net framework, we will see what it does in a moment , first i wuld like to breifly discuss the execution of .net assemblies in clr,

say i have to develop an application , that will run over CLR, ok i ll choose any CLS -compliant language  whichever suits my requirement, and write code using it, then i ll use the respective compiler to compile my code down to MSIL and i also requested the compiler to generate the assembly also ,did you notice the difference ??

generating MSIL code is not equivalent to generating assembly , infact its a subset, u will be generating msil code if u r generating a .net module ,or multifile assembly. genrating the assembly  require the compiler to put in manifest data also ,the manifest is the meta data about the assembly ,what it contains , strong name , referneced assemblies ,type it contains, that is why assemblies are also called self descripting components.:)

ok so i got an assembly , say myApp.dll/ or myApp.exe which everrs suits u , i ll go with myApp.exe

so far so good,

now i tried to execute the assembly, the assemblies generated as executables contains bootstrap code, that inovke the clr ,loads it into the process ,creates application domain , and hand over the execution to the managed code entry point. When managed code starts execution , since its the MSIL , so it must be converted to native code , this is done by a JIT compiler, which not only genreates code on fly but also optimize it according  to the platform ,application is running on,the jit compilation is done on method by method basis, when ever a method is called , clr looks in to the method address table that it maintains, if there is an address location specified that means the mehtod has already been converted to native , else , jit comes in action , it takes the whole method  generate its native code,in doing so , if the method refers to a type declared in other  assemblies , then at this moment that reffered assembly is also loaded .and then the execution resumed as if nothign happened

hmmmm now where is ngen in this scenario. ?

ngen is used to CONVERT MSIL code NATIVE Code, the sole reason is to reduce the applicaiton load time , and avoid jitting , also since its one time operation , it tries to optimize more then jitter. THE PURPOSE OF NGEN is to enhance performance. but ngen is not very effective cuz it comes with limitations, i ll point some ,and the rest u can read with links i ll provide at the end,

when u ngen an assembly , say

ngen myApp.exe

ngen loads myApp.exe and CLR and generates it native output that will be stored in winnt/assembly/native (something like that),
some Important points
1)  ngen does not convert ur assembly(myApp.exe) rather it produce a separate output.
2) ngen does not generate assembly manifest to native code
3) ngen generated code is installed in assembly cache , u cannot redistribute,
4) ngen generated code is build specific and each compilation will result in a different build no.
5) ngenerated code is very touchy about its environment, if clr detects changes in its environment like u installed extra rams,updated ur framework installaiton , it will refuse to use the ngen geneated code and will call jitter to rescue.
6) when deploying assemblies , u can use install-time ngening, but u must have actual assemblies installed on the deployment pc , u cant just take the ngened code and put it to deployment pc, this is due to the fact that the manifest still resides in assembly file 🙂

gosh !! ngen  is a blessing or what !!

it depends totally on ur solution what seems to fit , i think if u want full show from clr then its best to le jitter do it work , ms is trying to improve jit performance with more optimizations and jit-compiliation .

check these links for detailed info

in my last post , my freind Raja Khurram Shehzad  proposed that to avoid code tempering we can use ngen to use native code on client machines,  i think i have pointed enough issues , if i have put something wrong , plz correct me. but still i m not conviced that ngen will protect code tempering.


Reverse engineering protection in .net world


a better title wuld be cracking strong named .net assemblies 🙂


(note i dont have in-depth of security in .net world , following are just my thougts on the topic)

almost all of u have heared about the strong naming and gac , so ,whats new about that . Usually these terms are used in context of security and code tempering , so u strong named ur assembly and always signed them with ur keys, and also decorate them with attributes, so now runtime checks when ever that assembly , and ensure that it is the same original assembly, and the calling code has the right permission set and priviliges,


does this ensures that my code will not be tempered or reverse engineered or cracked, 🙂 i havent found any evidence of that yet 😀 , (i ll talk to obfuscation later on.)

by the way when ever runtime laods an assembly and if its a strong named , signed/partially signed , then it verifies that its loading the correct assembly , this is done by extracting public key token ,and calculating the assembly hash and comparing it with the origninal hash , remeber ur algorithm class abt RSA (K) with .net framework there comes a tool for signing assemblies , sn

sn provides different command line option . its really a powerfull tool

there is a swtich -Vr

executing this ,will register ur assemblies for skipping verification ,

hurrah , did ya get what i mean ??

what if

i developed an application , signed and stronged assembliessomeone just dissemble it using ildasm , temper the code , ( and believe me the instruction set IL is really simple , and the compiler generated IL code is a lot easier to comprehend , the only thing that kick ass is the stack evaluation , remember CLR is an stack based machine 😉 , it might be simple due to many reasons, one might be the maturity of c# , compiler, if u compared them to c++ compiler in terms of code generation c++ is way ahead , also since Il is an intermediate language, so compilers might emit code that are easier to optimize during jitting ,)

hhmm where i was, oh haan,

what if someone temper my code , and register the assembly as for skipping verification , infact he can redistribute his code wrapped in mine :P,

, so my question is still here , how can we prevent our code from being reverse-engineered.

for those of u who say use obfuscator,

hmm , i havent use one:P , but what i thnk that proper analysis of generated code will let it reverse -engineered , i mean , a tool can be written to analyze and dissemble the generated code back to source, and also identify the patterns in the code for further analysis,

so how u will protect ur code from being tempered ??

plz if there is any lack of knowledge ,then correct me i ll be gratefull

ldstr “Allah hafiz”

call.s class [mscorlib] MessageBox::Show()


sn -Vr dotCompilerator.dll