this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Tuesday, May 4, 2010

XML Serialization (Part -2)

In previous post we studied how to perform serialization with binary and soap serialization. In this post we will take a look on XML Serialization.

XML (Extensible Markup Language) is used to represent various data like picture, music, or any other simple type. XML represents data in such a way that, we can access our required information easily. XML data can also be edited easily compared to binary data. One more advantage is that XML data can be transferred in network and application that is not written in .net can also interpret them. Most of the languages has library to interpret XML document.

For XML serialization System.Xml.Serialization needs to include in our solution. Namespace provides classes that support to serialize and deserialized object with XML format.

To serialize primitive data type, its very similar to binary serialization, we use XMLSerializer instance for XML serialization, and use of Serialization and deserialization methods.

But when serialization of custom type class there are some rules and that must be met, otherwise we don’t get expected result.

àClass must be public

àClass must have a constructor with no argument

Both of the above condition should be met when serialization of a class object. Apart from it, class serialization would contain only public fields, no private fields will be shown in XML, you don’t require adding Serialize attribute to class, and it will take default value for it.

There are so many attributes to control serialized output; we customize output as per our requirement.

[XmlRoot ("MyCartItem")]

public class CartItem

{

[XmlAttribute] public Int32 productId;

public decimal price;

public Int32 quantity;

[XmlIgnore] public decimal total;

public ShoppingCartItem()

{

}

}

In above class we have used XMLRoot attribute which will be the root element in XML serialization. XMLAttribute says that ,field should be attribute in XML representation else by default each field is represented as an element. XMLIgnore is similar to NoSerialize in binary serialization; it will not serialize particular field.

Serialized output of above class would be like this..

10.25

2

Please note down here, I have assigned this value to my class object, it can be anything as per your initialization. I have not written code to serialized and deserialized with XML as its same as binary but instead of BinaryFormatter we need to use XMLSerializer class.

Monday, May 3, 2010

Serialization with .net (Part -1)

Serialization is the process to stream an object, after that store it to file, or transfer in network. Now a days there are so many requirements that we need to store object in file or we want to pass our object to some application running on remote location, even some time requirement exists to consume object in another application which is written in languages other than supported by .net framework.

Microsoft .net provided a very nice way to serialize object with just a few lines. For serialization you need to add System.Runtime.Searlization in your project.

Microsoft .net provides many types of serialization process like Binary, Soap, XML or custom serialization. Each type of serialization stands at their own place depends on requirement we can use any of the supported serialization.

We can serialize any of the data of .net primitive type or our class created by user.

Let’s check how it can be done.

Whenever you are clear that my serialization will be occurred between applications written in .net, you can use binary serialization. Binary serialization is very efficient and takes less space compared to other serialization method.

I have scenarios to store my string data to file.

àCreate an instance of stream class, where you will store your string data.

FileStream fs = new FileStream("Serialized.Data", FileMode.Create);

àI have string variable

string myData = “Hi! This is my string data”;

àI want to use Binary serialization, so I need to add System.Runtime.Serialization.Formatters.Binary and create an instance of it.

BinaryFormatter bf = new BinaryFormatter();

àCall Serialize method of BinaryFormatter object.

bf.Serialize(fs,myData);

Now if you open this “Serialized.Data” file you can able to see myData variable’s content in it, there might be some other binary data will be also added ,which is useful when we deserialized object.

At the time of deserialization create instance of BinarayFormmter and call deserialized method.

àdeserialization can be done by..

myData = (String) bf.Deserialize(fs);

Above example shows when we use primitive data type, what about class. We can do same thing with it, but we need to take care of something when creating class.

To serialize class object add [Serializable] attribute to class. So when ever we do serialize of that class all public and private members will be serialized. Some time we have calculation field in our class and so its not required to serialized it.

At that time we can add [NonSerialized] attribute to calculated field of class.

But when we deserialize object we don’t have calculated field value so at that we require it, we can do that calculation when object is deserialized.

Inherits class with IDeserializationCallback and implement OnDeserialization method, this method will be called exactly when our class is deserialzed, we need to call it explicitly.

Some time we face, version problem, say for example we have stored object earlier in file, and later on we added some new fields to our class so it will not find those newly added field when we deserialize object.

In that situation we can use [OptionalField] attribute to our new fields or members added to class once object is serialized. At the time of deserialize we can assign some default value to this newly added field at IDeserializationCallback’s OnDeserialization method.

Same thing can be done with SoapFormatter class instead of BinaryFormatter but it takes more space. When we want to pass object across network and firewall, SoapFormatter is better to use.

Thursday, April 29, 2010

Build custom culture for globalization

In globalization we need to use culture of different regions, there may be possibility when we required, having mix of more than one culture, at that time this custom culture can be very useful.

àCreate an instance of CultureAndRegionInfoBuilder class. This class can be available by adding reference to System.Globalization namespace in our application.

Give your name to custom culture, here we have “en-PC”

CultureAndRegionInfoBuilder cusBuild =

new CultureAndRegionInfoBuilder("en-PC", CultureAndRegionModifiers.None);

à Load data from existing culture, we can use any of the available culture. Here we have used “en-GB” its indicates culture of Great Brittan.

cusBuild.LoadDataFromCultureInfo(new CultureInfo("en-GB"));

à set the new CultureAndRegionInfoBuilder object with region information

cusBuild.LoadDataFromRegionInfo(New RegionInfo("GB"))

à Set culture specific settings.

cib.CultureEnglishName = "Pin Culture"

cib.CultureNativeName = "Pecer Culture"

cib.IsMetric = True

cib.ISOCurrencySymbol = "PC"

cib.RegionEnglishName = "Pig Latin Region"

cib.RegionNativeName = "Pecrer Region Culture"

à ' Register the custom culture

cusBuild.Register()

One thing should be note down when creating custom culture; we should register it when we complete it. To register culture we should have administrator privileges, so it should be done at the setup process.

Once we have successfully registered our culture, we can use it as other culture like

' Display some of the properties of the custom culture.

Dim ci As CultureInfo = New CultureInfo("en-PC")

We can access all properties of it as.

Console.WriteLine("Name: . . . . . . . . . . . . . {0}", ci.Name);

Console.WriteLine("EnglishName:. . . . . . . . . . {0}", ci.EnglishName);

Console.WriteLine("NativeName: . . . . . . . . . . {0}", ci.NativeName);

Wednesday, April 28, 2010

Why should Globalization?

Globalization means we need to build application that work anywhere with respective culture of particular region. It should show region specific date time format, currency symbol, language etc.

Thanks to .net framework, they have provided System.Threading and System.Globalization namespaces to build application that supports Globalization.

As we know different countries have their own language and have their own data format facility. Say for example some countries use comma separator for decimal some use period. If we have hard coded application that certainly it will not work in different culture than we have built.

Culture is always specified in computer when application run on it, it takes culture from computer previously set culture. We can override this culture but it can be only for application. To set culture we can use below syntax.

Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");

Here we have provided culture information by “en-ES”. There are different types of culture are available like specific culture, natural culture. Specific culture gives all of the data format facility for that culture while in case of natural culture we get only language specific transformation.

By providing culture setting we can also change its date,time format or even we can change currency format by accessing various property of date time and data format classes of NumberFormat and NumberDecimalSeparator.

One care should be taken when we use globalization in sorting and comparison, because in different culture they have different priority of letters and symbol priority.

At that time we can have two options either use StringCompariosn.InvarianCulture or use below syntax.

Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture

Tuesday, April 27, 2010

Creating Assembly at runtime with Reflection (Reflection Part-2)

We have discussed in previous post we can create assembly at runtime and we can add code in that assembly at the same time we can access that assembly’s method or members with use of reflection.

.net provides Builder Class to build assembly and its members, module, property and many more.

AssemblyBuilder

ConstructorBuilder

EnumBuilder

EventBuilder

FieldBuilder

LocalBuilder

MethodBuilder

ModuleBuilder

ParameterBuilder

PropertyBuilder

TypeBuilder

To create assembly at runtime we should follow below steps.

àCreate an instance of AssemblyBuilder that defines assembly name and we are also passing another attribute AssemblyBuilderAccess which tell that we want to run this assembly and then save to disk. If we don’t use RunAndSave and use Save then it only Save to disk but we don’t allow to run.

AssemblyBuilder asb = AppDomain.CurrentDomain.DefineDynamicAssembly(

new AssemblyName("myAssembly"), AssemblyBuilderAccess.RunAndSave);

àCreate a ModuleBuilder in created assembly

ModuleBuilder mb = asb.DefineDynamicModule("myMod");

àCreate a TypeBuilder public class in Module we have created

TypeBuilder tb = mb.DefineType("myType", TypeAttributes.Class | TypeAttributes.Public);

àCreate a default constructor to create instance of our dynamically created type.

ConstructorBuilder cb = tb.DefineDefaultConstructor(MethodAttributes.Public);

àCreate a public, static method named Greeting that doesn't accept parameters or return a value, method can be any type as per our need. But it should be added in type we created.

MethodBuilder method = tb.DefineMethod("Greeting", MethodAttributes.Public | MethodAttributes.Static);

àCreate an ILGenerator for the method, which allows us to write code for it. we can write of code in dynamic method in IL code its very error prone when writing code here. Care should be taken to write ILCode

ILGenerator dynCode = method.GetILGenerator();

àAdd a line of code to the method, equivalent to Console.WriteLine, this code is in IL so we have to know IL to write dynamic assembly.

dynCode.EmitWriteLine("Hello, world!")

This is what we have created type at dynamically now if we want to use this dynamically code at runtime with use of reflection we can do as per our previous post.

àCreate an instance of the dynamic type

Type myDynType = tb.CreateType();

àCall the static method we dynamically generated

myDynType.GetMethod("Greeting").Invoke(null, null);

Apart from this we can access dll files or any of the assembly’s information and invoke method of it. Reflection can be very useful when we don’t know what will be come when code is going to execute.

Monday, April 26, 2010

Reflection in .net (Reflection Part-1)

As a .net developer or any time worked with .net we are familiar with word Reflection. We rarely use reflection in our development but it is very powerful feature provided by .net framework.

It gives information of types, methods, properties, code etc at runtime dynamically generated assembly. With use of reflection we can access assembly written in .net or any other platform or even we can generate or create assembly at runtime as per our need.

To use reflection we need to import or add System.Reflection and or System.Reflection.Emit namespace in our application.

Let’s take a look how to use reflection to create type instance at run time.

We want to show string length in console and for that we don’t want to use Length property.

To use any type at dynamically we should follow below steps.

àCreate instance of type

Type t = typeof(StringBuilder);

àCreate constructor of type

ConstructorInfo ci = t.GetConstructor(new Type[] { typeof(string) });

àInvoke constructor

Object sb = ci.Invoke(new Object[] { "Hello, world!" });

àCreate a PropertyInfo instance representing the StringBuilder.Length property.

PropertyInfo lengthProperty = t.GetProperty("Length");

àRetrieve the Length property and cast it to the native type.

int len = (int)lengthProperty.GetValue(sb, null);

Console.WriteLine(len.ToString());

We can use any type as per above example it’s not necessary that it must be provided by .net framework. we can even create instance of type created by ourselves dll files.

If we check assembly’s information in project property we can see assembly’s name, assembly’s version, assembly’s copy write information, assembly’s version and many things that gives information for an assembly we can access all these information with use of Reflection.

First we need to load assembly in our current application domain.

That can be done by methods provided by Assembly class all are static methods.

Assembly.Load :Loads an assembly by name, usually from the Global Assembly

Cache (GAC)

Assembly.LoadFile :Loads an assembly by specifying the filename

Assembly.LoadFrom :Loads an assembly given its filename or path

Following methods allows to load assembly but only for examine we don’t run code of that assembly. That is also code reflection-only context.

Assembly.ReflectionOnlyLoad :Loads an assembly in reflection-only context, usually from the GAC

Assembly.ReflectionOnlyLoadFrom :Loads an assembly in reflection-only context, by specifying the filename

We can access assembly’s information by its attribute first need to iterate through attributes of it.

Like below are some of the assembly’s attribute.

AssemblyCopyrightAttribute

AssemblyCompanyAttribute

AssemblyDescriptionAttribute

To access all members like property, methods ,fields members we can call GetMembers. In that we can pass different BindingFlags enumerator.

Depends of BindingFlags we get array of members in a given assembly. We can also pass more than one BindingFlags enumerator.

Type t = typeof(String);

MemberInfo[] mi = t.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);

Above code will return all the private and static members of String type. There are also other options in BindingFlags enumerator depends on it we get list of members.

In next part we will discuss about how to create assembly at runtime.

Monday, March 29, 2010

Typed V/S Un-Typed

In .Net framework, we many choice to use type safety and also we can use object without specifying its type before it will be used.

Typed means we know type, type can be anything int, string, float or any user defined type object etc.

Un-Typed as name suggest it does not mean absence of type, but uncertainty in types like we don’t have idea which type will come weather its int,float or something else.

In .Net Framework Object is base type of any types. So if we have declared variable as Object and going to assign value then we can assign any values string, int but we don’t know or have control to assign value to Object type variable.

Un-Typed:

Array list, dataset, and many collections are most popular example of un-typed; in array list we can store any value. Also in dataset we have one or many tables; even we don’t have idea which table will be stored in our dataset before we access dataset.

Due to above characteristic, it lacks of type checking, we should be take care when cast to any type.

Typed:

Strongly typed dataset, Generics collection provides a great typed safety.

Strongly Typed Dataset we have dataset designed file, we can drag and drop tables, and we may have relation between them. Whenever we access typed dataset we can access tables and its column by its name we get intelligence menu.

We are sure that we are accessing particular table’s row and its column. We are also sure that value of column should be compatible with database’s type. Otherwise we would get compiler error.

With Generic collection, we can have collection of Dictionary,stringCollection and other collection which can accept only one type of data. Like if we are going to declare Dictionary to store key as integer and value as Person class object then we must follow it. If at the time of coding we do something wrong or use other object compiler will give error.

Summary

As per requirement we should use typed and untyped variable in our application. If we know that we are going to use only numeric datatype or have idea of particular type we should use typed, due to its checking of type safety at compile time, intelligence menu etc.

But if we don’t have any prior information of datatype, we don’t have other choice than un-typed. At the time of Un-Typed, care should be taken when casting to types. We should use try catch block to prevent crash of application.