My Potential My Passion

You are never given a wish, without also being given the power to make it come true - Richard Bach

Monday, November 27, 2006

WINDOWS VISTA + IIS7 + VS2005 = Confusion

With Windows Vista Ultimate decorating my laptop, I decided to open up an existing VS2005 web project (based on HTTP and not FileSystem) and as expected it didn't go smooth! I got an error saying "Unable to open web. The web server does not appear to have frontpage server extensions installed". After a quick bit of research (another name for googling), I found a solution which will benefit all. Here's what one should do to ensure that the project gets loaded:

1. First an foremost, IIS6 compatiblity needs to be enabled. There is no frontpage server extension now. In IIS7 we will have Sharepoitn Designer and Expression Web Designer. To enable compatibility with IIS6 go to Control Panel --> Programs --> Programs and Features --> Turn Windows features on or off. In the resulting dialog box, under Internet Information Services, navigate to Web Management Tools enable IIS6 Management Compatiblity.

2. Next you need to run VS2005 with elevated privileges. Only then you will get access to IIS. To do that right click the VS studio 2005 icon in Start --> Programs --> Microsoft Visual Studio 2005 and open Properties. Click on the Advanced button and check "Run as Administrator" and then click ok.

3. Now launch VS2005 using this shortcut with elevated privileges and open the website that earlier didnt open.

It should open this time without issues!!!

One thing that's torturing my mind is, how secure is it to run devenv in elevated privileges!!!??

Friday, November 17, 2006

Threading enhanced in 2.0 - Part II

This in continuation to my previous post where I wrote about ParameterizedThreadStart delegate. Well, there's more stuff added to the Thread class in .NET 2.0.

Remember the Thread.Abort method?? We know how messy things can get by calling this method! Imagine a situation where, we are in the middle of a particular process and we initiate a Thread.Abort. The thread will abort then-n-there and a ThreadAbortException will be thrown. The thread mechanism doesn't know where to exactly abort the thread so much so that, the integrity of the system is not harmed! Doing an abort in an unpredictable way can have serious implications on the behavior of the system and can leave the appdomain in an inconsistent state.

In .NET 2.0, again we have a savior! The BeginCriticalRegion and EndCriticalRegion methods. These are two static methods which engulf a critical section of code where-in a thread abort shouldn't happen in any case. The region that lies withing these 2 methods must be executed under any circumstance. After EndCriticalRegion() ....well we get a ThreadAbortException as usual.

Just for the sake of thought:

Why are these methods and not just blocks like the using{} block in c#?

So, instead of writing:




We could have written:


Comments are welcome!

Thursday, November 16, 2006

Threading enhanced in 2.0

Here's a cool thing. In .NET 1.1 we had a threadstart delegate which could execute a method on a different thread. Well...this was good as long as the method didn't have any parameters!! But what if we would like to share data or pass some data to the thread!? Worry not my friend..ParameterizedThreadStart has come to aid in .NET 2.0

There is a new delegate called ParameterizedThreadStart, declared as:

public delegate void ParameterizedThreadStart (Object obj)

This delegate take a single paramater of type object and returns void. Essentially this parameter takes in data that is to be passed to a parameterized method which is to be invoked on a different thread.

So now doing something like this is possible:

public void DisplayHello(string name)
Console.WriteLine ("Hello " + name);

ParameterizedThreadStart objPTS = new ParameterizedThreadStart(DisplayHello);
Thread objthread = new Thread(objPTS);


This is cool ain't it?? Just for the sake of thought - would it have be a good thing to provide a param array of type - object, instead of a single object as a parameter to the ParameterizedThreadStart delegate??

Monday, September 25, 2006

Deserialization in .NET 2.0

Deserialization is not new to .NET. It's as simple as using one of the formatters like BinaryFormatter or SoapFormatter and using the DeSerialize method. What .NET 2.0 adds is a way to initialize deserialized members automatically.
e.g. let's say I have a Order class which is marked as serializable:
class Order
public int units = 3;
public int price_per_unit = 4;
public int total_price = 12; // units * price_per_unit.

Now when I serialize an instance of this class, all 3 members will be serialized and in-turn all 3 members will be deserialized. Well good!!! But there's a small issue. Why should I serialize / deserialize "total_price" everytime?? It's a calculated field. Ideally I should be able to save some bytes from getting serialized and deserialized everytime, if I can manage to automatically initialize total_price on deserialization.
Now, if I simply mark the total_price field as [NonSerialized], it's not going to suffice, because, after the instance of this class is deserialized, the total_price will be initialized to 0 and not 12.
To resolve this, there's a new interface called IDeserializationCallback. This interface exposes a method called OnDeserialization which we can implement in our class to do this automatic calculations and initializations of NonSerialized fields.

So, here's how it's done:

class Order : IDeserializationCallback
public int units = 3;
public int price_per_unit = 4;
[NonSerialized]public int total_price = 0; // units * price_per_unit.

void IDeserializationCallback.OnDeserialization(object Sender)
total_price = units * price_per_unit; //here the price will be set to 12.

I marked total_price as NonSerialized, so when I serialize this object, only units and price_per_unit will be included.
When, the Deserialize method of a formatter is called, it automatically invokes IDeserializationCallback.OnDeserialization( object Sender) method which takes care of initializing the total_price and thus this field is now avaliable to use after the class is deserialized.

Cool stuff ain't it??

Wednesday, September 20, 2006

Store multiple values against a key!!!

Now this sounds a little different from the typical hashtables, dictionary and hybriddictionary classes of the world. Yes, I am talking about a new collection class in .NET 2.0 - NameValueCollection (NVC). Using a NVC allows me to store multiple values against a key in a collection object.
NameValueCollection nvc = new NameValueCollection();
nvc.Add("1", "Sarang");
nvc.Add("2", "Reena");
nvc.Add("2", "Teena");

for ( int x = 0; x < nvc.Count; ++x)

//the output that will be generated is:
//Reena, Teena

So, essentially now in addition to storing key value pairs, we can also group more data under a single key.


Thursday, September 14, 2006

More about delegates....

Many a times, in the programming world programmers end up saying that delegates “are” function pointers where in, reality is delegates “are like” function pointers. Why? Because they do a little more than just storing the address of the function to be invoked. Apart from doing more, delegates are object oriented (they are classes at the core) and are absolutely type safe.

Essentially, when we assign a function to a delegate here are two possibilities:

1. We might assign an instance method to the delegate: In this case the delegate stores a reference to the method’s entry point and also to the instance of the object, called the target. This is of the same type that can be assigned to the type that defined the method.
2. We might assign a static method to the delegate: In this case the delegate stores a reference only to the entry point of the method which we are interested in doing a dynamic invoke on.
To verify the above facts, here’s an example:

Class Program
delegate void myDelegate (string s);
static void Main(string[] args)
myDelegate md = new myDelegate(TargetMethod);
myDelegate md1 = new myDelegate(TargetMethod2);

1 Console.WriteLine(md.Target.ToString());
2 Console.WriteLine(md.Method.ToString());

3 Console.WriteLine(md1.Target.ToString());
4 Console.WriteLine(md1.Method.ToString());
5 Console.ReadLine();


void TargetMethod(string s)
static void TargetMethod2(string s)

In the example above lines 3 and 4 will throw an exception. Why??? because TargetMethod2 is a static method therefore an instance of the class is not required and is not available to be assigned to the Target property of the delegate instance. As a result, the Target property of the delegate will be null in this case for md1.

Apart from that, the delegate class also exposes Combine method which allows assigning and execution of multiple methods thru one delegate. Again internally when I call Combine a new delegate is instance is created and returned but the programmer is kept away from these details. To allow multiple methods to be called, internally the delegate maintains an invocation list which is nothing but an array of delegates i.e. Delegate[] - Verify this by calling the GetInvocationList () method the delegate instance.
Like the Combine we also have a Remove() method which dynamically allows us to remove a method from the delegate's invocation list.

So to conclude, they are not simply, stupid function pointers!!!

Wednesday, September 13, 2006

Compression in .NET 2.0

I was just checking out an interesting feature built into .net 2.0 – Compression capability in Streams. (I am not getting into why we need to compress data…etc)
.NET provides 2 classes to facilitate compression of streams. GZipStream and DeflateStream. Both these classes are based on open standards thus taking away any issues related to breach of intellectual property. Feel absolutely free to use them in your projects / products.
I will explain the working of one of these classes with an example. So here goes:
First to ensure that these classes are available to use, do a good old “using” or “imports” depending on whether it’s C# or VB.NET
using System.IO;
using System.IO.Compression;
Then create a class called FileCompression.
Write two methods called Compress and DeCompress which take 2 strings as paramters – one for infile and one for the out fileas follows:
public static void Compress( string input, string output)
FileStream infile = File.OpenRead(input);
FileStream outfile = File.OpenWrite(output);
GZipStream zip = new GZipStream(outfile, CompressionMode.Compress);
int aByte = infile.ReadByte();

while (aByte != -1)
aByte = infile.ReadByte();

In the compress method, we are opening a GZipStream object and passing the outfile to it as a param. The second parameter tells GZipStream to compress the data when storing it into the outfile. The we simply read one byte at a time from the input file and passing it to the GZipStream object to compress and store it into the output file.

public static void DeCompress(string input, string output)
FileStream infile = File.OpenRead(input);
FileStream outfile = File.OpenWrite(output);
GZipStream zip = new GZipStream(infile, CompressionMode.Decompress);
int aByte = zip.ReadByte();

while (aByte != -1)
aByte = zip.ReadByte();


In the DeCompress method we are doing just the opposite – read one byte at a time from the input (compressed) file using the GZipStream object and then write to a normal filestream. Note: The second parameter to the GZipStream object in this case is Decompress which tells GZipstream to decompress the data as and when it is read using the ReadByte method.

The DeflateStream object is nothing different interface wise and has the same methods. The only difference is GZipStream uses some extra headers so that the compressed file can also be processed by the gzip tool. These headers also make the file a little heavy. DeflateStream on the other hand, doesn’t use headers as a result it is slightly smaller in size. It’s recommended to use DeflateStream.

That’s about it for the day. Deflating for the moment…..:)