Musings on Coding

This is more of a reflective post. Its been a while since i joined microsoft and posted anything back here. I think i would try to come back here more often. I have been working as a consultant for quite sometime and am seeing how many programmers take things for granted. Its simply the easy way and that doesnt mean the correct way. I think i would try to crosspost here along with my msdn blog so hoping to put more stuff out here :)
with 2 Comments

XMLSerializable Hashtable

Well its high time that the hash table became XML serializable but i still havent figured out  why not.
But while I was thinking about this just thought i'd put it down myself.

I would like to know if there is a more standard implementation for this. But I just managed to this chewing gum class done for now.

using System;
using System.Runtime.Serialization;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;

namespace XMLSerializableHashTable
{
	[Serializable]
	public class SerializableHashtable:Hashtable,
				System.Xml.Serialization.IXmlSerializable
	{
		
		#region IXmlSerializable Members

		#region Node class
		/// 
		/// This class would be for custom serialization
		/// 
		[Serializable]
		public class Node
		{
			public Node()
			{}

			public Node(string k,object v)
			{
				key = k;
				val = v;
			}

			public string key;
			public object val;
		}

		#endregion Node class for XML Serialization

		/// 
		/// Write the xml using an array list
		/// using the Node to store key value pairs
		/// 
		/// 
		public void WriteXml(System.Xml.XmlWriter writer)
		{
			XmlSerializer xs = new XmlSerializer(typeof(System.Collections.ArrayList),
												new System.Type[]{typeof(Node)});
			ArrayList list = new ArrayList();
			foreach(string key in this.Keys)
			{
				list.Add(new Node(key,this[key]));
			}
			xs.Serialize(writer,list);
		}

		public System.Xml.Schema.XmlSchema GetSchema()
		{
			// TODO:  Add SerializableHashtable.GetSchema implementation
			return null;
		}

		/// 
		/// Deserialization using array list
		/// and the node(key,value) pairs
		/// 
		/// 
		public void ReadXml(System.Xml.XmlReader reader)
		{
			XmlSerializer xs = new XmlSerializer(typeof(System.Collections.ArrayList),
												new System.Type[]{typeof(Node)});

			//Move the reader into the ArrayList element.
			reader.Read();
			ArrayList list  = xs.Deserialize(reader) as ArrayList;
			Node node;

			if(list == null)
				return;

			//Reload the hashTable.
			for(int i=0;ithis.Add(node.key,node.val);
			}
		}
		#endregion
	}
}
with 2 Comments

Quest for the value of the Output parameter - I

Lets hit the specs for the output paramter

·         A variable need not be definitely assigned before it can be passed as an output parameter in a function member invocation.

·         Following the normal completion of a function member invocation, each variable that was passed as an output parameter is considered assigned in that execution path.

·         Within a function member, an output parameter is considered initially unassigned.

·         Every output parameter of a function member must be definitely assigned (§ 5.3) before the function member returns normally.

How do we get the value then ?

The point that totally put me of was the debugger that had the value. Why can I not access it :) ?

One for the Road

MSDN TV
 I have been wondering how to use that crappy Traffic jams and the hell load of time one has on the crowded roads of Bangalore when commuting to office.
Well with this in mind I finally picked up a few new episodes onto my PPC and made it a point to watch them rather than be bothered about the damn road blocks and traffic. 
Tonight's show - WinFX at PDC
with 0 Comments

LSA in .NET

After a lot of digging and findings on the LSA API, one would usually give up. Now in the managed world one would obviously jump looking to DirectoryServices for help but then after quite a lot of poking around i realized only the userFlags (winNt ) could be set and the policy object is totally in a different direction. Well then finally LSA was suggested as the way to go.

There was this wonderful article on code project that I found quite usefull in giving a good understanding of the API by Corinna John http://www.codeproject.com/csharp/lsadotnet.asphttp://www.codeproject.com/csharp/lsadotnet.asp Now the program here had a few gliches which im not too sure why.
So i went around looking a bit more and there to the resuce was pinvoke.net. Check this article out at http://pinvoke.net/default.aspx/advapi32/LsaOpenPolicy.htmlhttp://pinvoke.net/default.aspx/advapi32/LsaOpenPolicy.html This too follows from the code project article.
The most interesting part in sample at pinvoke.net was the use of the custom marshaler for the LSA_UNICODE_STRING which turn out to be known as the super special lsa string. Ok if you just want to dive into LSA here is the way to go http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/lsaopenpolicy.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/lsaopenpolicy.asp

Primitive Boxing J# and IL

Consider a method definition as follows

public void Write(object val);

You can call the method simply like this

 MyConsole.Write(100);

 It works fine provided this happens in a language like C# where primitive types are boxed automatically.
Looking at IL this is how it disassembles

IL_0000:  ldc.i4.s   100
IL_0002:  box        [mscorlib]System.Int32
IL_0007:  call       void Writer.MyConsole::Write(object)

 As you can see it just simply boxes it up into an Int32 struct. 
In J# you get the following error if you use the above statement to call the method.

c:\Code\JSharpInt\JSharpInt\Class1.jsl(12): Cannot find method 'Write(int)' in 'Writer.MyConsole'

Now you need to box this explicitly if you are sure of the method, using the Int32 struct.  

J#
      Writer.MyConsole.Write((System.Int32)10); 

Well you can check out the IL

IL_000c:  ldc.i4.s   10
IL_000e:  box        [mscorlib]System.Int32
IL_0013:  call       void [Writer]Writer.MyConsole::Write(object)

with 0 Comments

Community Server Reader

This is one awesome feature I liked about Community Server 2.0

with 1 Comments

Culture Free XML - ( Yes I know - Invariant )

XML serialization and deserialization is one interesting topic. I came across some interesting conversations when there was a requirement as to enable input values that are culture specific.
I would say XML is gotta be kept culture independed, always think about the consumer. Also we would always prefer this to happen across culture and also across versions.
So why make it culture specific?

Well I guess this is pretty evident from the way the framework implements XML serialization.
What ever the culture may be on the thread the way the xml serialization takes place is kind simple and straight forward.

de-DE          1,001          <?xml version="1.0" encoding="utf-16"?><decimal>1.001</decimal>

If you want to see it your self here it the snippet.

  1 		private string DisplayAllCultures()
  2 		{
  3 			decimal val = 1.001M;
  4 		
  5 			StringBuilder result = new StringBuilder();
  6 			foreach(CultureInfo ci in CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures))
  7 			{
  8 				Thread.CurrentThread.CurrentCulture = ci;
  9 
 10 				
 11 				result.Append(ci.Name);
 12 				result.Append("          ");
 13 				result.Append(val.ToString());
 14 				result.Append("          ");
 15 
 16 				using(MemoryStream mem = new MemoryStream(200))
 17 				{
 18 					//Read the serialzed string from memory
 19 					XmlTextWriter writer = new XmlTextWriter(mem,Encoding.Unicode);
 20 					XmlSerializer xs = new XmlSerializer(typeof(decimal));
 21 					xs.Serialize(writer,val);
 22 
 23 					mem.Position = 0;
 24 					byte[] buffer = new byte[mem.Length];
 25 					mem.Read(buffer,0,Convert.ToInt32(mem.Length -1));
 26 					UnicodeEncoding unicode = new UnicodeEncoding();
 27 					result.Append(unicode.GetChars(buffer));
 28 				}
 29 
 30 				result.Append("\r\n");
 31 			}
 32 			return result.ToString();
 33 		}
 34 
with 0 Comments

Battle of Generators

I was kind of surprised when I got a mail asking me if i would review the a Tangible Architect and was happy to.
Anyway more importantly I have always been playing around with Olymars and now its time really do some stuff.

I've also been working with EntityBroker for quite a while.
Lets see how this baby comes out. :)

with 0 Comments

castClass vs

Wanted to share a small note keeping in mind the "as" keyword .

public class Program
{
            public static void Main()
            {
                        object o = 100;
                        string s = o as string;
                        string t = (string) o;
            }
}

  IL_0000:  ldc.i4.s   100
  IL_0002:  box        [mscorlib]System.Int32
  IL_0007:  stloc.0
  IL_0008:  ldloc.0
  IL_0009:  isinst     [mscorlib]System.String 
  IL_000e:  stloc.1
  IL_000f:  ldloc.0
  IL_0010:  castclass  [mscorlib]System.String  
  IL_0015:  stloc.2
  IL_0016:  ret

 If you notice that "as"  is translated into isinst opcode and the advantage of using this is that it would return a null reference if the object of is not castable to a string.
On the other hand the castClass would throw an InvalidCast exception.

Start.com

I wished MS would get things out to more people and faster

http://start.com

with 0 Comments

J# and out parameters

I came across another peculiar scenario for J#.
We all believe that out parameters would not have to be initlialized since they are expected to return a value from the calling method. But then again we have to think how its implemented in J#. Ironically J# doesnt have a good idea about out parameters and guess it uses it as a ref

with 0 Comments

Hello world for IAsyncResult

Here is a hello world for IAsyncResult.
I was wondering - does this internally spawn its own thread ? Need some info as to how to catch exceptions thrown from this ?

Any help would be appreciated.

using System;

namespace IAsyncTest
{
	class Program
	{
		public delegate void AsyncTask();
		
		[STAThread]
		static void Main(string[] args)
		{
			Task t = new Task();
			AsyncTask asyncTask = new AsyncTask(t.DoTask);
			IAsyncResult ar = asyncTask.BeginInvoke(new AsyncCallback(t.Done),null);
			Console.ReadLine();
		}
	}

	public class Task
	{
		public void DoTask()
		{
			Console.WriteLine("Start Sleep");
			System.Threading.Thread.Sleep(10000);
			Console.WriteLine("End Sleep");	
		}

		/// <summary>
		/// IAsyncCallback Method
		/// </summary>
		/// <param name="ar"></param>
		public void Done(IAsyncResult ar)
		{
			Console.WriteLine("Done");
		}
	}
}
with 0 Comments

Deprecating Methods - J#

I was wondering regarding deprecating methods in J# and guess what everyone told me the @deprecated attribute. But how do i get a message to indicate what method to substitute with.

I was actually surpised to find the resolution at the winfx msdn articles and the funny thing is that it worked pretty well in 1.1 version of the framerowk

/** @attribute.method Obsolete("My Message", false) */

In case your looking for the link it was http://winfx.msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vjcon/html/0449fb4b-b24e-4400-92ec-312ed29018a8.asp

 

with 0 Comments

Not of System.Object

When we learn C# we assume for all types the following holds true.

object o = <variable>;

So come to think of it is there any type that would not satisfy this statement (WRT to C#).
Well and here is a sample that shows you that there is a type who does not have
System.Object as its root, its the pointer.

class Class1
{
	public static void Main()
	{
		unsafe
		{
			int* variable;
			object o = variable;
		}
	}
}

Check out the compiler error you end up with :)

with 0 Comments

new int();

Whats the difference between ?

int i= new int();
int j=0;


If you check out the IL it turns out that there is no difference :)

  .locals ([0] int32 i, [1] int32 j)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldc.i4.0
  IL_0003:  stloc.1

with 0 Comments

Tasks TODO: Visual Studio

I guess that we all want to keep track of many things that we
do and still end up not organizing these. Ever tried writing code like this?

//TODO: remove intilialization
for(int i=0;i<a.Length;i++)
{
  a = new object
[i];
  Console.WriteLine(i);
}

Go to the task window (CTRL+ALT+K) and right click in this window and select
Show Task -> All
If you are more interested check out the taskList options in the

Tools->Options in visual studio
 


 

with 0 Comments

Static method Call with Instance - C# vs J#

class ClassTest
{
     public static void S()
    { }
     public void Test()
    {
        this.S();
    }
}




This is the compiler error
StaticCall.cs(11,3): error CS0176: Static member 'ClassTest.S()' cannot be accessed with an instance reference; qualify it with a type name instead

Why did the J# spec allow this code to compile and not the C# ?
Should we be able to call static methods using a instance as they pretty much belong to the same type definition or should this work like C# which prevents 
static method calls via instance variables because the instance could be null etc and more arguments hence forth.
Just a thought !
with 0 Comments

Getting the Type in J#

Last day a collegue of mine was trying to get the type of a class in J#.

Everyone is would be familiar with the typeof(<MyClass>) in C# right. The question was how to do this in j# as typeof is not supported ?

Loading the assembly was not an option and well we didnt want to make an instance and then get the type from it.

This was what i ended up with .

 

    System.Type t = Class.ToType(System.Windows.Forms.Form.class);

J# java.lang.Class

Right Click and Build Solutions from Windows Explorer

When your developing in a team you have so much of depended code and you just want the assembly from that other god forsaken referenced project. But do I have the assembly ? Nope but i do have the latest code.
Now the problem of opening up visual studio and waiting for the whole damn thing to load and then finally CTRL+SHIFT+B..

I guess this would be quite a common story amoung  many guys developing in a team if I'm not wrong. Well this just got me writing a simple batch file when a collegue of mine mentioned that it would nice to right click and build. So if you guys wanna do that I guess this would be a simple approach ..

The Bat File.
Placethis into your visual studio 2003 (aka 7.1) Common7\Tools folder and name it BuildDebug.bat

echo off
call "%VS71COMNTOOLS%\vsvars32.bat"

REM Remove the error log
IF EXIST error.txt del Error.txt

REM Build the solution
devenv.exe /build debug /out "error.txt" %1

REM display if error exists
IF EXIST error.txt type Error.txt

REM Remove the error log
IF EXIST error.txt del Error.txt

PAUSE

The Reg key for adding Shell extentions
You can add the file association manually and pass in the first parameter or simply just save this as a .reg file and run or manually enter the key into your registry

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\VisualStudio.Solution.7.1\Shell\Build\Command]
@="\"C:\\Program Files\\Microsoft Visual Studio .NET 2003\\Common7\\Tools\\BuildDebug.bat\" \"%1\""

 

 

 

with 2 Comments