Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, December 23, 2014

#EvilCode 0001 : Lambda and Ref/Out.

What would be output of following ?

        static void Main(string [] args)
        {
            List< int> numlist = new List< int>() {1,2, 3, 4, 5, 6, 7 };
            CalculateAndPrint( ref numlist);
        }

        public static void CalculateAndPrint( ref List< int> Num)
        {
            var n = Num.Where(d => d > Num[2]);

            foreach ( var item in n)
            {
                Console.WriteLine(item);
            }
        }

The most obvious answer is 4,5,6,7. However that's not. This code refuses to compile because Lamba expressions  cannot accept variables that are declared in an outer scope.

Tuesday, June 19, 2012

Detecting if Application is running under Wow64


Back Again...Everytime I get back to blogging after long hibernation, I promise myself to be regular, only to break the promise soon. Hopefully this time, I would be more consistent.  So here it is, my first blog after 1.5 years.

"Windows 32Bit on Windows 64Bit" , better known as the WoW64 is a subsystem that provides a lightweight compatibility layer, which aims to create a 32-bit environment that provides interfaces required to run un-changed 32-bit Windows applications on a 64-bit machine.

Under a 64 bit machine, the 32bit applications are installed under  "c:\Program Files(x86)" Folder while the 64 bit applications are installed under "C:\Program Files" Folder. Many a times, this along with other reasons, makes it necessary for us to detect if our application is running under WoW64 Feature. Here is how we do it.



[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool wow64Process
);


public static bool IsApplicationWow64Process()
{
using(Process currentProcess = Process.GetCurrentProcess())
{
bool retVal = false;
if(!IsWow64Process(currentProcess.Handle,out retVal))
{
return false;
}
return retVal;
}
}

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

WScript 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)

WshArguments Object

Access the entire set of command-line arguments

WshNamed Object

Access the set of named command-line arguments

WshUnnamed Object

Access the set of unnamed command-line arguments

WshNetwork Object

· Connect to and disconnect from network shares and network printers

· Map and unmap network shares

· Access information about the currently logged-on user

WshController Object

Create a remote script process using the Controller method CreateScript()

WshRemote Object

· Remotely administer computer systems on a computer network

· Programmatically manipulate other programs/scripts

WshRemoteError Object

Access the error information available when a remote script (a WshRemote object) terminates as a result of a script error

WshShell Object

· 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)

WshShortcut Object

Programmatically create a shortcut

WshSpecialFolders Object

Access any of the Windows Special Folders

WshUrlShortcut Object

Programmatically create a shortcut to an Internet resource

WshEnvironment Object

Access any of the environment variables (such as WINDIR, PATH, or PROMPT)

WshScriptExec Object

Determine status and error information about a script run with Exec()

Access the StdIn, StdOut, and

Thursday, March 18, 2010

Tolerance for DateTime comparison

By default, C# compares DateTime instances with a tolerance of 100 ns. Recently i ran into a situation where i needed to customize the tolerance level. C# doesnt provide any overloaded method operation to do so, but we could do ourself very easily.

if((dateTime1 - dateTime2).Duration() <>
{
}

This ensures a tolerance of 10 seconds.This can altered to do any tolerance level that we require.



Wednesday, January 20, 2010

Designer View Not Available in VS 2003

There are times when Visual Studio 2003 fails to identity Windows Forms in your projects and displays it just as any normal CS files. This would literally rob you of chance of working on the Designer View of the Form.

Solution to this is quite simple, all you need to do is use the Visual Studio Editor to exclude the particular File ( along with its RESX files ) and include it back again. That's pretty much it and you have your Designer View back.

Thursday, October 22, 2009

Redirecting Tracing or Debugging output.

Attaching Visual Studio IDe to the application for viewing debugging information can turn out to be quite troubleesome, especially when dealing with large applications. In such cases, as developer, one would like to redirect the debugging information to a external file without having to attach the IDE.

Following code verify whether you are running an exe build using debug mode and then redirect the output to a external file.

#if (DEBUG)
TextWriterTraceListener tr2 = new TextWriterTraceListener (System.IO.File.CreateText ("DebuggerLog.txt"));
Debug.Listeners.Add(tr2);
#endif

The output can be redirected to Console using ConsoleTraceListner.

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 )

Okay, so in the part of the posts about Vista, we looked at the ways we could use manifest files to disable Registry Virtualization and subsequently, disable to UAC prompts. So with that out of the way, the next obvious question if how we are going get our application write in the Registry and Program Files directories.

The way I look at this, there are two distinct approaches of accomplishing this.

Method A

You would need to set permission at the directory/key level for the User Group .


This would ensure that our application could still write in the registry despite running the application from the Limited User Privileges.

Similar setting can be applied to the installation directory enabling us to write to the particular folder.

Method B

The second method is how we redesign the architecture of the product by introducing a second layer of code which would help us write the code. We would implement a Windows Service which would do the registry/folder writing for us.

The basic idea behind this approach is the fact the Windows Service runs in the System account and henceforth enable us in writing in the restricted areas. The custom application would send request to the Windows Service which, in-turn does the restricted operation. The mode of communication can be any of the IPC, from Named Pipes to Mailslot or any other.



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

.Net 2.0 provides SerialPort class which helps you in detecting the available Serial Ports in the machine. However, this is one useful class which v1.1 developers find missing in their tool kit.

As far as 1.1 is concerned we can accomplish it using WMI Classes easily.

private static void GetAvailablePortListUsingWMI()
{
//Below is code pasted from WMICodeCreator
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Port : {0}", queryObj["DeviceID"]);
}
}
catch (ManagementException e)
{
Console.WriteLine(e.Message);

}
}


But is this perfect ? At First glance it does give you that impression, but the moment you have your virtual ports running, you are going to run against the wall.

WMI Classes fails in detecting the Virtual Serial Ports.

Solution wasn't too hard to find. I opened up the reflector against the SerialPort Class supported by .Net 2.0 and checked what it was doing and emulated the same with 1.1 code. The SerialPort class use the registry in detecting the ports and it does support the virtual ports as well.

Following is sample of code which runs in background for the SerialPort class in .Net 2.0

private static void GetAvailablePortListUsingRegistry()
{
RegistryKey localMachine = null;
string[] valueNames=null;
RegistryKey key2 = null;
string[] strArray = null;
new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM").Assert();
try
{
localMachine = Registry.LocalMachine;
key2 = localMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false);
if (key2 != null)
{
valueNames = key2.GetValueNames();
strArray = new string[valueNames.Length];
for (int i = 0; i <>
{
strArray[i] = (string) key2.GetValue(valueNames[i]);
Console.WriteLine("Port : {0} ",strArray[i]);
}
}
}
catch(Exception ex)
{
Console.WriteLine("Error {0}",ex);
}
finally
{
if (localMachine != null)
{
localMachine.Close();
}
if (key2 != null)
{
key2.Close();
}
CodeAccessPermission.RevertAssert();
}




Saturday, April 25, 2009

Disable Right Click in DataGrid , Thanks Justin

It is only few days earlier I had posted an entry about disabling right click in a TextBox.  Now how we do the same in DataGrid ?

It doesn’t seem quite as easy as in case of TextBox.  The idea in assigning ContextMenu to DataGrid backfires when you attempt to right click right inside a cell.  Thanks to my friend Justin Jose, I do have the solution for it.

DataGridTextBoxColumn dgColumn = new DataGridTextBoxColumn();
dgColumn.TextBox.ContextMenu = contextMenu1;
dgColumn.MappingName = "ColumnName";
DataGridTableStyle dgTableStyle = new DataGridTableStyle();
dgTableStyle.GridColumnStyles.Add(dgColumn);
myDataGrid.TableStyles.Add(dgTableStyle)

Thanks Justin, this is cool

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 ?