You are on page 1of 27

.

Net Framework concepts


• Serialization
• Reflection
Serialization
• Serializing is the process of converting an object
into a linear sequence of bytes that can be stored
or transferred.
• Deserializing is the process of converting a
previously serialized sequence of bytes into an
object
• Namespace : System.Runtime.Serialization
Serializing Objects
• How to Serialize an object
1. Create a stream object to hold the serialized o/p.
2. Create a BinaryFormatter object.
3. Call the BinaryFormatter.Serialize method to serialize the
object and output the result to stream.

Look the sample Application.

• Behind the Scenes


Windows relies on serialization for many important tasks, including
Web services, remoting, and copying items to the clipboard
Serializing Objects
• How to Deserialize an Object
1. Create a stream object to read the serialized output.
2. Create a BinaryFormatter object.
3. Create a new object to store the deserialized data.
4. Call the BinaryFormatter.Deserialize method to
deserialize the object, and cast it to the correct type.
Serializing Objects
• Behind the Scenes of Deserialization
If an object references another object, the Formatter queries the
ObjectManager to determine whether the referenced object has already
been deserialized (a backward reference), or whether it has not yet
been deserialized (a forward reference).

If it is a backward reference, the Formatter immediately completes


the reference. However, if it is a forward reference, the Formatter
registers a fixup with the ObjectManager.

A fixup is the process of finalizing an object reference after the referenced object
has been deserialized. Once the referenced object is deserialized, ObjectManager
completes the reference
Serializing Objects
• How to Create Classes That Can Be Serialized

You can serialize and deserialize custom classes by adding the Serializable attribute
to the class.This is important to do so that you, or other developers using your class,
can easily store or transfer instances of the class.

• Disable Serialization of Specific Members

Some members of your class, such as temporary or calculated values,might not need
to be stored , So we can use the resources effectively. For these Add NonSerialized
attribute to these members and use the IDeserializationCallback interface, and then
implement IDeserializationCallback.OnDeserialization.
Serializing Objects
• How to Provide Version Compatibility

If you add a member to a class in version 3.1 of your application, it will not be able
to deserialize an object created by version 3.0 of your application.

• To overcome this limitation, you have two choices:

■ Implement custom serialization, that is capable of importing earlier


serialized objects.
■ Apply the OptionalField attribute to newly added members that might cause
version compatibility problems
Serializing Objects
• Best Practices for Version Compatibility:

■ Never remove a serialized field.


■ Never change the name or type of a serialized field.
■ When adding a new serialized field, apply the OptionalFieldAttribute
attribute.
■ When removing a NonSerializedAttribute attribute from a field that
was not serializable in a previous version, apply the
OptionalFieldAttribute attribute
■ For all optional fields, set meaningful defaults using the serialization
callbacks unless 0 or null as defaults are acceptable.
Serializing Objects
• Choosing a Serialization Format
Based on our needs we have to select the Formatter
There is two formatters supported by .Net

 Binary Formatter
Namespace: System.Runtime.Serialization.Formatters.Binary
Most Efficient way to serialize the objects that will be read by
only .Net based Application.

 Soap Formatter
Namespace: System.Runtime.Serialization.Formatters.Soap
Most Reliable way to serialize the objects that can be read by
any non-.Net Framework Application
Serializing Objects
• Serialized data by using Soap Formatter

The following example is a three-member object serialized


with SoapFormatter that has been slightly edited for readability

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<a1:ShoppingCartItem id="ref-1">
<productId>100</productId>
<price>10.25</price>
<quantity>2</quantity>
</a1:ShoppingCartItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Serializing Objects
• Guidelines for Serialization

 When in doubt, mark a class as Serializable. Even if you do not need to serialize it
now, you might need serialization later. Or another developer might need to serialize a
derived class.

 Mark calculated or temporary members as NonSerialized. For example, if you track


the current thread ID in a member variable, the thread ID is likely to not be valid
upon deserialization. Therefore, you should not store it.
XML Serialization
• Why Use XML Serialization?
 Greater interoperability
 More Administrator friendly
 Better Forward Compatibility

• Limitations of XML Serialization


1.Serialize only public data
2.Cannot Serialize object Graphs

• How to Use XML to Serialize an Object


1. Create a stream, TextWriter or XmlWriter object to hold the serialized output.
2. Create a XmlSerializer object by passing it the type of object you plan
to serialize.
3. Call the XmlSerializer.Serialize method to serialize the object and
output the result to the stream.
XML Serialization
• How to Use XML to Deserialize an Object

Fallow the similar steps instead of serialize method


Call the deserialize method.

• How to Create Classes that Can Be Serialized


by Using XML Serialization

 Specify the class as public


 Specify all members that must be serialized as public
 Create a parameter less constructor
Custom Serialization
• Custom serialization is the process of controlling the serialization and
deserialization of a type.

• How to Implement Custom Serialization


 By implementing the ISerializable interface and applying the serializable attribute to the class
 Implementing ISerializable involves implementing the GetObjectData method and a special
Constructor that is used when the object is deserialized.
 The Runtime calls GetObjectData during serialization and the serialization constructors during
deserialization, during these process we have to populate the SerializationInfo object
provided with the method call.
 Add the variables to be serialized as name/value pairs using the AddValue method, which
internally creates the serializationEntry structures to store the information.
Custom Serialization
• Responding to Serialization Events
 Serializing – This Event is raised just before serialization takes place. Apply
OnSerializing attribute to the method that should during this event.

 Serialized – This Event is raised just after serialization takes place. Apply OnSerialized
attribute to the method that should during this event.

 Deserializing - This Event is raised just before deserialization takes place. Apply
OnDeserialized attribute to the method that should during this event

 Deserialized - This Event is raised just after deserialization takes place and after
IDeserializationCallback.OnDeserialization has been called. We should use
IDeserializationCallback.OnDeserialization instead when the formatters other than BinaryFor.
Custom Serialization
• Change Serialization based on Context
Streamingcontext structure provides information about the destination of a serialized object
to class that implements the Iserializable interface. This structure contains two properties .

 Context – A referance to an object that contains any user-defined context information.


 State - A set of bit flags indicating the source or destination of the objects being
serialized/Deserialized. The flags are
o Cross Process – The Source or Destination is a different process on the same m/c.
o Cross M/C – The source or Destination is a different m/c.
o File - The source or Destination is a file, don’t assume same process will deserialize.
o Presistence – The S/D Is a store such as Database , file or other. don’t assume same
process will deserialize.
o Remoting – The S/D is remoting to an unknown location that might be on the same m/c
but might also be in the different m/c.
o CrossAppDomain – The S/D is a different AppDomain.
Understanding Reflection
• Introduction
– The Reflection system is used to inspect the type information as well as to create code on the
fly, It presets code as an object model. From assemblies and modules all the way down to
individual statements.

• Assemblies and Modules


– Assembly is a logical container for different parts of data that CLR needs to execute code.
These parts inlcudes:
 Assembly Metadata
 Type Metadata
 Code (IL Code)
 Resources
– Assembly can be present in multifiles.
– Modules are containers for types within an individual assembly file, In general we will use
multiple modules per assembly only where we need to do things like mix source languages within
a single assembly. Visual studio does not support does not support for multiple modules
Understanding Reflection
• Examining Assemblies
– Assembly class supports a number of static methods to create instances of the class. Some of
the static class are:
GetAssembly, GetEntryAssembly, GetExecutingAssembly, Load, LoadFile, LoadFrom,
ReflectionOnlyLoad, ReflectionOnlyLoadFrom

– Assembly class supports a number instance properties and methods like,


 Properties:
EntryPoint, FullName, GlobalAssembluCache, ReflectionOnly
 Methods:
CreateInstance, GetExportedTypes, GetFile, GetFiles, GetModule, GetModules,
GetName, GetSatelliteAssembly, GetTypes
Assembly Attributes
• Common Attributes
– Assembly attributes can adorn assembly to provide additional information about the assembly,
– Some common attributes
 AssemblyCompanyAttribute
 AssemblyCopyrightAttribute
 AssemblyConfigurationAttribute
 AssemblyCultureAttribute
 AssemblyDelaySignAttribute
 AssemblyDescibtionAttribute
 AssemblyInformationalVersionAttribute
 AssemblyKeyFileAttribute
 AssemblyDefaultAliasAttribute
– Getting Assembly Attributes
 Look the Sample Application
Reflecting Types
• Getting Types
– We can get the type object in number of ways
 From the Assembly Class
 From the Module Class
 From Instances of an object
 Using Typeof keyword in C# or GetType in VB

– After creating type object ,We can look at the methods, properties, events, interfaces and
inheritance tree of a particular type in the system.
– We have various Properties and Methods for Type Class like
 Properties :
Assembly,AssembyQualifiedName, Attributes, BaseType, FullName, IsAbstract,
IsInterface, IsnotPublic, IsClass, IsEnum, IsSealed, IsValueType, IsVisible, Namespace,
IsPublic etc..
 Methods :
GetConstructor, GetConstructors, GetEvent, GetEvents, GetField, GetFields,
GetInterface/s, GetMember/s, GetMethod/s, GetProperty, GetProperties etc..
Reflecting Types
• Enumerating Class Members
– Each part of a type is represented by a class within the
reflection system that ends with the name info.
– A number of methods on the Type class allow you to get each
of the parts of the type. These match the info classes as well.
– Example for retrieving properties all the properties of a class
Foreach(PropertyInfo prop in type.GetProperties)
{
// do the operations
}
Reflecting Types
• Understanding the MethodBody
– The MethodBody is a special sort of container that contains local variables and the actual
Intermediate Language (IL) instructions that are compiled into machine code at runtime.
– The local variable return as an array of LocalVariableInfo objects that contain information
about the type of each variable , finally we can get the array of bytes (actual IL code) that
the CLR uses to compile and run the m/c code.

• Using the BindingsFlags


– BindingFlags Enumeration is used to control how members of a type are retrieved using the
GetMembers methods
– BindingFlags enumeration is a flagged enumeration, i.e. more than one value can be used.
– Some of the BindingFlags Enumerations are:
DeclaredOnly , Default, FlattenHierarchy, IgnoreCase, Instance, NonPublic, Public, Static
Creating Code at Runtime
• Building your own code
– System.Reflection.Emit namespace contains the builder classes that are used to build the
assemblies, types, methods and so on.
– To build a code at runtime, we have to encapsulate it like any other code(Create an
Asembly,then module within the assembly, and types within the module)
– Each of the Builder class derives from its info class counterpart. Ex : AssemblyBuilder derives
from Assembly,MethodBuilder derives from MEthodInfo etc..
– Some sample Builder class:
 AssemblyBuilder
 ConstructorBuilder
• EnumBuilder
• EventBuilder
• FieldBuilder
• LocalBuilder
• MethodBuilder
• ModuleBuilder
• ParameterBuilder
• PropertyBuilder
• TypeBuilder
Creating Code at Runtime
• Creating an Assembly and Module
– Before define any Types , we need to create Assembly and Module, AppDomain is used to
create a dynamic Assembly.
– AppDomain class has DefineDynamicAssembly method that takes Assemblyname and
AssemblyBuilderAccess as parameters
– AssemblyName object is for naming the Assembly
– AssemblyBuilderAccess object specifies what we can do with the new assembly , we can
specify ReflectionOnly,Run,Save,RunAndSave
– After these we have to create the ModuleBuilder so that we can start creating type
information.
– Sample code:
AssemblyName tempName = new AssemblyName();
tempName.Name = "MyTempAssembly"; // for Assembly name

AssemblyBuilder assemBldr=
AppDomain.CurrentDomain.DefineDynamicAssembly(tempName,AssemblyBuilderAccess.RunAndSave);

ModuleBuilder modBldr = assemBldr.DefineDynamicModule("MainMod", "MyTempAssembly.dll");


Creating Code at Runtime
• Defining a Type
– Creating a dynamic Type starts with calling the ModuleBuilder’s DefineType method. These
method takes a type name and TypeAttributes enumeration value, which specifies options for
the type
– Sample
TypeBuilder typeBldr = modBldr.DefineType("MyNewType",TypeAttributes.Public | TypeAttributes.Class);

• Creating Members
– Fallowing is the various methods of the TypeBuilder that help us to define the members of a
type.
Define Constructor , DefineDefaultConstructor, DefineEvent, DefineField, DefineGenericParameters
DefineMethod, DefineProperty
– Sample
ConstructorBuilder ctorBldr =typeBldr.DefineDefaultConstructor(MethodAttributes.Public);
Creating Code at Runtime
– We can now take these constructor and create an ILGenerator object,
ILGenerator class is used to generate local variables and IL code
– Sample
ILGenerator codeGen = ctorBldr.GetILGenerator();
codeGen.Emit(OpCodes.Ret);

– Create a method by specifying its return type and parameter types like
MethodBuilder methBldr = typeBldr.DefineMethod("Add",MethodAttributes.Public,null,new
Type[] { typeof(string) });
– Define a static method by adding MethodAttributes.Static to the attributes like
MethodBuilder methBldr = typeBldr.DefineMethod("Add", MethodAttributes.Public |
MethodAttributes.Static,null,new Type[] { typeof(string) });
– Define a private field called _count like
FieldBuilder fieldBldr = typeBldr.DefineField(“_count”, typeof(int),
FieldAttrubutes.Private);
Creating Code at Runtime
– Define a property similar to how we define a method like
PropertyBuilder propBldr =
typeBldr.DefineProperty("Count",PropertyAttributes.None,typeof(int),Type.EmptyTypes);
– Method to perform set and get operation on property
MethodAttributes getAttributes =
MethodAttributes.Public |MethodAttributes.SpecialName |MethodAttributes.HideBySig;

MethodBuilder propGetBldr =
typeBldr.DefineMethod("get_Count",getAttributes,typeof(int),Type.EmptyTypes);

propBldr.SetGetMethod(propGetBldr);

– Persisting to Disk
assemBldr.Save("MyTempAssembly.dll");

You might also like