Tuesday, December 23, 2014
#EvilCode 0001 : Lambda and Ref/Out.
Tuesday, June 19, 2012
Detecting if Application is running under Wow64
Thursday, May 13, 2010
WSH object and Usage
Following is a list of WSH objects and its typical usage. I found it extremely useful ( courtesy MSDN)
| Object | What you can do with this object |
| · Set and retrieve command line arguments · Determine the name of the script file · Determine the host file name (wscript.exe or cscript.exe) · Determine the host version information · Create, connect to, and disconnect from COM objects · Sink events · Stop a script's execution programmatically · Output information to the default output device (for example, a dialog box or the command line) | |
| Access the entire set of command-line arguments | |
| Access the set of named command-line arguments | |
| Access the set of unnamed command-line arguments | |
| · Connect to and disconnect from network shares and network printers · Map and unmap network shares · Access information about the currently logged-on user | |
| Create a remote script process using the Controller method CreateScript() | |
| · Remotely administer computer systems on a computer network · Programmatically manipulate other programs/scripts | |
| Access the error information available when a remote script (a WshRemote object) terminates as a result of a script error | |
| · Run a program locally · Manipulate the contents of the registry · Create a shortcut · Access a system folder · Manipulate environment variables (such as WINDIR, PATH, or PROMPT) | |
| Programmatically create a shortcut | |
| Access any of the Windows Special Folders | |
| Programmatically create a shortcut to an Internet resource | |
| Access any of the environment variables (such as WINDIR, PATH, or PROMPT) | |
| Determine status and error information about a script run with Exec() Access the StdIn, StdOut, and |
Thursday, March 18, 2010
Tolerance for DateTime comparison
Wednesday, January 20, 2010
Designer View Not Available in VS 2003
Thursday, October 22, 2009
Redirecting Tracing or Debugging output.
Thursday, July 30, 2009
UAC Compatible applications - Part 3 ( Getting Process List )
So now we have got an idea of how to get our application work in Vista. There are few tips which could help us tackle minor issues which we might face in Vista.
One of such issues is when we have to get the list of all processes active in the system. What we usually do is call the System.Diagnostics.Process.GetProcesses() method. This, however, get us into trouble when running from limited user in vista. The Limited User in vista doesn’t have privilege to fetch this list.
Of course, it is not end of the world and is definitely, there is one work-around for this as well.
You could query the WMI Classes to get the desired result.
ManagementScope scope = new ManagementScope();
System.Management.ObjectQuery query = new ObjectQuery("select * from Win32_Service");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach(ManagementBaseObject objService in searcher.Get())
{
Console.WriteLine(objService["Name"]);
}
Simple as it can get.
Wednesday, July 22, 2009
UAC Compatible applications - Part 2 ( Access Registry )

Tuesday, July 21, 2009
UAC Compatible applications - Part 1 ( Disable Virtualization )
Vista with UAC enabled is quite a nightmare for developers , especially if you are making an existing application vista compatible.
One of the first problems we face is how UAC prompts for Administrative credentials whenever it is running an application that performs action that requires administrative privileges. As a developer, one of first steps we need to do is to disable this.
All you need to get rid of UAC prompts is the manifest files.
<?xml version="1.0" encoding="utf-8" ?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.3.0.110"
processorArchitecture="X86"
name="MyApplication"
type="win32" />
<description>MyProjectDescription</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" />
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
There is two ways you could assign a manifest file to an application.
Method 1:
You can use Mt.exe to embed the manifest right into the application. Following commands does the job for you.
Mt.exe –manifest TPWPWDbsetup.exe.manifest TPWPWDbsetup.exe
Method 2:
The second method is to keep the manifest file along the application. The manifest file should be named as "YourApplicationName.exe.manifest".
Vista would detect the manifest and use the same settings when launching your application.
Another advantage of using the manifest file is it ensures registry virtualization is turn-off. I would really recommend developers to keep the virtualization turn-off for two reasons
a) Microsoft does seems to have plan to do away with the virtualization in the future editions of OS.
b) With Virtualization turn off, your applications is bound to throw exceptions aiding you in the test phase itself. On other hand, if the virtualization was on, your registry entries are made in localized key without showing any error.
Following are some of the settings you could use in the manifest file.
| Application Marking | Virtualize? |
| Unmarked | Yes |
| asInvoker | No |
| requireAdministrator | No |
| highestAvailable | No |
Thursday, July 02, 2009
Virtual Serial Port detection in .Net 1.1
Saturday, April 25, 2009
Disable Right Click in DataGrid , Thanks Justin
Tuesday, April 21, 2009
Disable Textbox Right Click Context Menu
Earlier today I had a requirement to disable right click context menu inside a TextBox Control. Though the solution looked simple at hindsight, it did seem cheeky.
All you needed to do was to add a Context Menu to you Form and attach this as the Context Menu for your Text Box Control. And that is all you need to think about !!
What happens is when you are not specifying any Context menu explicitly, Windows default Context menu gets attached to your control. By overriding it with another empty menu control, you are denying the default one an appearance.
Simple as it can get.
Friday, March 27, 2009
Get List of Event Handlers.
Quite often we would need to get list of Event Handlers of a particular event from outside the Class that has actually implemented it.
Here is a method which allows you to Check if Event Hendlers are added and if so, gives you the list of method name of those handlers.
private static ArrayList GetListOfEventHanlders()
{
ArrayList delgList;
FieldInfo fi = objClassInstance.GetType().GetField("MyEvent",BindingFlags.Instance | BindingFlags.NonPublic);
object handler = fi.GetValue(objClassInstance);
if(handler!=null)
{
delgList = new ArrayList();
MulticastDelegate originalDelegate = handler as System.MulticastDelegate;
Delegate[] originalHandlers = originalDelegate.GetInvocationList();
foreach(Delegate item in originalHandlers)
{
delgList.Add(item.Method.Name);
}
}
else
{
return null;
}
return delgList;
}
For more details do check out this excellent article by Stephen Horsfield at http://blogs.interakting.co.uk/steve/archive/2008/05/19/NET--Hacking-events-and-manipulating-delegates.aspx
Saturday, March 14, 2009
Lazy Evaluation : A Future CLR Need ?
Let's us first have a look at the code below.
static void Main(string[] args)
{
GetConstant(GetInfinity());
}
static int GetConstant(int x)
{
return 0;
}
static int GetInfinity()
{
return GetInfinity() + 1;
}
That looks pretty straightforward code, but if you look closely, we would realize this would end up in a StackOverflowException owing to the infinite recursive GetInfinity Method. If you look furthur closely, do we really need a call to GetInfinity in first place, as GetConstant Method would return a value 0, least bothering the value returned by GetInfinity.
This is where my thought process starts. Cann't the compiler make the decission of whether to make a call to GetInfinity ?
At the end of the day, there are 2 different evaluation orders that could be follows.
a) GetConstant(GetInifinity()) => GetConstant(GetInifinity()+1) => GetConstant(GetInifinity() +1 +1 )....
b) GetConstant(GetInifinity()) =>0
If you notice, the first one never stops while the second one terminates after the first line.
This is something which functional programming languages can take pride in, the Lazy Evaluation.
Wikipedia defines Lazy Evaluation is the technique for delaying a computation until such time as the result of the computation known to be needed.
CLR engages in eager evaluation and hence get it self tangled in the infinite recursive loop in the code above.
I believe this is something Microsoft can bring in the future version of C#. Lazy evaluation can save us quite a bit of time.
Wednesday, March 11, 2009
Get All Physical Drives
.Net 2005 provides us with the DriveInfo Class which enables us to get all logical drives in our system. We can use this class along with the property of DriveType to filter out the physical drives. But the problem with this approach is, suppose you were to connect an external USB Hard disk to your system, even that is detected as Physical Drive. Ideally you would want that to be detected as a Removable Drive.
We can accomplish this using WMI Classes. Check out the following function
private static StringCollection GetDrives()
{
StringCollection drives = new StringCollection();
foreach(ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType!='USB'").Get())
{
foreach(ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
foreach(ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"+ partition["DeviceID"]+ "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
drives.Add(disk["Name"].ToString());
}
}
}
return drives;
}
Monday, March 09, 2009
Dynamic Interface Addition to existing Class using Reflection
I recently went through an article by Eric McMullen. The power of reflection and dynamic code was so well depicted in the article.
We know how to create a dynamic code using reflection. But what i liked about this bit of article from Eric was how an already existing type was wrapped by a Interface dynamically at the runtime. Now, isn't that a useful feature to have ??
Not sure ?? Think in this manner. You have an interface with a method "Name". You also have a class "MyName" which DOES NOT implement the interface but has a virtual method "Name". It is obvious that you cannt create a referance of the interface for the class. But the point , is with Dynamic extension, we could just well do it.
How do we do it ? lets have a look at the code.
First and foremost thing you would want is have an assembly, in this case a dynamic one. So let us go ahead and degfine it first.
I have create a function which would take the target type and interface that needs to be implement as parameters.
public object GetNewImplementation(System.Type TargetType,System.Type InterfaceToImplement)
{
AssemblyName an = new AssemblyName();
an.Name = "ExtendedTypes";
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler ( CurrentDomain_AssemblyResolve);
Type t = Subclass (moduleBuilder, TargetType, InterfaceToImplement, "ClassTest1");
return (Activator.CreateInstance(t,true)) as object;
};
As you can see i am calling a SubClass method in later part of the method. This is the magic method which does the trick for us.
public Type Subclass(ModuleBuilder builder, Type target, Type interfaceToImplement, string newTypeName)
{
TypeAttributes attributes = TypeAttributes.Public;
TypeBuilder tb =builder.DefineType("ConsoleApplication1.DynamicClassTest1", attributes,target);
tb.AddInterfaceImplementation(interfaceToImplement);
Type subClass = tb.CreateType();
return subClass;
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly returnVal = null;
if(args.Name == this.assemblyBuilder.FullName)
{
returnVal = assemblyBuilder;
}
return returnVal;
}
Now is that cool ?
Friday, March 06, 2009
Passing Reference Variable using Pass-by-Value
This is bit of going back to school.But at times, it's nice to revisit old classes once in a while.
Pass-By-Value and and Pass-By-Ref is something we learnt when we all started coding. But these are some very basics which we often tend to overlook. I recently was talking to a friend of mine who was passing a KeyPressEventArgs object to a Method by value. We for a longer part, overlooked the basics of programming and kept wondering why the value of property "Handled" was changed , despite the object being passed as "pass-by-value".
But that’s exactly how it should be. The value ought to be changed because we are passing a reference variable by value. That's the quintessential behavior. Lemme put it up in an example.
private void ArrayChange(int []G)
{
G[0]= 3434;
}
private void MyFunction()
{
int []arr = new int[]{3,4};
ArrayChange(arr);
Console.WriteLine(arr[0]);
}
The output of this would be 3434 and NOT 3. This is because even though the array is being passed as Value, being the reference variable, it is the reference to array that gets passed and not the entire array as such.
This is exactly what happened in my case. KeyPressEventArgs being a reference variable reacted in the same way it has been designed to.
Well, rather to look our self as stupid, optimistically I would prefer to believe that such goof-ups would occur when one started looking beyond the basics. This is also where the KISS ( Keep It Simple Stupid) principle comes along.
As programmer's we often think too many complicated solutions for a very simple problem. Probably, it is quite a good idea to go back to school and get our basics refreshed.That would encourage us to put the solutions really simple and follow the KISS principle.
Wednesday, March 04, 2009
Windows Form Resizing issue.
I recently tried out bring out a form which had a size 2x2 without any border or title bar. The problem i faced was whatever i do, the form always took up a default size evidently larger than the one i set.
The solution was simple and straightforward. Just put up the MinimumSize and Maximumsize values for the border. By default, due to the draggging and resizing you had done, the values would be now 0,0. Change the value to say 1,1 and you have your way
Thursday, November 06, 2008
C# 4.0 : Optional Parameters
C# 4.0 Feature list looks promising and adds more flexiblity to the programmer.
Of course, i dont have hands on experience with this features as it is yet be released for beta, my knowledge is purely based on the blog entries by Bart De Smet in his blogs.
First feature i would like to focus is a long-standing request for any C# programmer,The Optional Parameters for methods.
Optional parameters also bring along default values for parameters.
The syntax is very much simple and straightforward.
public static void SayHello(string s = "hello")
{
// body
}
The developer can invoke the SayHello method with or without an arguement, which case the default value would be used.
SayHello();
SayHello("welcome c# 4.0");
One important point to note here is, all optional parameters needs to come at the end of the arguement list.The reason for this is obvious, to remove chances of ambiguities which may be resulted
public static void SayHello(string s1 = "Hello World!", string s2)
What would a call with a single string argument result in? Would the parameter be bound to s1, overriding the default, or would it bind to s2?
Tuesday, September 23, 2008
Prefix vs As Casting : Which is faster?
.Net Provides two ways to Cast an object, namely, Prefix Casting and "as casting". "As Casting" provides an additional type which results in a null value to be returned in case of casting error. On other hand, Prefix casting would throw an exception in that scenario.
But which is faster ? Well, it seems strange that even though "as-casting" provides an additional checking it seems faster than the prefix. Following sample code demonstrate the same.
ArrayList d = new ArrayList();
for (int i = 0; i < 67108864; i++)
{
d.Add(new Class1(i));
}
Class1 obj1;
DateTime dtAS = DateTime.Now;
for (int i = 0; i < 67108864; i++)
{
obj1 = d[i] as Class1;
}
Console.WriteLine((DateTime.Now - dtAS).Milliseconds.ToString());
Class1 obj2; DateTime dtN = DateTime.Now;
for (int i = 0; i < 67108864; i++)
{
obj2 = (Class1)d[i] ;
}
Console.WriteLine((DateTime.Now - dtN).Milliseconds.ToString());
If you look into the IL code for same, you would notice that "as casting" uses isinst IL command while prefix casting uses "castclass" method.
But if you have a look at how MSDN has defined isinst command, it can lead to think why in the earlier code, as casting works faster.
Here is a snippet from MSDN about isinst
Tests whether an object reference (type O) is an instance of a particular class.
"If the class of the object on the top of the stack implements class (if class is an interface) or is a derived class of class (if class is a regular class) then it is cast to type class and the result is pushed on the stack, exactly as though Castclass had been called. Otherwise, a null reference is pushed on the stack. If the object reference itself is a null reference, then isinst likewise returns a null reference."
Now if object is casted exactly as though CastClass after validation, then how is it that its faster ?
anyone has any suggestions ?

