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

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.