in

ASP.NET Weblogs

Sijin Joseph's blog

My experiences with .Net

March 2005 - Posts

  • Why do we get paid so much?

    I was just thinking today about why software developers are typically paid so much more than other people in similar kind of work. One reason might be because software companies generate more revenue per employee as compared with other industries.

    Construction or any other engineering discipline is as complex as software, but software is unique in the sense that building software is the easy part, this is very different from the other engg. disciplines where manufacturing is the hard part. Think of construction, It is such an immensely complex task that if you don't know how it's done you'd wonder how anything even stands up. Can you imagine if we had bugs in skyscrapers? But coming back to the point, it means that constructing a building is like building a piece of software with a quality level so high that maybe only NASA can achieve. Then why don't construction people get outrageously high salaries?

    The answer IMHO is standardization, the construction industry is so standardized and they have such well-defined patterns that although to a layman a building construction may look incredibly complex, to the builder it's just like putting Lego blocks together.

    So that means if the vision of software factories becomes a reality, it would mean that building software would require an architect who would design the system and then junior guys just use standard off the shelf components to build it. Nirvana. Yeah but not for us,[ :)] once that happens the cost of software goes down and hence so do our  pays [:)]

    So why is that the software industry has not yet mastered component based development, again IMHO these things take time, again look at construction, human beings have been building ever since they moved out of the caves, serious architecture and building techniques have taken thousands of years to be perfected, how old is our industry? about 50 years, so we have a long way to go before we reach the level of sophistication that the consstructuon industry has. Which means that we are safe atleast in our lifetimes. [:)]

    Let's speculate a bit more and try to see into the future, so what will be the software industry of the next generation, my guess is bio-tech. Bio-tech is in it's nascent stages just like software was in the 50's and the 60's, but in the next few decades it's going to make a huge huge impact on our lives. And you can be sure that IIT or MIT elite will be opting for bio-tech rather than computers in about 10-15 years.

  • Cool sites discovered using Spiderous

    Spiderous is a site that aggregates popular links from social bookmark managers like del.icio.us , spurl and furl
     
    Here are some great links I found today
     
    Tabs on your webpage using CSS
     
    Like to build your own systems, check out this article on advanced system building
     
    Color Scheme generator
     
    Free Menu designs using CSS
     
    Fade anything technique for web pages
     
    The state of the scripting universe
     
    A+ Freeware

    Posted Mar 23 2005, 01:28 PM by Sijin Joseph with no comments
    Filed under:
  • ADO.Net connection pooling

    I was reading up on ADO.Net connection pooling yesterday, here is some info that I gathered.
     
    The below excrepts are from - Pragmatic ADO.Net (An excellent excellent book on ADO.Net)
     
    Connection Pooling

    Connections are precious commodities, and writing code to minimize the stress on the server of having too many connections open concurrently will help with overall database performance. Fortunately, ADO.NET (like its predecessors) tries to help manage those connections with a facility called Connection Pooling. Connection Pooling is the process of managing connections as shared resources that can be doled out from a pool of recently used connections. Connection pooling takes advantage of the fact that many different parts of most applications require connections for a short amount of time as well as the fact that building and tearing down connections is an inherently expensive operation. Connection pooling is a method of reusing connections. The real magic occurs when connections are closed, because the pool hangs on to the connection for some short time (the pooling timeout) before actually closing the connection. If another connection is requested before that short amount of time has elapsed, it hands the open connection to the requestor. This saves the actual work of tearing down the connection and opening a new one. By utilizing connection pooling, you reduce the likelihood of making a round trip to the database only to find out that the database is out of connections. The connection pool reduces the time it takes to determine the out-of-connections state. In fact, with the connection pool, the additional requests can block to wait for a new connection to be available. This allows a machine to throttle its actual usage of the database so as not to swamp a particular database server with requests.

    Each of the managed providers handles connection pooling differently. Although connection pooling is mostly transparent to the database developer, understanding how the different pooling mechanisms work allows you to write code that will take advantage of the connection pooling.

    2.2.4.1 SQL Server Managed Provider's Connection Pooling

    The SQL Server Managed Provider creates a pool of connections that have identical connection strings—these connection strings must be byte-for-byte identical. The managed provider simply matches identical connection strings in the pool. It uses the connection strings that a connection has after it has been set, not the connection strings you set. For example, if I create a connection with the connection string of "Server=localhost;Database=ADONET;", after I set it the connection will have all of the defaults in the connection string, including security information (unless you have specified not to persist it). What this means is that if you are trying to pool connections and you are using integrated security, your connections will not pool because the security information in the connection string will be different from that in the pool (because the different users each will have their own security identity and credentials embedded into the connection string, so they can't be identical to another user's connection string).

    SQL Server's Managed Provider implements the pooling facilities down in the bowels of the System.Data namespace.[4] If you want to watch the pooling, use the SQL Server Profiler to see the connections created and destroyed. The SQL Server Managed Provider gives us limited influence over how the pooling works. It exposes the pool settings through the connection string.

    [4] Note: The SQL Server Managed Provider's connection pooling is not enabled while running under Visual Studio .NET's debugger.

    2.2.4.2 OLE DB Managed Provider's Connection Pooling

    The OLE DB Managed Provider handles connection pooling much differently than the SQL Server Managed Provider. With the OleDbConnection class, the underlying OLE DB provider (not the ADO.NET managed provider) handles the connection pooling. This process is transparent to the ADO.NET developer with the exception of the OleDbConnection.ReleaseObjectPool() static method, which alerts the underlying provider that your code will not be using data access for some period of time and that it can destroy the object pool after all the connections are returned. This helps OLE DB shut down more effectively. Because the pool and the connections have a specific amount of time to live, these connections normally will not be destroyed for that period of time. By calling the ReleaseObjectPool() method, this destruction will be more timely.

    An OLE DB provider enables a number of services including connection pooling (which it calls resource pooling), transaction auto-enlistment, and client-side cursors. These services are enabled or disabled based on the provider's OLEDB_SERVICES Registry key. Because changing this Registry key would cause all applications on that machine to be affected by that change, the preferred method is to use the OLE DB Services connection string attribute to modify the behavior.

    For example, if I wanted to disable pooling and automatic transaction enlistment, I would do the following:

    OleDbConnection conn = new OleDbConnection("Server=localhost;" +                                "OLE DB Services=-4;" +                                "Integrated Security=true");conn.Open();

    Other than in the connection string, there is no way to control this behavior. The IDataInitialize::GetDataSource() OLE DB call can initialize it with specific values, but this is really only useful when you are calling OLE DB directly or within an OLE DB provider.

    2.2.4.3 Oracle Managed Provider's Connection Pooling

    The Oracle Managed Provider implements connection pooling much like the SQL Server Managed Provider. In other words, connections are pooled by identical connection strings within a single process. Several settings can be specified in the connection string to change the default behavior of Oracle Managed Provider's connection pooling.

     

    2.2.4.4 ODBC Managed Provider's Connection Pooling

    The ODBC Managed Provider has no native support for connection pooling; however, in ODBC 3.0 and above there is support for connection pooling. There are two methods for enabling ODBC connection pooling; neither of them has anything to do with ADO.NET. First, if you have the ODBC Data Source Administrator 3.5 or above, you can use the Connection Pooling tab Simply double-click the driver name and enable or disable the connection pooling . This will affect all software on the computer.

     

    The other method for enabling ODBC connection pooling is to call the ODBC API to enable connection pooling during your process. You do this by importing the ODBC call with DLLImport. Listing 2.4 shows how I have wrapped the calls into a simple class.

    Listing 2.4 Enabling ODBC Connection Pooling
    /*  Example Usage:    ODBCPooling.Enable();*/public class ODBCPooling{  [System.Runtime.InteropServices.DllImport       ("odbc32.dll",       CharSet=System.Runtime.InteropServices.CharSet.Auto)]  private static extern int SQLSetEnvAttr(                                   long Environment,                                   long EnvAttribute,                                   long ValuePtr,                                   long StringLength);  const long SQL_ATTR_CONNECTION_POOLING = 201;  const long SQL_CP_ONE_PER_DRIVER = 1;  const long SQL_IS_INTEGER = -6;  const long SQL_CP_OFF = 0;  static int Enable()  {    return SQLSetEnvAttr( 0,                          SQL_ATTR_CONNECTION_POOLING,                          SQL_CP_ONE_PER_DRIVER,                          SQL_IS_INTEGER);  }  static int Disable()  {    return SQLSetEnvAttr( 0,                          SQL_ATTR_CONNECTION_POOLING,                          SQL_CP_OFF,                          SQL_IS_INTEGER);  }}

    You only need to do this once per process to enable the pooling of connections. You can turn pooling for ODBC on and off by enabling or disabling it with this class. Unfortunately, there is no support for configuring the pooling beyond just enabling or disabling it.

     

    So it seems that the different providers have different techniques for pooling. I also found an interesting article on how Sql provider does connection pooling internally and how you can force the pool to be flushed, you can read it at

    http://www.sys-con.com/dotnet/article.cfm?id=483

    The below article discusses connection pooling in Microsoft Data Access Components(MDAC) 

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnmdac/html/pooling2.asp

    The below article provides an in-depth look in general data access using .Net and has good coverage on connection pooling.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daag.asp


    Posted Mar 23 2005, 11:42 AM by Sijin Joseph with 7 comment(s)
    Filed under:
  • Notes from Webchat on serialization in .Net

    I had hosted a webchat on serialization in .Net today, will be posting the link to the transcript as soon as it is up.

    Bascially the areas I discussed were, Runtime serialization and Xml Serialization. Versioning issues, common problems with serialization and what's new in .Net 2.0

    Here are the notes I used for the webchat, pretty unorganized. Hope to put all this into an article soon.

    Serialization in .Net

     What is serialization?

    Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location. Deserialization is the process of taking in stored information and recreating objects from it.

     

    What can it be used for?

    Preserve the state of your application to persistent storage.
    Distributed communication (Remoting and web services use serialization)
    Deep copies of objects
    Storing config information

     

    Site settings using XmlSerializer
    http://codebetter.com/blogs/david.hayden/archive/2005/03/01/56226.aspx

     XmlSerializerSectionHandler
    http://pluralsight.com/wiki/default.aspx/Craig/XmlSerializerSectionHandler.html

     In .Net the support for serialization is in two namespaces

    System.Runtime.Serialization – The classes in this namespace facilitate “runtime serialization”. The goal here is to preserve as much type information as possible and then recreate the object with the type information on Deserialization. Requires that the objects have the Serializable attribute. And the Serialization Formatter permission is required which is only granted to local apps by default.

     System.Xml.Serialization – The classes in this namespace facilitate XML serialization. The goal here is to provide a high performance mechanism to convert objects into XML. Only public fields and properties of the object are preserved. Used if communication between heterogeneous systems is required. Requires no special security permissions. Has a lot of restrictions as to what can be serialized and what cannot.

     
    In runtime serialization

     Two aspects of serialization

                What needs to be serialized
                How is the serialized data formatted

     In .net we can do serialization using the Serializable attribute or by implementing ISerializable interface.

    In case we choose Serializable attribute the formatters use reflection to get the data that needs to be serialized. Binary and SoapFormatters will serialize every field in the object including private and protected ones. It does not serialize fields marked with the NonSerialized attribute.

     
    If the object implements ISerializable it gets complete control over the serialization and deserialization process.
    ISerializable has only one method GetObjectData(), for Deserialization a special ctor is required. Which should be made protected and private if the class is sealed.

                 BinaryFormatter
                            Writes the data to be serialized in binary format. Most efficient formatter but not useful for open systems.

                 SoapFormatter
                            Writes the data to be serialized in the SOAP 1.1 format. Less efficient but a must if interoperability is a requirement. Used by remoting.

     StreamingContext

                An enumeration that can be used to decide what to serialize based on the context in which serialization is taking place. For example if the context is cross process then system wide handles like files etc. can be saved as is. The context can be specified in the constructor of the formatter. Contains information about the destination of the serialized message. It is passed to objects that handle their own serialization through ISerializable.

     Versioning

    SerializationBinder
                For Assembly and Type resolution. Allows you to handle things like change in class name, change in namespace etc.
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemruntimeserializationserializationbinderclasstopic.asp

     SerializationSurrogate

                Allows another class to handle the serialization of an object. Allows you to handle the case where there is an object that does not support serialization and cannot be inherited or wrapped. The problem here is that the surrogate receives a uninitialized object i.e. no ctors have run. Also can only access public fields and properties, has to resort to reflection to access private, protected members.

     An implementation of serialization surrogate that uses reflection
    http://weblogs.asp.net/rosherove/archive/2005/03/03/384267.aspx

     Implementation of surrogates for binary serialization of datasets
    http://msdn.microsoft.com/msdnmag/issues/04/10/CuttingEdge/

     http://www.topxml.com/xmlserializer/surrogateselectors.asp

     IDeserializationCallback
                Allows objects to do post serialization initialization.

     http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemruntimeserializationideserializationcallbackclasstopic.asp

     
    XmlSerializer

                            Allows objects to be stored in XML format. Webservices internally use XmlSerializer to convert objects into SOAP format. Focuses on mapping .Net classes to arbitrary XML formats or formats defined via a schema. Optimized for performance. Takes the type to serialize in the ctor and uses the type information to give high performance while serializing and deserializing. Works only with public field and properties(provided they have both get and set properties), this is to facilitate working in restricted conditions like the intranet and internet.

     
    Restrictions on types that can be serialized using XmlSerializer
    http://www.topxml.com/xmlserializer/serializable_classes.asp

     Controlling Xml serialization via attributes
    http://www.topxml.com/xmlserializer/serialization_attributes.asp

     Attrbutes that control Xml Serialization
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconattributesthatcontrolserialization.asp

     Controlling Xml serialization using attributes
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcontrollingserializationbyxmlserializerwithattributes.asp

     When type is passed as ctor, it creates a type mapping table which it uses for serialization.

     XmlIncludeAttribute is applied on the base class to specify all derived types. Or we can use XmlElementAttribute on a field to specify the types of objects that we expect by setting the DataType property.

     For Arrays we can either use the XmlElement attribute in which case the root node for arrays is not used. Or we can use XmlArray and XmlArrayItem to control how array and array elements are serialized.

     Any class that implements IEnumerable or ICollection can be serialized and serialization can be controlled using XmlArray and XmlArrayItem attributes. When XmlSerializer detects a collection it does not serialize the public properties of the class.

     Xsd.exe can be used to generate .Net classes from an xsd schema

     Advanced Xml serialization

    This can be used if we cannot attach attributes to the class, or it is not known beforehand.

     Global types – can be specified in the ctor by passing an array of additional types.

     XmlAttributeOverrides – again is specified via the ctor. XmlAttributeOverrides has two overloads of Add to apply attributes to type or to an element within a type. XmlAttributes class needs to be passed to Add() this contains strongly typed properties for the various attributes that can be applied.

     Choice elements

    We can use an enumeration with XmlChoiceIdentifier to handle these situations.

     Namespaces

    XmlSerializerNameSpaces class, and XmlNamespaceDecalaration or can be passed in the ctor of the XmlSerializer.
    XmlSerializerNameSpaces used to map prefixes to namespaces.

     

    Soap encoding using XmlSerializer

    Using SoapReflectionImporter to generate TypeMapping which is passed to ctor of XmlSerialzier

    Can be customized using SoapAttributeOverrides which takes a SoapAttributes corresponding to a type or to a member in the type.

     

    Handling versioning problems with XmlSerializer, provides  events when it encounters unknown element, unknown node etc. Alternatively you can apply the XmlAnyElement or XmlAnyAttribute attribute to an array of type XmlElement and that will contain all unresolved elements and attributes.

     

    Troubleshooting common problems with XmlSerialzier
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnxmlnet/html/trblshtxsd.asp

     
    *XmlPreSerializer, XmlReflectionImporter, SoapReflectionImporter

     Serialization and remoting

                Remoting uses serialization to transport marshal-by-value objects.

     Serialization and datasets

                DataSets convert to XML by implementing the IXmlSerializable interface

     Common problems in serialization

                Delegates and serialization, solved by using the field:NonSerialized option. Versioning. Objects that cannot be serialized via XmlSerializer. Permission problems.

     What’s new in serialization in .Net 2.0

                http://msdn.microsoft.com/msdnmag/issues/04/10/AdvancedSerialization/default.aspx

                 OptionalFieldAttribute

                OnDeserializing/OnDeserialized OnSerializing/OnSerialized ,
    these events are only defined for BinaryFormatter. No new stuff has been added for the SoapFormatter.

     XmlFormatter class is now supporting all these Deserialization events.  It also supports two modes SharedContract and SharedType.

    More info at

       http://weblogs.asp.net/cschittko/archive/2003/10/29/34414.aspx

    http://www.douglasp.com/CommentView.aspx?guid=bff35b26-4739-4971-9a05-507e5aaddd7a

     SoapFormatter has been deprecated in .Net 2.0 no new features have been added.  XmlFormatter is the successor to that

     IXmlSerializable is now documented and can be used in applications to get control over xml serialization.

    GetSchema(), ReadXml() and WriteXml() are the methods. XmlSchemaProvider attribute

     

    Sample code illustrating use of IXmlSerializable

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/wsnetfx2.asp

    How does that address some of the problems present in the current implementation?

                OptionalField allow us to specify a field as optional and a version in which it was added. Thus when a new version is deserialized the formatter does not thrown an exception if the type does not contain that field. The serialization events give more control.

     Example of OptionalField

    http://fredrik.nsquared2.com/viewpost.aspx?PostID=174

     Links:

     How to serialize a hashtable

    http://codebetter.com/blogs/geoff.appleby/archive/2004/11/13/32005.aspx

     Handling non serializable events in .Net 2.0 using VB.Net

    http://www.lhotka.net/WeBlog/PermaLink.aspx?guid=8f8ae33f-f3b3-4864-a146-4f852d78783e

     

     And here are the code snippets I used during the chat

    /* Creating deep copies using serialization
     *
    [Serializable]
    public class Customer
    {
        public string Name;
        public Address Address = new Address();
       
        public Customer(string name)
        {
            this.Name = name;
        }

        public Customer DeepCopy()
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            Customer clone = (Customer)formatter.Deserialize(stream);
            return clone;
        }

        public Customer ShallowCopy()
        {
            return (Customer)this.MemberwiseClone();
        }
    }

    [Serializable]
    public class Address
    {
        public string Street;
        public string Pin;
        public string City;
    }


    [STAThread]
    static void Main(string[] args)
    {
        Customer obj1 = new Customer("Henry");
        obj1.Address.City = "Bangalore";
        obj1.Address.Street = "Banergatta";
        obj1.Address.Pin = "560076";

        Customer obj2 = (Customer)obj1.ShallowCopy();
        Customer obj3 = (Customer)obj1.DeepCopy();

        Debug.Assert(Object.ReferenceEquals(obj1.Name, obj2.Name));
        Debug.Assert(Object.ReferenceEquals(obj1.Address, obj2.Address));

        Debug.Assert(! Object.ReferenceEquals(obj1.Name, obj3.Name));
        Debug.Assert(! Object.ReferenceEquals(obj1.Address, obj3.Address));
       
        System.Console.ReadLine();
    }

    */


    /* Storing user settings
     *
    public class UserSettings
    {
        private Point _mainFormPosition = Point.Empty;
        public Point MainFormPosition
        {
            get{ return _mainFormPosition; }
            set{ _mainFormPosition = value; }
        }

        private Size _mainFormSize = Size.Empty;
        public Size MainFormSize
        {
            get{ return _mainFormSize; }
            set{ _mainFormSize = value; }
        }

        private float _conversionFactor = float.MinValue;
        public float ConversionFactor
        {
            get{ return _conversionFactor; }
            set{ _conversionFactor = value; }
        }
    }


    [STAThread]
    static void Main(string[] args)
    {
        UserSettings settings = new UserSettings();
        settings.ConversionFactor = 10;
        settings.MainFormPosition = new Point(100,100);
        settings.MainFormSize = new Size(640, 480);

        XmlSerializer serializer = new XmlSerializer(typeof(UserSettings));
        XmlTextWriter writer = new XmlTextWriter("settings.xml", System.Text.Encoding.UTF8);
        writer.Formatting = Formatting.Indented;
        serializer.Serialize(writer, settings);
        writer.Close();

        System.Console.ReadLine();
    }

    /* Output
    <?xml version="1.0" encoding="utf-8"?>
    <UserSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <MainFormPosition>
        <X>100</X>
        <Y>100</Y>
      </MainFormPosition>
      <MainFormSize>
        <Width>640</Width>
        <Height>480</Height>
      </MainFormSize>
      <ConversionFactor>10</ConversionFactor>
    </UserSettings>
    */



    /* Simple runtime serialization with SoapFormatter
    [Serializable]
    public class Customer
    {
        public string Name;
        public ArrayList Orders = new ArrayList();

        [NonSerialized]
        public string DataThatShouldNotBeSerialized;

        public Customer(string name)
        {
            this.Name = name;
        }
    }

    [Serializable]
    public class Order
    {
        public string Product;
        public int Quantity;
        public Customer Customer;

        public Order(string product, int quantity, Customer customer)
        {
            this.Product = product;
            this.Quantity = quantity;
            this.Customer = customer;
        }
    }


    Customer customer = new Customer("James");
    customer.DataThatShouldNotBeSerialized = "Random data";
    Order order1 = new Order("Motherboard", 2, customer);
    Order order2 = new Order("CPU", 2, customer);
    customer.Orders.Add(order1);
    customer.Orders.Add(order2);

    SoapFormatter formatter = new SoapFormatter();
    FileStream stream = new FileStream("customer.xml", FileMode.Create);
    formatter.Serialize(stream, customer);
    stream.Close();
    */


    /* Custom runtime serialization with SoapFormatter
    [Serializable]
    public class Customer : ISerializable
    {
        public string Name;
        public ArrayList Orders = new ArrayList();

        public string DataThatShouldNotBeSerialized;

        public Customer(string name)
        {
            this.Name = name;
        }

    #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Name", Name);
            info.AddValue("Orders", Orders);
        }

        private Customer(SerializationInfo info, StreamingContext context)
        {
            Name = info.GetString("Name");
            Orders = (ArrayList)info.GetValue("Orders", typeof(ArrayList));
        }
    #endregion
    }

    [Serializable]
    public class Order
    {
        public string Product;
        public int Quantity;
        public Customer Customer;

        public Order(string product, int quantity, Customer customer)
        {
            this.Product = product;
            this.Quantity = quantity;
            this.Customer = customer;
        }
    }


    Customer customer = new Customer("James");
    customer.DataThatShouldNotBeSerialized = "Random data";
    Order order1 = new Order("Motherboard", 2, customer);
    Order order2 = new Order("CPU", 2, customer);
    customer.Orders.Add(order1);
    customer.Orders.Add(order2);

    SoapFormatter formatter = new SoapFormatter();
    FileStream stream = new FileStream("customer.xml", FileMode.Create);
    formatter.Serialize(stream, customer);
    stream.Close();
    */


    /* New serialization events in .Net 2.0
        
    [Serializable]
    public class Employee
    {
        private string _name;
       
        public string Name
        {
            get{ return _name; }
            set{ _name = value; }
        }
       
        public Employee(string name)
        {
            _name = name;
        }
       
        [OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            Console.WriteLine("Serializing");
        }
       
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
            Console.WriteLine("Serialized");
        }
       
        [OnDeserializing]
        private void OnDeserializing(StreamingContext context)
        {
            Console.WriteLine("DeSerializing");
        }
       
        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            Console.WriteLine("DeSerialized");
        }
    }


    Employee emp = new Employee("Mark");

    BinaryFormatter formatter = new BinaryFormatter();
    FileStream stream = new FileStream("employee.dat", FileMode.Create);

    formatter.Serialize(stream, emp);
    stream.Seek(0, SeekOrigin.Begin);

    emp = (Employee)formatter.Deserialize(stream);

    stream.Close();
       
    /*
    This will output

    Serializing
    Serialized
    Deserializing
    Deserialized
    */

     
    /* Simple Xml serialization
    public class Employee
    {
        public int ID;
        public string Name;
        public string Department;
    }

    Employee emp = new Employee();
    emp.ID = 1001;
    emp.Name = "Mark";
    emp.Department = "Accounts";

    XmlSerializer serializer = new XmlSerializer(typeof(Employee));
    XmlTextWriter writer = new XmlTextWriter("employee.xml", System.Text.Encoding.UTF8);
    writer.Formatting = Formatting.Indented;
    serializer.Serialize(writer, emp);

    writer.Close();

    Output is
    <?xml version="1.0" encoding="utf-8"?>
    <Employee xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <ID>1001</ID>
      <Name>Mark</Name>
      <Department>Accounts</Department>
    </Employee>



    [XmlRoot("employee")]
    public class Employee
    {
        [XmlAttribute("id")]
        public int ID;

        [XmlElement("name")]
        public string Name;

        [XmlElement("department")]
        public string Department;
    }

    <?xml version="1.0" encoding="utf-8"?>
    <employee xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="1001">
      <name>Mark</name>
      <department>Accounts</department>
    </employee>
    */



    Posted Mar 16 2005, 07:40 PM by Sijin Joseph with no comments
    Filed under:
  • Using spiderous to discover cool sites

    Once I started using del.icio.us for managing my bookmarks, I came across this site called spiderous which aggregates popular and new bookmarks from sites like del.icio.us , spurl, furl and a couple of others.

    I make it a point to check out the popular links on a daily basis, you can find some really good stuff.

    For example, today I found these great links

    A Programmers guide to the mind - An excellent article on how the mind works and how to best utilize it.

    The Selfish Class - A theory on how to promote code reuse using the principles of evolution.

    Also for those interested in cognitive science, here is a great site http://www.cognitivedaily.com/

  • Excellent article on how to start a startup

    Paul Graham who has written an excellent article on how to start a startup. He is also the author of a great book called Hackers and Painters, a definte read.

    http://www.paulgraham.com/start.html
  • Load event gets fired on each call to ShowDialog()

    While chasing down one bug in my custom message box at codeproject I came acorss an interesting fact. If you use ShowDialog() to show your form then the Load event gets fired everytime. I've been using Winforms for such a long time and was surprised that I had never really come across this behaviour.

    It's not a bug, if you use reflector and take a look at Form.ShowDialog() you will see that the flag which is used to prevent Load event from getting fired more than once is disabled everytime ShowDialog() gets called.
    Posted Mar 09 2005, 12:52 PM by Sijin Joseph with 1 comment(s)
    Filed under:
  • How to hire Programmers

More Posts