DOT NET ANSWERS

 

Serialization:

            Serialization is the process of saving the state of an object by converting it to a stream of bytes. The object can then be persisted to file, database, or even memory. The reverse process of serialization is known as deserialization.

 

Uses for serialization:
        
Serialization is used in many scenarios, but the main purpose is to save the state of an object in order to have the ability to recreate the same object when required. It is an important to let the user save work and then be able to continue from that point at a later time. This is a common need in various tools and applications. Serialization is also used in creating a clone of an object.
       Another important need for serialization arises when the object is required to travel electronically over wire. In such cases the objects are serialized and deserialized. In fact, serialization is one of the fundamental requirements for techniques such as .NET Remoting.

Types of serialization
        The .NET Framework provides certain built-in mechanisms which can be used to serialize and deserialize objects. This functionality can be found in the System.Runtime.Serialization and the System.Xml.Serialization namespaces of the .NET Framework.
      Serialization in .NET can be classified into four types 
 

 

 This classification arises from the format in which the data in the object is persisted.

 

The XML serialization technique can convert only the public properties and fields of an object into an XML format. The XML serialization is also known as shallow serialization.

The inability of the XMLSerializer to serialize the private fields of an object is overcome by the SOAP and binary serialization techniques. In the binary and SOAP serialization techniques, the state of the entire object is serialized into a stream of bytes. In cases where the object contains a reference to other objects, even those are serialized. This type of serialization is known as deep serialization.

 

The main methods which encapsulate the functionality of serialization are the Serialize and Deserialize methods. The SoapFormatter and the BinaryFormatter are the concrete classes which enable the serialization process within the .NET Framework.

 

    SampleObject objSampleObject = new SampleObject();
    objSampleObject.Value = 100;              
    
    //SOAP Serialization using SoapFormatter
    SoapFormatter formatter = new SoapFormatter();
   Stream objFileStream = new FileStream("c:\\MyFile.xml", FileMode.Create,                 FileAccess.Write, FileShare.None);
     formatter.Serialize(objFileStream, objSampleObject);
    objFileStream.Close(); 
    //De-Serialization
    Stream objNewFileStream = new FileStream("c:\\MyFile.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

// The de-serialize method is used to de-serialize an object or an object containing other objects. //This method has the following signature:

//Object de-serialize( Stream serializationStream ) ;

SampleObject objObject2 = (SampleObject)formatter.Deserialize(objNewFileStream);
    objNewFileStream.Close();
    int Value = objObject2.Value;
    Console.WriteLine(Value);                
          

          An instance of the SoapFormatter object is created and the Serialize method is called and a FileStream is passed to enable serialization. The technique for using a binary formatter would be the same except that instead of the SoapFormatter, an instance of the BinaryFormatter would need to be created.

 

Comparison: Which technique to use?

         The XmlSerializer can be used when you need the data in the object to be stored in an XML Format. However, this serialize has the limitation that it can serialize only the public fields of an object.
        The SoapFormatter is ideal in scenarios where you need interoperability. This is ideal in applications spanning heterogeneous environments.
         The BinaryFormatter generates a very compact stream when an object is serialized as compared to the other two techniques and hence is useful when data needs to travel electronically across the wire. This is appropriate when the applications do not involve heterogeneous environments.

 

Serializable attribute:


          
The developer would need to mark a class as serializable using the appropriate attribute in order for the object of that class to indeed be serializable. In fact, the serialization feature is a design time issue because an object cannot be made serializable at runtime.

         The code snippet below shows the usage of SerializableAttribute:

[Serializable]
public class MyClass



The SerializableAttribute needs to be applied even when the class implements the ISerializable interface. When an attempt is made to serialize an object which is not marked as Serializable, the CLR throws a SerializationException.

 

Selective serialization:


              I
n certain scenarios, it may be beneficial to serialize an object in parts. Certain objects might contain information which is sensitive and for security reasons such information should not be serialized. Also, it might not make sense to serialize certain data like the reference to another object or storing a Thread ID. This data might not be valid when the object is deserialized.
               For such situations, the .NET Framework provides the NonSerialized attribute. This attribute can be used to prevent particular member variables of an object from being serialized.

         

[Serializable]
public class SampleObject
{
  public int intValue = 0;
 
  [NonSerialized()]         
  public string strSecret = "E5522B9D-B088-42a0-A6E0-264B4D2DF174";
  
  public SampleObject()
  {
 CACHING:

        By utilizing the caching functionality built into ASP.NET, you can greatly improve the performance and scalability of your site.

          Caching provides performance enhancements in cases where frequently used items can be accessed from an alternate cached location faster than they can be obtained from the originating location. An example of caching would be where a client browser or proxy server stores a local copy of a frequently accessed Web page. The advantage is that the page can be accessed locally faster than it can be accessed across the Internet each time it is requested.

          The Microsoft.NET framework includes a caching object model that provides two types of caching: data caching and output caching.

          Output cached items take the form of entire pages or just fragments of a page. Output caching improves performance by allowing pages or fragments of a page to not have to be constructed for each client request.
            Items stored in the data cache consist of application objects that are stored in memory so that the application saves time in retrieval of the data from the data source. Each ASP.NET-based application has a private memory cache stored for the lifetime of the application. The cache is cleared each time you restart the application.

 

Caching an ASP.NET page
               
The idea behind caching the contents of an entire page is so that the page can be served up all at once from the cache rather than having to regenerate the page for each request that is made. When a page request is made, the cache engine checks its contents to determine if a cached version of the page already exists. If it does, the cached HTML page is sent in response to the client request. If it doesn't, the page is dynamically rendered, returned to the client, and stored in the cache if necessary.
              
         <%@ OutputCache Duration="60" VaryByParam="none" %>
                Caching the contents of an entire page is simple to do. The @OutputCache page directive instructs the cache engine on what to do with the page. The directive includes a Duration parameter for indicating how long the page should be stored in cache. In addition, there is a VaryByParm parameter that allows you the flexibility to store multiple versions of the page based on the query string or Web form contents posted to the page.

 

              When multiple parameters affect the page output, the VaryByParam can be set to * to allow it to vary the caching across all parameter combinations. This feature isn't ideal for every page, however. The page should have fairly static content before you decide to cache the entire contents of the page; otherwise, you could consume a large amount of system resources for little benefit..

 

Caching an ASP.NET page fragment
           
 Caching an entire page isn't always feasible, especially when part of the page content is highly volatile. In an ideal scenario, the static content would be cached while the rest of the page content would render dynamically when requested. This is precisely what page fragment caching allows you to accomplish in your Web applications.

         The following directive instructs ASP.NET to output cache the user control for 120 seconds, and to vary the caching using the "CategoryID" and "SelectedID" querystring or form post parameters.

<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>

The VaryByParam attribute is extremely powerful and allows user control authors to instruct ASP.NET to cache/store multiple instances of an output cache region on the server.

In addition to supporting the VaryByParam attribute, fragment caching also supports a VaryByControl attribute. Whereas the VaryByParam attribute varies cached results based on name/value pairs sent using POST or GET, the VaryByControl attribute varies the cached fragment by controls within the user control. For example:

<%@ OutputCache Duration="120" VaryByParam="none" VaryByControl="Category" %>

Note that similar to output-cached pages, explict use of VaryByParam is required even if it is not used.

If the user control contained a drop-down select box control named Category, the user control's output would vary based on the selected value within that control.

The fragment caching is implemented through User Controls. The fragments of the page that will be cached are placed in one or more User Controls. The User Controls are then included in different pages as desired. The caching options for the controls are specified by placing an OutputCache directive within each control or programmatically in the code behind using the PartialPageCachingAttribute. The caching parameters are set on the individual controls rather than within the page itself.

 

Caching data


         
While there are parameter inputs for page and page fragment caching, for the most part, the cache engine has the majority of the control and does most of the work. On the other hand, data caching is where the majority of the control is handled programmatically. The Cache class located in the System.Web.Caching namespace is the way in which items are added into and retrieved from the ASP.NET cache.

        The Cache class provides a dictionary type interface, which means you assign a key to the value when it is stored. The key is used to access the value again at a future point in time when it is needed.
         You have the following three options for programmatically putting content into the cache:

Using a name value pair similar to a Dictionary object.
Example: Cache[“keyName”] = “MyValue”;
Example: Cache[“keyName2”] = myObject;

Using the Cache.Add method, which returns an object representing the item added into the cache. If an object with the given key name already exists in the cache, then the Add method will fail.
Example: Cache.Add(“keyName”, “MyValue”);
Example: Cache.Add(“keyName2”, myObject);

Using the Cache.Insert method, which, unlike the Insert method, does not have a return type. In addition, if an item already exists in the cache with the given key name, the Insert method will override it with the new value given.
Example: Cache.Insert(“keyName”, “MyValue”);
Example: Cache.Insert(“keyName2”, myObject);


The Add and Insert methods offer advantages over the straight dictionary interface. These methods allow other options to be set, such as an expiration policy, priority policy, dependencies, and a delegate to notify when the item is removed from cache. These options aren't available using the dictionary interface.

The expiration policy is controlled through the DateTime and TimeSpan data types. This will allow you to set a time to expire the content. The use of DateTime allows you to specify a specific date and time to remove the item from the cache. The TimeSpan allows you to specify a time interval from when the object was last accessed to when it expires from cache.

The priority policy is related to garbage collection. Since the cache is kept in memory, there is a limited amount of memory. When the items in cache exceed the available space, some items will be automatically purged from the cache. The priority policy specified through the CacheItemsPriority enumerated type gives you control over the order in which items will be purged relative to the other items in cache. This way, you have control over which items are of higher importance and will remain cached longer than others.


 A delegate is called when the item is removed from the cache. This allows you to have notification when the object is no longer in cache so that the appropriate action can be taken, such as putting the item back into cache. This is ideal for use with a validation dependency. When the dependency changes, causing the item to be removed, the delegate can put the item back into the cache based upon the changes.

 

The following is a list of the performance counters in version 1.1 of the Microsoft .NET Framework:

 

Cache Total Entries shows the total number of entries.

 

Cache Total Hits shows the number of times something was retrieved from the cache.

 

Cache Total Misses shows the number of times something was attempted to be retrieved from the cache but did not exist.

 

Cache Total Hit Ratio shows a ratio of the number of items found in the cache against the number of accesses.

 

Cache Total Turnover Rate is the number of items added to or removed from the cache per second.

 

ADVANTAGES OF OOP:

           

          1. Modularity

          2. Reusability

          3. Extendibility

 

Stack Vs. Heap:

 

  1. Stack or value types can be allocated much more quickly than heap-allocated types
  2. Values on the stack are instantly and automatically deallocated once thy go out of scope.
  3. Its easy to coy the value of one value variable into another value type variable.