Rakesh Rajan's blog

Thoughts on .NET, software and a few trivial things...

Class to Xml tool (test version)

Summary

CTX (Class to Xml) tool is a very simple tool which provides you a code editing environment in C# and VB.NET, compiles the source codes and lets you see the Xml output of all serializable types once successfully compiled.


Intro

Do you use Xml Serialization in .NET – if yes, you might be interested in this tool!

Have you ever thought "Hmm…now that I have written a serializable class, I wonder how will it look when it is Xml Serialized"?

If yes, you are in good company :). Sometime back I was involved in a project in which I had to develop a lot of business entity classes which would be Xml Serialized. Since these classes had to adhere to a specific schema, I had a tough time synchronizing the Xml Attributes and the final xml schema it generated when xml serialized.

The sequence of how I would go about doing this was like this:

  1. I would develop a draft version of xml schema.
  2. I would create a simple console project in which I would start writing the class to be serialized.
  3. This project will have a small code snippet which will create an instance of the serializable class and xml serialize it and then finally print out the xml output.
  4. I will keep comparing this output with my xml schema until they are in sync.

As I got involved in more and more projects (many of them my own :) ) which came to have similar requirements, I decided to create a little tool which would automate the above tasks.

Introducing the Class to Xml (CTX) tool - a very simple tool which provides you a code editing environment in C# and VB.NET, compiles the source codes and lets you see the Xml output of all serializable types once successfully compiled.

How to use the tool

  1. Open up the source code files of the serializable classes you want to get the xml for (including all the files that are referenced) and select the language.
  2. Press F5. The whole list of files will be compiled.
  3. If compilation is successful, the Output pane would list all serializable types available in the assembly. If compilation failed, the Errors pane would list the errors.
  4. After successful compilation, select the required serializable type in the combo box; the Xml representation is displayed in the Serialized Xml text box.

Download

The current test version source code (probably terrible) in Visual Studio 2005 is available here (The site is down due to site maintenance, please wait while I resolve this ASAP).
Do check it out and let me know your comments.

I plan to finalize the code soon…er, I have no idea how “soon” though :)

Posted: Feb 18 2006, 03:15 PM by rakeshrajan | with no comments
Filed under: ,
Digitally mastering my portraits

I used to paint portraits in oil when I was kid.

For different reasons, I had not been able to maintain them as a result of which they have aged a lot :(.

The last time I went home, I took close up snapshots of my works with my Canon PowerShot A510, and now I am repairing them with Photoshop :).

Check out the initial stages of the "repair" (extracted the subjects and set the background to 0,0,0) below:

Posted: Jan 15 2006, 07:03 PM by rakeshrajan | with no comments
Filed under:
XML Serialize IDictionary types (Hashtable, DictionaryBase etc.)

Problem

You want to serialize a type; however it:

  • implements IDictionary, or
  • derives from DictionaryBase, contains a member which implements IDictionary or derives from DictionaryBase,
which causes XmlSerializer to throw an exception:
"System.NotSupportedException: The type X is not supported because it implements IDictionary".

Solution

Override XmlSerialization by making the type implement the System.Xml.Serialization.IXmlSerializable class. Define how you want the object to be serialized in XML in the WriteXml method, and define how you could recreate the object from an xml string in the ReadXml method.

Code

Download the full code here.

The WriteXml and ReadXml methods used in the sample follow.

public void WriteXml(System.Xml.XmlWriter writer)
{
	// Used while Serialization

	// Serialize each BizEntity this collection holds
	foreach( string key in this.Dictionary.Keys )
	{
		Serializer.Serialize(writer, this.Dictionary[key]);
	}
}

public void ReadXml(System.Xml.XmlReader reader)
{
	// Used while Deserialization

	// Move past container
	reader.Read();

	// Deserialize and add the BizEntitiy objects
	while( reader.NodeType != XmlNodeType.EndElement )
	{
		BizEntity entity;

		entity = Serializer.Deserialize(reader) as BizEntity;
		reader.MoveToContent();
		this.Dictionary.Add(entity.Key, entity);
	}
}

Description

By default, XML Serialization does not serialize types that implement IDictionary; it throws an exception when you attempt to do so. This comes quite in the way when you need to switch serialization techniques, or have custom collections which derive from DictionaryBase or any other sort of scenario.

The workaround for this problem is to let XML Serializer know how to serialize your IDictionary types yourself, by implementing the System.Xml.Serialization.IXmlSerializable class. This interface declares three methods - ReadXml, WriteXml and GetSchema.

When XmlSerializer attempts to serialize a type and finds that it implements IXmlSerializable, the serializer would simply pass control to the ReadXml (during deserialization) or WriteXml (during serialization) methods. In other words, you yourself handle how serialization and deserialization should happen.

Posted: Jan 15 2006, 12:42 PM by rakeshrajan | with no comments
Filed under:
This blog gets updated

Now that http://msmvps.com runs on CS (thanks a lot to Susan and team!), I will be cross posting for a while - here and at http://rakeshrajan.com/blog/.

Also, since some of the readers complain that the LuxLegend skin I am using isn't really attractive (maybe because it's pretty dark), I have set the skin here to LuxLegend - light :)

 

I have moved!

Friends, now that I have bought my own little niche in the web world, I have decided to shift this blog to this cool new place. It runs on Community Server with LuxLegend as the skin. Please update your links.

For your convenience, I have duplicated these posts at the new blog. However note that I haven’t copied comments or trackbacks. Please refer to this for the same.

Wish you a great time out there!

Posted: Oct 10 2005, 01:17 AM by rakeshrajan | with 2 comment(s)
Filed under:
Just posted a new article - Delegate and Events Internals
Check it out here:
http://www.codeproject.com/useritems/DelegatesNEventsInternals.asp
Posted: Oct 07 2005, 06:46 AM by rakeshrajan | with no comments
Filed under: ,
Off to the Global Summit! :)

A few more hours, and I will be on board the first flight of my trip to Redmond for attending the Global MVP Summit.

It's quite wonderful to know that within a few hours I will be meeting people I have only “seen” at newsgroups.

Hope the journey will go on fine.

Updates after I come back on October 5th.

See ya!

Posted: Sep 27 2005, 05:53 PM by rakeshrajan | with 3 comment(s)
Filed under:
.NET Certifications FAQ

This is something that comes up frequently.

Check out the below link I wrote a long long time ago. Hope it has some helpful information. Please drop me a mail if you have questions.

http://t-mug.org/certification.aspx

 

Posted: Sep 23 2005, 01:57 AM by rakeshrajan | with no comments
Filed under:
How to make Visual Studio .NET create web projects in a user defined folder

Just published this here:
http://support.microsoft.com/kb/555436

Posted: Aug 22 2005, 09:57 AM by rakeshrajan | with 5 comment(s)
Filed under:
How to share custom application configuration settings across projects in .NET

Just published this here:
http://support.microsoft.com/kb/555396

Interestingly, I had stumbled upon this while answering this post:
http://www.msdn.microsoft.com/newsgroups/default.aspx?dg=microsoft.public.dotnet.general&mid=ff9719e6-3829-4122-8b23-565087e9b1a4&sloc=en-us

Posted: Aug 16 2005, 02:12 PM by rakeshrajan | with 3 comment(s)
Filed under:
Session Start event in .NET 2.0 seems to be updated

In .NET 1.x, the session start event would be invoked if an unhandled exception propagates out of the application scope (in additional to the normal invocation). This meant that the code in the session start event handler may be called multiple times during the same session, which isn’t good.

I fiddled with little snippets of code in Whidbey beta 2, and it seems this has been resolved in .NET 2.0.

Posted: Aug 07 2005, 11:17 PM by rakeshrajan | with no comments
Filed under:
It's my birthday!

Dear folks, it's my birthday today! You ask how old I am? Keep guessing, 'coz I won't tell ;)

Hmm...come to think of it - I haven't decided on any new 'age' resolutions...so I guess I would just continue coding.

Nothing special planned for today...being a Saturday (which is a holiday for my company), I would miss out all fun of being at office on a b'day.
In case you didn't know, it's our unofficial custom @ office that b'day guys/gals get surrounded by collegues who would first sing the b'day song, 'present' a few b'day kicks and then finally scream 'Treat'!

Posted: Jul 30 2005, 06:21 PM by rakeshrajan | with 7 comment(s)
Filed under:
Bugs, developers and testers

Developers usually develop applications with the objective of getting the functionality up and running as quick as possible. After the functionality is complete, they would proceed to test their code.
Unfortunately, many developers are neither inclined to find bugs in their own code (for, that just means more work), nor would most have that special 'testing' knack to do so. That's where testers come in.

However, many testers I have seen weren't into hard-code development in their career; they were just testers from the very beginnings. There are good and bad points to this. Being completely ignorant about how an application is coded, the tester might be able to test things that would be extremely random and 'creative' – something a developer would have never thought.
For instance, I recently chanced to see such a tester testing an ASP.NET web form page which had several text-input boxes, one of which had a validation criterion of accepting (while typing) only numbers. After testing them by typing values into text boxes directly, this guy opened up an instance of notepad, typed in several words, copied them into the clipboard, and pasted it into the text box. The text box happily accepted the input without validating! These are things routine developers wouldn't think about.

However, testers who weren't developers before could miss out finding serious bugs. For example, some time back I was involved in an ASP.NET project for a short period of time. The project had a screen for displaying and editing information of a user, and the user ids were passed in the query string. Obviously, a user is supposed to view only his own information.
Now, the tester who was assigned this screen wasn't concerned about those "queer set of strings" in the address bar. Needless to say, he missed this very obvious but critical bug - a user could change the value passed in the query string to access information of any other user! Sadly though, the developer who coded the screen never thought of this bug either!

This brings us to this point – we need both non-dev 'creative' testers and the dev testers to test applications. Skipping over one of these can result in a product of inferior quality. We can't be sure that a developer would find bugs in his own code, unless he has a high degree of professionalism.

In my opinion, I feel a solution like follows could help ensure that both kinds of tests happen.

  • Make the technical lead of the project test the code of his team members, for he would (hopefully) have a greater deal of responsibility on product quality than his subordinates.
  • Assign a non-techie tester to test the application, so that he could find out the remaining 'creative' bugs.
  • And if you find the rare breed of developer/tester who can do both, hire him!

More importantly, flaws in the design and structure of the application are more critical (in magnitudes), and will have to be caught as early as possible. However, this will require a different kind of approach. More on this later...

HttpUnhandledException and HttpParseException - they are now Serializable :)

In .NET 1.x, these exceptions weren't serializable - which meant we couldn't persist/transport them in a direct manner.

Thankfully, .NET 2.0 has both of them serializable

 

Posted: Jul 08 2005, 07:09 PM by rakeshrajan | with 3 comment(s)
Filed under:
System.Data.OleDb.OleDbException: Unspecified error

System.Data.OleDb.OleDbException: Unspecified error while calling the Connection.Open method on an Access or Excel file within ASP.NET. This is an issue you could face while opening Excel or Access files as data sources in ASP.NET using OleDb Jet.

Cause Number 1

ASP.NET/Impersonated account doesn’t have enough privileges to create the ldb file.

Resolution Give the ASP.NET user account create/write privileges to the folder where the excel/access file is placed. If you are using impersonation, give the impersonated account the said privileges.



Cause Number 2

Impersonated account doesn’t have enough privileges to create temporary files.

Description When you open excel or access files using Jet, it requires creation of temporary files. Under ASP.NET, these files will be created under the C:\Documents and Settings\MachineName\ASPNET\Local Settings\Temp folder. By default, the ASP.NET user account is given full access to this folder. Now, when you are using impersonation, the impersonated account naturally wouldn’t have access to this folder. Consequently, the Jet engine wouldn’t be able to create the temporarily files while opening connections to excel or access files under ASP.NET. Due to this, the OleDb provider throws an exception with no specific message - System.Data.OleDb.OleDbException: Unspecified error.

Resolution Give the impersonated account full access to the above mentioned folder.
Check out the Microsoft support article here[^]

Posted: Jul 04 2005, 03:04 PM by rakeshrajan | with 5 comment(s)
Filed under:
Just finished uploading the MVP Summit pics

I just completed uploading pics from the MVP Summit held @ Singapore on April 2005 (yes...it was long overdue :( ).

Here are the MSN Spaces and .Text links to the photo albums:

So why did I add them at both locations? MSN's photo album features are really good (like uploading, slide show etc.)...but the pics look a bit odd...they seem to be rescaled with lesser quality. With .Text however, you need to struggle with uploading, live without the slide show and other cool features of MSN; yet, the pics looks great. That's why.

Happy browsing...

 

Posted: Jul 02 2005, 10:06 PM by rakeshrajan | with 2 comment(s)
Filed under:
Why Multiple Inheritance was not implemented in .NET

Just came across this blog entry on why Multiple Inheritance was not implemented in .NET.

http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85562.aspx

 

Posted: Jun 29 2005, 10:56 AM by rakeshrajan | with 20 comment(s)
Filed under:
Just posted my first ASP.NET article!

I just posted my first ever ASP.NET article :)

That too, after a significant time!

Hmm...I should write more frequently...

Posted: Jun 05 2005, 08:26 PM by rakeshrajan | with 4 comment(s)
Filed under:
How to find out the immediate calling method

Use the StackFrame and StackTrace classes.

For example:


	public static void SourceMethod()
	{
		TargetMethod();
	}

	public static void TargetMethod()
	{
		StackTrace st = new StackTrace();

		// This will output 'SourceMethod'
		Console.WriteLine(st.GetFrame(1).GetMethod().Name);
	}


Note:
Code optimizations might give you different results.  Some methods may even be completely optimized out.  But this code should work fine without any optimizations.

Posted: May 02 2005, 10:55 PM by rakeshrajan | with 2 comment(s)
Filed under:
Static readonly versus constants

Though both would appear similar – they are both read only and generate almost similar IL code – they have a number of differences.  Here they are:

Constants are evaluated at compile time, whereas static (or static readonly) variables at runtime.

So, when the compiler generates the IL, the value of the constant is burned into the IL wherever it is referenced.  Consequently, when you change the value of a constant, all the client applications referring the constant will have to be recompiled. 

However, if you change the value of a static field, you only need to recompile that library and none of the clients.  This is because the IL generated would only be referencing the static field, and will not have the value burned into it.

Though constants and readonly variables are both read only, readonly is a runtime constant, and can hold references types (like DataSet etc.).  Constants on the other hand cannot hold reference types except for string and null.

Yet another difference is that constants need to be initialized at the declaration itself, whereas readonly fields may be initialized either at the declaration or in a constructor (or in static constructors/type initializers).

Posted: May 01 2005, 11:03 AM by rakeshrajan | with 6 comment(s)
Filed under:
More Posts Next page »