Getting Last inserted Identity value in SQL server

In this article I would like to share my idea about getting Identity after a row was inserted in to the SQL Server 2005.
After inserting a row into the database which has primary key feild, most of the time we need the identity, We have three approches based on our reqiurements and situations.

SELECT @@IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT(‘TableName’)

All of the abouve three will get the identity value but in different approches.

The variable @@IDENTITY will return the last generated identity value produced on a connection, without based on the table that produced the value. While @@IDENTITY is limited to the current session, it is not limited to the current scope. This means that if we insert some record in Table1 which has a trigger on the insert and the trigger inserts a record in some other table2 then the @@IDENTITY will return the identity value inserted in Table2.

SCOPE_IDENTITY() will return the last IDENTITY value produced on a connection and by a statement in the same scope, without based on the table that produced the value. So we can say that this function is some identical to @@IDENTITY with one exception. like @@IDENTITY will return the last identity value created in the current session, but it will also limit it to your current scope as well . So that means it will return identity value inserted in Table1.

Use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.
IDENT_CURRENT will reutrn returns the last IDENTITY value produced in a table, Without based on the connection that created the value, and Without based on the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session., So it will retrieve the last generated table identity value.

Webservice WSDL link for westher

how to validate file extension and filesizea and filename in javascript

<html>
<head>
<script>
function getSize()
{
    //var myFSO = new ActiveXObject("Scripting.FileSystemObject");
    var filepath = document.upload.file.value;
   
    alert(filepath);
   
    //var thefile = myFSO.getFile(filepath);
//    var size = thefile.size;
//    alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>

Inheritance

A C# class may only subclass—inherit from—one other class. Therefore, by inheriting from (subclassing) an abstract class, the derived class has used up its ability to participate in a meaningful type hierarchy.
On the other hand, a class can implement—inherit from—any number of interfaces. And, it can still inherit from (subclass) a base class which makes sense.

Single inheritance

C# supports single inheritance: C# does not support multiple inheritance from multiple classes like C++ does. But, by using abstract classes and interfaces, C# programs can achieve most of the same functionality without the confusion and maintenance problems associated with multiple inheritance.

Value type polymorphism

.NET value types are objects descending from Object; but, they cannot inherit from other types. They can implement interfaces. Thus, primitives—such as Int32— can implement the IComparable interface, for example, making them comparable.

Separation of contract and implementation

Interfaces separate the syntax rather than the semantic contract from the implementation. Classes can be designed to decouple the semantic contract from the implementation. For example, abstract classes can be separated in a different assembly than their concrete implementations.

Versioning

An abstract class can contain an interface plus implementations. This simplifies versioning. An abstract class can be extended by adding new nonabstract methods with default implementations. Also, a convenience method is easily added to an abstract class.
An interface cannot be modified without breaking its contract with the classes which implement it. Once an interface has been shipped, its member set is permanently fixed. An API based on interfaces can only be extended by adding new interfaces.

Design flexibility

Interfaces offer more design flexibility; precisely because, they can be implemented by any class regardless of its type hierarchy.

Visual C# Best Practices

  • Use abstract classes and interfaces in combination to optimize your design trade-offs.

Use an abstract class

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)
  • Use an abstract class to define a common base class for a family of types.
  • Use an abstract class to provide default behavior.
  • Subclass only a base class in a hierarchy to which the class logically belongs.

Use an interface

  • When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
  • Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
  • Use an interface to design a polymorphic hierarchy for value types.
  • Use an interface when an immutable contract is really intended.
  • A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

Summary

The following table compares the features of abstract classes and interfaces.
Abstract class Interface
Derived classes exhaust their single base class inheritance option. Classes can implement multiple interfaces without using up their base class option. But, there are no default implementations.
Cannot be instantiated except as part of subclasses. Only derived classes can call an abstract class constructor. Cannot be instantiated.
Defines abstract member signatures which derived classes must implement. Otherwise, the derived class itself will be abstract. Defines abstract member signatures—all of which—implementing classes must implement. Otherwise, a compiler error results.
New non-abstract members may be added that derived classes will inherit without breaking version compatibility. Extending an interface with new members breaks version compatibility.
Optionally, provide default (virtual) member implementation. All members are virtual and cannot provide implementations.
Can include data fields. Cannot include data fields. However, abstract properties may be declared.

Radio button validation in javascript

HTML
                     <input type="radio" name="paymenttype" id="paymenttype"  value="Payment through Gayeway"/>Payment By Card
                      <input type="radio" name="paymenttype" id="paymenttype"  value="Payment through Check" />Payment By Check

Script

 if (!checkRadio())
 {
 alert('You have to select payment type');
 return false;
 }


    function checkRadio () {
 var radios = document["frmUser"].elements["paymenttype"];
 for (var i=0; i <radios.length; i++) {
  if (radios[i].checked) {
  document.getElementById("hdn").value=radios[i].value;
//alert(document.getElementById("hdn").value)
   return true;
  }
 }
 return false;
}

Submit in jquery

<html>
<head>
  <style>

  p { margin:0; color:blue; }
  div,p { margin-left:10px; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Type 'correct' to validate.</p>
  <form action="javascript:alert('success!');">
    <div>
      <input type="text" />

      <input type="submit" />
    </div>
  </form>
  <span></span>
<script>

    $("form").submit(function() {
      if ($("input:first").val() == "correct") {//first input tag,
  //if ($("input:second").val() == "correct") {second input tag,
        $("span").text("Validated...").show();//for all span
        return true;
      }
      $("span").text("Not valid!").show().fadeOut(1000);
      return false;
    });
</script>

</body>
</html>



<html>
<head>
  <style>

  p { margin:0; color:blue; }
  div,p { margin-left:10px; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Type 'correct' to validate.</p>
 <form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>
  <span></span>
<script>

   $('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});
$('#other').click(function() {
  $('#target').submit();
});
</script>

</body>
</html>

Ready() event in jquery

.ready( handler ) Returns: jQuery

Description: Specify a function to execute when the DOM is fully loaded.
  • version added: 1.0.ready( handler )

    handlerA function to execute after the DOM is ready.
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.
All three of the following syntaxes are equivalent:
  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
  // Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
 // Handler for .ready() called.
});
If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Aliasing the jQuery Namespace

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:
jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Example:

Display a message when the DOM is loaded.

<!DOCTYPE html>
<html>
<head>
  <style>p { color:red; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function () {
  $("p").text("The DOM is now loaded and can be manipulated.");
});
  </script>
</head>
<body>
  <p>Not loaded yet.</p>
</body>
</html>

Load in jQuery

  • .load( handler(eventObject) )

    handler(eventObject)A function to execute when the event is triggered.
  • version added: 1.4.3.load( [eventData], handler(eventObject) )

    eventDataA map of data that will be passed to the event handler.
    handler(eventObject)A function to execute each time the event is triggered.
This method is a shortcut for .bind('load', handler).
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
For example, consider a page with a simple image:
<img src="book.png" alt="Book" id="book" />
The event handler can be bound to the image:
$('#book').load(function() {
  // Handler for .load() called.
});
As soon as the image has been loaded, the handler is called.
In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.
The Ajax module also has a method named .load(). Which one is fired depends on the set of arguments passed.
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache
Note: The .live() and .delegate() methods cannot be used to detect the load event of an iframe. The load event does not correctly bubble up the parent document and the event.target isn't set by Firefox, IE9 or Chrome, which is required to do event delegation.

Examples:

Example: Run a function when the page is fully loaded including graphics.

$(window).load(function () {
  // run code
});

Example: Add the class bigImg to all images with height greater then 100 upon each image load.

$('img.userIcon').load(function(){
  if($(this).height() > 100) {
    $(this).addClass('bigImg');
  }
});

Value in JQuery

http://api.jquery.com/val/

.val()

Contents:

.val() Returns: String, Number, Array

Description: Get the current value of the first element in the set of matched elements.
  • version added: 1.0.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option.
For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:
$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons
Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:
$.valHooks.textarea = {
    get: function( elem ) {
        return elem.value.replace( /\r?\n/g, "\r\n" );
    }
};

Examples:

Example: Get the single value from a single select and an array of values from a multiple select and display their values.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p></p>

  <select id="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>
    <option selected="selected">Multiple3</option>
  </select>
<script>
    function displayVals() {
      var singleValues = $("#single").val();// return value for the control which id id single
      var multipleValues = $("#multiple").val() || [];// return value for the control which id id multiple as its mor so array will return
      $("p").html("<b>Single:</b> " + 
                  singleValues +
                  " <b>Multiple:</b> " + 
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);// For All Select change event
//$("#multiple").change(displayVals); // For ID
    displayVals(); //Automatically called
</script>
</body>
</html>

Demo:

Example: Find the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <style>

  p { color:blue; margin:8px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <input type="text" value="some text"/>
  <p></p>
<script>
    $("input").keyup(function () {
      var value = $(this).val();
      $("p").text(value);
    }).keyup();
</script>
</body>
</html>
 
Same as 
 
<html>
<head>
  <style>

  p { color:blue; margin:8px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <input type="text" id="text" value="some text"/>
  <p></p>
<script>
    
 function f11() {
      var value = $("#text").val();
      $("p").text(value);
    }
$("input").keyup(f11);
f11()
</script>

</body>
</html> 

Demo:

.val( value ) Returns: jQuery

Description: Set the value of each element in the set of matched elements.
  • version added: 1.0.val( value )

    valueA string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
  • version added: 1.4.val( function(index, value) )

    function(index, value)A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
This method is typically used to set the values of form fields.
Passing an array of element values allows matching <input type="checkbox">, <input type="radio"> and <option>s inside of n <select multiple="multiple"> to be selected. In the case of <input type="radio">s that are part of a radio group and <select multiple="multiple"> the other elements will be deselected.
The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:
$('input:text.items').val(function( index, value ) {
  return value + ' ' + this.className;
});
This example appends the string " items" to the text inputs' values.

Examples:

Example: Set the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <style>
  button { margin:4px; cursor:pointer; }
  input { margin:4px; color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>
    <button>Feed</button>
    <button>the</button>
    <button>Input</button>
  </div>
  <input type="text" value="click a button" />
<script>
    $("button").click(function () {
      var text = $(this).text();
      $("input").val(text);
    });
</script>
</body>
</html>

Demo:

Example: Use the function argument to modify the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <p>Type something and then click or tab out of the input.</p>
  <input type="text" value="type something" />
<script>
  $('input').bind('blur', function() {
    $(this).val(function( i, val ) {
      return val.toUpperCase();
    });
  });
  </script>
</body>
</html>

Demo:

Example: Set a single select, a multiple select, checkboxes and a radio button .

<!DOCTYPE html>
<html>
<head>
  <style>
  body { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>
    <option selected="selected">Multiple3</option>
  </select><br/>
  <input type="checkbox" name="checkboxname" value="check1"/> check1
  <input type="checkbox" name="checkboxname" value="check2"/> check2
  <input type="radio"  name="r" value="radio1"/> radio1
  <input type="radio"  name="r" value="radio2"/> radio2<script>
    
    $("#single").val("Single2");//From begining Single2 wiil be selected
    $("#multiple").val(["Multiple2", "Multiple3"]); //From begining Multiple2,Multiple3 wiil be selected
    $("input").val(["check1","check2", "radio1" ]);//From begining check1,check2 and radio1 wiil be selected
</script>
</body>
</html>

Demo:

JQuery assign value to a hdn field

ALL<P>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("p").click(function(){       //$("p") is for all <p> ; $("#p") is id of a control
   $("#hdn").val("Pradeepta");//$("#control id").val(value);
alert($("#hdn").val())              //.click is for click event
  });
});
</script>
</head>
<body>
<input type="hidden" name="hdn"  id="hdn"/>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

ID OF < P >
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#p1").click(function(){
   $("#hdn").val("Pradeepta");
alert($("#hdn").val())
  });
});
</script>
</head>
<body>
<input type="hidden" name="hdn"  id="hdn"/>
<p>If you click on me, I will disappear.</p>
<p id="p1">Click me away!</p>
<p>Click me too!</p>
</body>
</html>

What is Serialization? What is serializable attribute used for?

Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter

The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.

SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.

You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.

Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()
Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…
Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( "  " & strItem )
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.

XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.

Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory. 


 Summary: Why would you want to use serialization? The two most important reasons are to persist the state of an object to a storage medium so an exact copy can be recreated at a later stage, and to send the object by value from one application domain to another. For example, serialization is used to save session state in ASP.NET and to copy objects to the clipboard in Windows Forms. It is also used by remoting to pass objects by value from one application domain to another. This article provides an overview of the serialization used in the Microsoft .NET Framework. (9 printed pages)

Introduction
Persistent Storage
Marshal By Value
Basic Serialization
Selective Serialization
Custom Serialization
Steps in the Serialization Process
Versioning
Serialization Guidelines

Introduction

Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
When implementing a serialization mechanism in an object-oriented environment, you have to make a number of tradeoffs between ease of use and flexibility. The process can be automated to a large extent, provided you are given sufficient control over the process. For example, situations may arise where simple binary serialization is not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized. The following sections examine the robust serialization mechanism provided with the .NET Framework and highlight a number of important features that allow you to customize the process to meet your needs.

Persistent Storage

It is often necessary to store the value of fields of an object to disk and then retrieve this data at a later stage. Although this is easy to achieve without relying on serialization, this approach is often cumbersome and error prone, and becomes progressively more complex when you need to track a hierarchy of objects. Imagine writing a large business application containing many thousands of objects and having to write code to save and restore the fields and properties to and from disk for each object. Serialization provides a convenient mechanism for achieving this objective with minimal effort.
The Common Language Runtime (CLR) manages how objects are laid out in memory and the .NET Framework provides an automated serialization mechanism by using reflection. When an object is serialized, the name of the class, the assembly, and all the data members of the class instance are written to storage. Objects often store references to other instances in member variables. When the class is serialized, the serialization engine keeps track of all referenced objects already serialized to ensure that the same object is not serialized more than once. The serialization architecture provided with the .NET Framework correctly handles object graphs and circular references automatically. The only requirement placed on object graphs is that all objects referenced by the object that is being serialized must also be marked as Serializable (see Basic Serialization). If this is not done, an exception will be thrown when the serializer attempts to serialize the unmarked object.
When the serialized class is deserialized, the class is recreated and the values of all the data members are automatically restored.

Marshal By Value

Objects are only valid in the application domain where they are created. Any attempt to pass the object as a parameter or return it as a result will fail unless the object derives from MarshalByRefObject or is marked as Serializable. If the object is marked as Serializable, the object will automatically be serialized, transported from the one application domain to the other, and then deserialized to produce an exact copy of the object in the second application domain. This process is typically referred to as marshal by value.
When an object derives from MarshalByRefObject, an object reference will be passed from one application domain to another, rather than the object itself. You can also mark an object that derives from MarshalByRefObject as Serializable. When this object is used with remoting, the formatter responsible for serialization, which has been preconfigured with a SurrogateSelector takes control of the serialization process and replaces all objects derived from MarshalByRefObject with a proxy. Without the SurrogateSelector in place, the serialization architecture follows the standard serialization rules (see Steps in the Serialization Process) below.

Basic Serialization

The easiest way to make a class serializable is to mark it with the Serializable attribute as follows:
[Serializable]
public class MyObject {
  public int n1 = 0;
  public int n2 = 0;
  public String str = null;
}
The code snippet below shows how an instance of this class can be serialized to a file:
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", 
                         FileMode.Create, 
                         FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
This example uses a binary formatter to do the serialization. All you need to do is create an instance of the stream and the formatter you intend to use, and then call the Serialize method on the formatter. The stream and the object instance to serialize are provided as parameters to this call. Although this is not explicitly demonstrated in this example, all member variables of a class will be serialized, even variables marked as private. In this aspect, binary serialization differs from the XML Serializer, which only serializes public fields.
Restoring the object back to its former state is just as easy. First, create a formatter and a stream for reading, and then instruct the formatter to deserialize the object. The code snippet below shows how this is done.
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", 
                          FileMode.Open, 
                          FileAccess.Read, 
                          FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(fromStream);
stream.Close();

// Here's the proof
Console.WriteLine("n1: {0}", obj.n1);
Console.WriteLine("n2: {0}", obj.n2);
Console.WriteLine("str: {0}", obj.str);
The BinaryFormatter used above is very efficient and produces a very compact byte stream. All objects serialized with this formatter can also be deserialized with it, which makes it an ideal tool for serializing objects that will be deserialized on the .NET platform. It is important to note that constructors are not called when an object is deserialized. However, this violates some of the usual contracts the run time makes with the object writer, and developers should ensure they understand the ramifications when marking an object as serializable.
If portability is a requirement, use the SoapFormatter instead. Simply replace the formatter in the code above with SoapFormatter, and call Serialize and Deserialize as before. This formatter produces the following output for the example used above.
<SOAP-ENV:Envelope
  xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:SOAP- ENC=http://schemas.xmlsoap.org/soap/encoding/
  xmlns:SOAP- ENV=http://schemas.xmlsoap.org/soap/envelope/
  SOAP-ENV:encodingStyle=
  "http://schemas.microsoft.com/soap/encoding/clr/1.0
  http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:a1="http://schemas.microsoft.com/clr/assem/ToFile">

  <SOAP-ENV:Body>
    <a1:MyObject id="ref-1">
      <n1>1</n1>
      <n2>24</n2>
      <str id="ref-3">Some String</str>
    </a1:MyObject>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
It is important to note that the Serializable attribute cannot be inherited. If we derive a new class from MyObject, the new class must be marked with the attribute as well, or it cannot be serialized. For example, when you attempt to serialize an instance of the class below, you will get a SerializationException informing you that the MyStuff type is not marked as serializable.
public class MyStuff : MyObject 
{
  public int n3;
}
Using the serialization attribute is convenient, but it has limitations as demonstrated above. Refer to the guidelines (see Serialization Guidelines below) regarding when to mark a class for serialization, since serialization cannot be added to a class after it has been compiled.

Selective Serialization

A class often contains fields that should not be serialized. For example, assume a class stores a thread ID in a member variable. When the class is deserialized, the thread stored for the ID when the class was serialized might not be running anymore, so serializing this value does not make sense. You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows:
[Serializable]
public class MyObject 
{
  public int n1;
  [NonSerialized] public int n2;
  public String str;
}

Custom Serialization

You can customize the serialization process by implementing the ISerializable interface on an object. This is particularly useful in cases where the value of a member variable is invalid after deserialization, but you need to provide the variable with a value in order to reconstruct the full state of the object. Implementing ISerializable involves implementing the GetObjectData method and a special constructor that will be used when the object is deserialized. The sample code below shows how to implement ISerializable on the MyObject class from a previous section.
[Serializable]
public class MyObject : ISerializable 
{
  public int n1;
  public int n2;
  public String str;

  public MyObject()
  {
  }

  protected MyObject(SerializationInfo info, StreamingContext context)
  {
    n1 = info.GetInt32("i");
    n2 = info.GetInt32("j");
    str = info.GetString("k");
  }

  public virtual void GetObjectData(SerializationInfo info, 
StreamingContext context)
  {
    info.AddValue("i", n1);
    info.AddValue("j", n2);
    info.AddValue("k", str);
  }
}
When GetObjectData is called during serialization, you are responsible for populating the SerializationInfo object provided with the method call. Simply add the variables to be serialized as name/value pairs. Any text can be used as the name. You have the freedom to decide which member variables are added to the SerializationInfo, provided that sufficient data is serialized to restore the object during deserialization. Derived classes should call the GetObjectData method on the base object if the latter implements ISerializable.
It is important to stress that you need to implement both GetObjectData as well as the special constructor when ISerializable is added to a class. The compiler will warn you if GetObjectData is missing, but since it is impossible to enforce the implementation of a constructor, no warnings will be given if the constructor is absent and an exception will be thrown when an attempt is made to deserialize a class without the constructor. The current design was favored above a SetObjectData method to get around potential security and versioning problems. For example, a SetObjectData method must be public if it is defined as part of an interface, thus users have to write code to defend against having the SetObjectData method called multiple times. One can imagine the headaches that can potentially be caused by a malicious application that calls the SetObjectData method on an object that was in the process of executing some operation.
During deserialization, the SerializationInfo is passed to the class using the constructor provided for this purpose. Any visibility constraints placed on the constructor are ignored when the object is deserialized, so you can mark the class as public, protected, internal, or private. It is a good idea to make the constructor protected unless the class is sealed, in which case the constructor should be marked private. To restore the state of the object, simply retrieve the values of the variables from the SerializationInfo using the names used during serialization. If the base class implements ISerializable, the base constructor should be called to allow the base object to restore its variables.
When you derive a new class from one that implements ISerializable, the derived class must implement both the constructor as well as the GetObjectData method if it has any variables that need to be serialized. The code snippet below shows how this is done using the MyObject class shown previously.
[Serializable]
public class ObjectTwo : MyObject
{
  public int num;

  public ObjectTwo() : base()
  {
  }

  protected ObjectTwo(SerializationInfo si, StreamingContext context) : 
base(si,context)
  {
    num = si.GetInt32("num");
  }

  public override void GetObjectData(SerializationInfo si, 
StreamingContext context)
  {
    base.GetObjectData(si,context);
    si.AddValue("num", num);
  }
}
Do not forget to call the base class in the deserialization constructor; if this is not done, the constructor on the base class will never be called and the object will not be fully constructed after deserialization.
Objects are reconstructed from the inside out, and calling methods during deserialization can have undesirable side effects, since the methods called might refer to object references that have not been deserialized by the time the call is made. If the class being deserialized implements the IDeserializationCallback, the OnSerialization method will automatically be called when the entire object graph has been deserialized. At this point, all the child objects referenced have been fully restored. A hash table is a typical example of a class that is difficult to deserialize without using the event listener described above. It is easy to retrieve the key/value pairs during deserialization, but adding these objects back to the hash table can cause problems since there is no guarantee that classes that derived from the hash table have been deserialized. Calling methods on a hash table at this stage is therefore not advisable.

Steps in the Serialization Process

When the Serialize method is called on a formatter, object serialization proceeds according to the following rules:
  • A check is made to determine if the formatter has a surrogate selector. If it does, check if the surrogate selector handles objects of the given type. If the selector handles the object type, ISerializable.GetObjectData is called on the surrogate selector.
  • If there is no surrogate selector or if it does not handle the type, a check is made to determine if the object is marked with the Serializable attribute. If it is not, a SerializationException is thrown.
  • If it is marked appropriately, check if the object implements ISerializable. If it does, GetObjectData is called on the object.
  • If it does not implement ISerializable, the default serialization policy is used, serializing all fields not marked as NonSerialized.

Versioning

The .NET Framework provides support for versioning and side-by-side execution, and all classes will work across versions if the interfaces of the classes remain the same. Since serializations deals with member variables and not interfaces, be cautious when adding or removing member variables to classes that will be serialized across versions. This is especially true for classes that do not implement ISerializable. Any change of state of the current version, such as the addition of member variables, changing the types of variables, or changing their names, will mean that existing objects of the same type cannot be successfully deserialized if they were serialized with a previous version.
If the state of an object needs to change between versions, class authors have two choices:
  • Implement ISerializable. This allows you to take precise control of the serialization and deserialization process, allowing future state to be added and interpreted correctly during deserialization.
  • Mark nonessential member variables with the NonSerialized attribute. This option should only be used when you expect minor changes between different versions of a class. For example, when a new variable has been added to a later version of a class, the variable can be marked as NonSerialized to ensure the class remains compatible with previous versions.

Serialization Guidelines

You should consider serialization when designing new classes since a class cannot be made serializable after it has been compiled. Some questions to ask are: Do I have to send this class across application domains? Will this class ever be used with remoting? What will my users do with this class? Maybe they derive a new class from mine that needs to be serialized. When in doubt, mark the class as serializable. It is probably better to mark all classes as serializable unless:
  • They will never cross an application domain. If serialization is not required and the class needs to cross an application domain, derive the class from MarshalByRefObject.
  • The class stores special pointers that are only applicable to the current instance of the class. If a class contains unmanaged memory or file handles, for example, ensure these fields are marked as NonSerialized or don't serialize the class at all.
  • Some of the data members contain sensitive information. In this case, it will probably be advisable to implement ISerializable and serialize only the required fields.