This Blog Has Been Moved !

This Blog Has been moved to http://aleemkhan.wordpress.com

Serialization is used to persist the state of the object, so the object can be regenerated with the same state later. .NET provides different types of serializations for objects,

  • BinaryFormatter for bunary serialization
  • XMLSerializer class for XML Serialization
  • SoapFormatter class for Soap Serialization.

You can use these objects for serialization. The Framework also needs to serialize the objects at various places for example in case of web services, the objects needs to be serialized for communication, in case of Remoting and also if the object is to be passed across the boundary of an Application Domain or the process. In all these cases, the framework will only be able to successfully serialize your objects if your objects are serializable.  

All the basic .NET types are serializable except Object, there are various other base classes which are by default serializable and can be successfully used in above scenarios, this includes the very commnly used DataSet, DataTable and other class, the complete list is

These classes are serializable because they implement the ISerializable Interface.

To set your own types Serializable, the most common way is to set the class/type with the [System.Serializable()] attribute, also use the [System.NonSerialized()] for the members that you don’t want to serialize. See the following example

 

[System.Serializable]

class TestClass

{

      private string str = "Check";

      [System.NonSerialized()]

      private SqlCommand cmd = new SqlCommand();

      private int count;

     

      public CheckFunction()

      {

            ........

            ........

      }

}

 

However, using the serializable attribute is not the only way, and in some cases is not enough, specially if you are serializing complex objects which are inherited from other base objects. To serialize such objects you can have better control over serialization by implementing the ISerializable interface. This interface has only one method, which is GetObjectData(), this method is called when the object is to be serialized and you need to provide an extra constructor in the class to provide the de-serialization mechanism to regenerate the object. While serialization in GetObjectData() method, you can add your values to SerializationInfo parameter. During de-serialization you can get the values from the SerializationInfo object and set the values to the members of the class to regenarte the object in the same state. The example below will give you can idea

 

class TestClass : ISerializable

{

      private string str = "Check";

      private int count;

     

public TestClass(SerializationInfo info, StreamingContext context)

{

            this.str = info.GetString("str");

            this.count = info.GetInt32("count");

      }

 

      public void GetObjectData(SerializationInfo info, StreamingContext context)

      {

            // TODO:  Add TestClass.GetObjectData implementation

            info.AddValue("str",str);

            info.AddValue("count",count);

      }

}

 

Generally, as the MS guidelines and PAG documents say, serialization is not recommended for your custom objects, it has various issues regarding performance, security and scalability. But sometimes you have no other option then to use serialization. PAG guidelines do not recommend serialization and due to valid reasons but do not tell any other way you could get around the typical problems without serialization.

 

Just added the Jessica’s blog link to my outlook.

It has got a lots stuff on WinForms, could not get time to read as yet.

 

 

 

Have you seen Orkut, Google Suggest, Google Maps. Are you amazed by the wonderful web experience? They are using AJAX. AJAX is a really good technique; I don’t call it a technology because it is nothing new, just a blend of few established technologies like JavaScript, XML etc.

To learn about the actual idea behind AJAX, you can go through the article http://www.adaptivepath.com/publications/essays/archives/000385.php.

There are many implementations and third party AJAX libraries available, the idea is not so difficult and you can even implement it yourself without using any library provided that you have time.

Anyway, for .NET programmers AJAX.NET is available, you can download the C# source form https://svn.borgworx.net/SVN/BorgWorX/trunk/Web/Core/Ajax/

Creating an application with AJAX.NET is not very difficult, just a few basic steps you need to follow, here is a good article at MSDN

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/ASPNetSpicedAjax.asp about using AJAX.NET.

 

Fiddler is a really cool tool for HTTP Debugging. I have used it for some apps for testing and analyzing the requests from the app and the corresponding responses. You can get Fiddler Here: http://www.fiddlertool.com/fiddler/

 

Finally, after so much effort I have WinFX Runtime Beta1 installed on my system with Visual Studio.NET Beta 2. Could’nt get the WinFX SDK installed as yet so I don’t have the XAMLPAd. I downloaded the source for the Chris Anderson’s AvPad and it ran fine.

 

Wrote my first small Avalon application also; actually I just ran a sample to test everything is properly setup. I thought I’ll write some useful application by the end of the day today but could not get time. Its 11:15 PM now and I need to go home so maybe tomorrow I’ll try to write some Avalon code.

I am still figuring out the XAML and the procedural code relationship in Avalon, I never liked these split architectures. You have to write XAML and then the procedural code and somehow they work together. Also, I know you can Avalon App in pure procedural code without XAML.

 

I need to do some work on this and get comfortable with this new stuff, and by the way where WinForms stand now, you can still create a WinForm app, I still have to compare these two application types and what are the best places/scenarios for using each of them.

 

Anyway, VisualStudio.NET Beta 2 is amazing. The development experience is great, very comfortable and elegant. The new Error Window is really wonderful with that grid view.

 

I was thinking that Microsoft may be going too fast in some of its development; they should not update the products/specs so frequently. I downloaded C# 3.0 enhancements document today (haven’t seen it though). Now ppl haven’t used C# 2.0 as yet. Most people in my environment and other local software houses are using VS.NET 2003. C# 2.0 and Whidbey are still in the Beta and now they are proposing new C# 3.0.

Maybe this is because they have so many problems with these products that they tend to improve them continuously but this has a real bad effect on the programmer productivity. Most programmers are not able to get benefit and utilize the new features and changes. I think people at Microsoft and surrounding environment do benefit from everything that they add but medium/small companies are not using most of the new features.

 

I think they need to make a few solid releases without tweaking the things so often, if they need to get the Windows Vista and Widbey some real success at all levels.

 

Ok ! Its late .. I am leaving .. Bye!

 

Hey,

 

I just got a mail from one of the friends, he wants to get the information about the printer like printer status, error, current status etc, I thought I should share the answer with all.

 

Yes there are ways to do this, the most common answer to almost anything related to any information in Windows is

WMI (Windows Management Instrumentation), this is the layer windows provides and uses for retrieving all sorts of information from the system and the running kernel.

 

In the following code I have listed all your printers on the system and also some of their properties/status like printing, stopped etc, but I can’t possibly list everything.

There is tons of information you can get about printer using WMI Win32_Printer class. Please refer to

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_printer.asp and modify this code according to what you actually need.

 

 

using System;

using System.Diagnostics;

using System.Management;

using System.ComponentModel;

 

namespace ConsoleWMI

{

      class Class1

      {

            [STAThread]

            static void Main(string[] args)

            {

                  new Class1();

                                   

            }

            public Class1()

            {

                  System.Management.ManagementObjectSearcher searcher = new ManagementObjectSearcher

                        ("SELECT * FROM Win32_Printer");

                 

                  foreach (ManagementObject service in searcher.Get())

                  {

                              string [] pStatus = {"Other","Unknown","Idle","Printing","WarmUp","Stopped Printing", "Offline"};

                              string [] pState = {"Paused","Error","Pending Deletion","Paper Jam","Paper Out","Manual Feed","Paper Problem",

                                                         "Offline","IO Active","Busy","Printing","Output Bin Full","Not Available","Waiting",

                                                         "Processing","Initialization","Warming Up","Toner Low","No Toner","Page Punt",

                                                         "User Intervention Required","Out of Memory","Door Open","Server_Unknown","Power Save"};

 

                              foreach(System.Management.PropertyData pData in service.Properties)

                              {

                                    if(pData.Name == "Caption" || pData.Name == "Default" || pData.Name=="ServerName")

                                          Console.WriteLine(pData.Name + " = " + pData.Value);

                                    else if(pData.Name == "PrinterState")

                                          Console.WriteLine(pData.Name + " = " + pState[Convert.ToInt32(pData.Value)]);

                                    else if(pData.Name == "PrinterStatus")

                                          Console.WriteLine(pData.Name + " = " + pStatus[Convert.ToInt32(pData.Value)]);

 

                              }

                              Console.WriteLine();

                  }

                  Console.ReadLine();

            }

     

      }

}

 


These are the configurations of the cluster we set-up with two Windows 2003 Web Servers and a DB Server (see last post to catch up) . It is'nt a pure cluster actually but the Application Load Balancing, the load balancing service (available in Windows 2003 Server, I think its also in 2000 server but have'nt checked that) distributes the application requests among both the servers.

In contrast to this load balancing setup, a pure cluster also manages the server fail overs and the state of the servers, but it needs an extra bit of hardware, maybe i'll say something about that once we have that setup also.

This Load Balancing service in Windows 2003 Server is also interesting, I'll write a step-by-step process to setup NLB when next time I get to blog :) .. so stay tunned .... Also, there are a few other intersting things coming up, I think i'll be active here ...... C ya !

This last week was great for learning. We had to setup our ASP.NET app on multiple web-servers/webcluster, the major issue in this case is that how session will be managed accross the cluster of webservers. ASP.NET Sessions can be managed in three ways, I’ll just go briefly here and then you can go through the references if you need details

1- In-Proc Session Management: This is what we have in a default ASP.NET application. The ASP.NET worker process aspnet_wp.exe manages all processes.

2- Centralized Session State Server: The second way in which the ASP.NET sessions can be managed is through the Session State Server, which is the session management out of the process, in other words you can set the sessions to be managed on a separate machine and then all the web-servers can access the user session from there. (In my opinion this is the best way to go for a webfarm) .NET Framework comes with a Session State Service which u can run from the SCM. There is a <sessionstate> attribute in the application web.config file which needs to be set for the state server and you are ready to go.

3- Session Management with SQL-Server: The last method is the session management through the SQL-Server; you can manage the session in a SQL Server DB.

 

Although, the Framework provides the mechanisms but changing the way your application manages the state is not seamless and there are a lot of consideration which are to be taken during the application design if you want to make your application scalable for such an environment.

If you are implementing sessions through state server or through SQL-Server, in other words managing sessions out of the process, the objects placed in the sessions are serialized/de-serialized on each access. Now you need to insure that all the objects that you keep in sessions are Serializable otherwise the application will crash which trying to serialize a non-serializable object. Framework provides support for the native objects so they seem to serialize without any problem, apart from them there are a lot of other built-In library classes which implement the ISerializable interface which make them inherently serializable, this includes the DataSet and DataTable objects which are commonly used through the sessions. Still, there are other objects that you keep in sessions and you need to make them serializable.

Serialization/De-Serialization also introduces a performance overhead but in a cluster environment you have to bear that cost to enhance the application performance.

Setting the serialization is not very difficult; you can set the [Serializable] attribute over a class to make this class serializable provided that all its members are either serializable or native types. There are various issues involved with setting a type as serializable including the security and performance issues and generally setting serialization for your classes is not recommended but there seems no other solution if we need to manage the session out of process.

Maybe while designing the application you can avoid the use of your custom types through sessions so don’t need to keep them in the session. You can also implement the ISerialiable and implement its GetObjectData() method to get a better control over serialization.

For furthur descussion about session states
http://www.msdn.microsoft.com/netframework/technologyinfo/infrastructure/tuning/default.aspx

For further discussion about the serialization issue http://msdn.microsoft.com/msdnmag/issues/05/09/SessionState/Default.aspx


Yahoo! for Good
Click here to donate to the Hurricane Katrina relief effort.