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, September 7, 2010

Difference between build and rebuild

In vs we find two options build and rebuild for our solution and very rarely we give attention what do we require.

There is very much difference between both of them, if you have noticed it, build takes less time compared to rebuild.

When we build application it complies files which has been changed it does not compile all files in project, while in case of rebuild it compiles all files weather it has been changed or not. Mainly rebuild should be done when so many files are changed and also it might possible some files are changed outside of IDE.

Hope this information will help to speed up your application when you choose rebuild instead of build.

Tuesday, August 10, 2010

Hide Tab Pages from Tab Control in Win forms

Recently I come to know one requirement to hide tab pages on my tab control of windows form depends on some condition.

I thought there could be some properties like Visible as we have in other controls. But surprisingly there is no such properties exist.

At the end I have only one solution to remove my tabpage from tab control. Let’s go through some code.

I have following tabControls.

myTabControl is my Tab Controls and I have following sub tabs(tab Pages) in it.

tabPage1

tabPage2

tabPage3

At index of 0, 1 and 2 respectively.

To hide my tabPage1 on my UI I have following options.

myTabControl.TabPaegs.Remove(0)

or

myTabControl.TabPages.Remove(tabPage1)

I hope this could be helpful when we have some condition for showing tabs.

Tuesday, July 20, 2010

Call customize Main method in Vb.net

If you have tried to find main method in vb.net, you would not able to find it because vb.net automatically generates that method at runtime. We don’t require writing it. Developer who have worked with C# may find this problem most.

You can write your own main method that can be used at runtime. You can write your main method in a class or a module like below.

But you need be aware of one thing on your project properties

Application->uncheck Enable application framework. In this case, your main method will be invoked instead of automatic generated one.

To Fix Label’s and other controls text are wrapping though it looks Okay in Designer

Recently I have faced a very strange problem in my project, suddenly in some forms text of label wrapped when I run application.

I have not changed anything in my designer or code, though it was creating problem at runtime. I have compared my forms with older version, I also went through each of possible design property of forms but I didn’t find anything.

I had no idea what to do. Then I came to know that my project is in Vb.net and recently I have added my custom main method, if you have been using vb.net you would be aware there is no main method, framework create it runtime. But if you want to do something at startup you need to write main method in vb.net application.

So I got what the problem it was.

By default when runtime create main method it uses following setting for text render but if you are using your own main method at that time you need to add this line to your main method else it can create problem what I have faced.

Application.SetCompatibleTextRenderingDefault(False)

Saturday, July 17, 2010

Bind Enum to windows dropdown box.

Sometime our dropdown lookup value are fixed and we don’t have any database table. In such situation we mostly make enum of our look up value.

But most of the time we are used to bind datasource of tables or list to combbox. So we might be wonder how to bind our enum to combobox.

Here is the simple way to bind combobox.

Say for example you have RoleTypes Enum.

public enum RoleTypes

{

Owner = 1,

Manager = 2,

AssitManager = 3,

Employee = 4

}

Now, to bind this enum to our combo box.

this.cmbUserRole.DataSource = Enum.GetValues(typeof(RoleTypes));

Set value to combobox.

this.cmbUserRole.SelectedItem = (RoleTypes)1;

To get value from combobox.

Convert.ToInt32((RoleTypes) this.cmbUserRole.SelectedItem);

Monday, July 12, 2010

Change Local Working Folder Path in TFS…

Hi, all

Before a few days ago, I was using TFS as our version control system. When I tried to get latest for first time, It asked me for local path where It would be copied from server.

Later on, I needed to change my local path to somewhere else and when I was looking in TFS window to change my local path, I was wondered there were no such options which leads me to change my local working path.

I tried to find in web and I got solution.

In VsàFile menuàSource ControlàWork Space this will leads you a dialog box which shows all workspace on your computer.

You can change any of the lists by editing it.

I hope this will be helpful.

Thursday, July 1, 2010

Declare Guid as Constant.

If you have tried to declare Guid constant with keyword, const you definitely come to error that Guid can’t be declared as constant.

We can only use Const keyword for the value type not for the Object type. Here Guid is object type. You can get to know your datatype is value type or object type by the color of it.

Like value type always shows in blue text(link) while reference type shows in skyblue.

We can use readonly keyword for object type.

We can declare constant of guid as

readonly Guid myId = Guid.NewGuid();

After all our goal is that nobody can change value of our variable and that can be achieved by above.

Wednesday, May 26, 2010

Graphics with .net (Part -3)

Till now we got idea of how to create image and edit existing image. Now we are moving to add text data to our existing image or creating image where text is to be inserted as copyright logo or company’s initial.

To add text to any image, following things are required.

Object of Graphics

Object of Font

If require Object of Brush

Call Graphics.DrawString method and pass font and brush object.

Yes its very simple to add text to our image. Now let’s check out how to create Font object and how to write in image

Create object of Font
Font f = new Font(“Arial”,10,FontStyle.Bold);

Apart from above constructor Font class has more than 12 constructor, we can create FontFamily object and pass it to Font Constructor.

FontFamily ffm = new FontFamily(“Arial”);
Font f = new Font(ffm,10);

If we need to read type of font, we can do with help of FontConverter class. But their errors prone, as we don’t get any error at compile time. We don’t come to know any error till it throws Runtime exception.

FontConverter converter = new FontConverter();
Font f = (Font)converter.ConvertFromString("Arial, 12pt");

Write text To Image
Once font is created, we need to create object of brush to fill text with that color, or we can use Brushes if we don’t wish to create object of brush.

Graphics g = this.CreateGraphics();
Font f = new Font("Arial", 40, FontStyle.Bold);
g.DrawString("My Test String!", f, Brushes.Blue, 10, 10);

Above code will draw “My Test String!” in form with Blue color and bold style with Arial font family.

With help of StringFormat we can format string like its alignment, FormatFlags, LineAlignment, Traimming etc.

Alternatively, to add text to image saved in disk, load it by using any of the bitmap or image class then follow step to draw string on it.

After that call save method of image or bitmap class, that will store new modified image in disk.

Tuesday, May 25, 2010

Graphics with .net (Part -2)

As we discussed in previous post, we required to modify existing image file or have to create new image, chart, edit image and back save to file.

Image and Bitmap class provides ability to modify existing image file or create new image file.

Image is an abstract class, but we can have instance of it by Image.FromFile or Image.FromStream methods. FromFile accept any image file, FromStream accepts stream of Image file. We can use whatsoever we have at hand when we are going to play with Image.

Bitmap class is inherited by Image, For still image we can use Bitmap class, For animated image we can use System.Drawing.Imaging.MetaFile. Bitmap class is widely used for image editing and creation compared to MetaFile.

Display Image in background.
To display image in the back ground of form or any control we have one or more techniques, we can choose any of them.

Take a picturebox control on the form, or create instance of picture box and set BackGroundImage property.

Image backImage = Image.FromFile(“@myImage.jpg”);
myPictureBox.BackGroundImage = backImage;

Here we have placed picturebox control and set its name myPictureBox. myImage.jpg is file available in our current directory else we can specify whole path of my image file.

In another method, we can set background image using Graphics.DrawImage method.

Bitmap backImage = new Bitmap(“@myImage.jpg”);
Graphics g = this.CreateGraphics();
g.DrawImage(backImage,1,1,this.Width,this.Height);

DrawImage methods has 30 around overloaded method, we can use any of them.

Create and Save Image

To create or edit any image first create object of Bitmap class, edit it using Graphics then with Bitmap.Save method, save it back to disk.

Bitmap bm = new Bitmap(600, 600);
Graphics g = Graphics.FromImage(bm);

Brush b = new LinearGradientBrush(new Point(1, 1), new Point(600, 600), Color.White, Color.Blue);

Point[] points = new Point[] {new Point(10, 10), new Point(77, 500), new Point(590, 100), new Point(250, 590), new Point(300, 410)};
g.FillPolygon(b, points);
bm.Save("bm.jpg", ImageFormat.Jpeg);

In above code we have created a polygon and filled it with Blue-while Gradient Brush. Once it done, we save it to disk by bm.jpg to our current directory.

To edit an image, just use another over load of Bitmap constructor that takes file as parameter.

Display Icon
Icon are transparent bitmap image with specific size and used to convey status to windows system. .Net have provided built in Icons with 40-40 size for Questions, Exclamation, Information etc.

To add Icon to Form or control just call Graphics.DrawIcon method, it will do rest for us.

Graphics g = this.CreateGraphics();
g.DrawIcon(SystemIcons.Information, 40, 40);

Above code will draw 40*40 Information Icon on our form.

Monday, May 24, 2010

Graphics with .net (Part -1)

As a developer, we passed through requirement when we want some customize user interface. We want to draw various shapes, various charts, various diagram to output.

Thanks to System.Drawing namespace, we can play with output design. Graphics includes drawing various shapes circle, rectangle, triangle, ellipse etc, also fill shapes with different colors, modify image as per need. Font can be changed, various charts can be constructed.

System.Drawing includes classes Bitmap, Brush, Brushes, ColorCoverter, ColorTranslator, Font, FontConverter, Graphics, Icon, Image, Pen, Pens, Region, SolidBrush, StringFormat, SystemBrushes, SystemColors and many other classes which can be used at various task of graphics drawing.

Apart from classes System.Drawing namespace have structures CharacterChange, Color, Point, PointF, Rectangle, RectangleF, Size, SizeF. Here F in structure name specifies floating point value support.

Location of control: with help of Point we can set location of control

btnOkay.Location = new Point(50,50) will set btnOkay at (50,50) point.

Set Color, with Color structure
btnOkay.ForeColor = Color.Red;
bnkOkay.BackColor = Color.Blue;

We can specify color from another method FromArgb and passing value of RGB.
btnOkay.ForeColor = Color.FromArgb(10,200,200);
bnkOkay.BackColor = Color. FromArgb(5,20,50);

Draw on surface of form or control.

To draw shapes first we need to create object of Graphics, create object of pen, and now call various method of Graphics to draw shape with pen created earlier.

Graphics g = this.CreateGraphics();

Pen p = new Pen(Color.Blue, 5);

g.DrawLine(p,10,10,100,100);

Above code will draw a blue line with 5 pixel thick from point (10,10) to (100,100)

Pen’s style can be set with DashStyle enumeration.

p.DashStyle = DashStyle.Dot;

p.DashStyle = DashStyle.Dash;

p.DashStyle = DashStyle.DashDot;

p.DashStyle = DashStyle.Solid;

By default, pen draw with solid style. Pen.DashOffset and Pen.DashPattern used to customize dash pattern.

To control endcaps, create arrows or modify pen start cap and end cap, LineCap enumerations is helpful.

p.StartCap = LineCap.ArrowAnchor;
p.EndCap = LineCap.DiamondAnchor;

p.StartCap = LineCap.Flat;
p.EndCap = LineCap.Round;

Methods of Graphics which start with Draw needs to fill it with different brushes, Graphics also support fill methods, which does not create shape but also fill shape.

To fill shape, Brush is used. Brush class is abstract class so any of their child class’s instances can be initiated.

System.Drawing.Drawing2D.HatchBrush: A rectangular brush with a hatchstyle, a foreground color, and a background color

System.Drawing.Drawing2D.LinearGradientBrush: Encapsulates a brush with a lin-
ear gradient that provides a visually appealing, professional-looking fill

System.Drawing.Drawing2D.PathGradientBrush: Provides similar functionality to
LinearGradientBrush; however, you can define a complex fill pattern that fades
between multiple points

System.Drawing.SolidBrush: A brush of a single color

System.Drawing.TextureBrush: A brush made from an image that can be tiled across a shape, like a wallpaper design

Monday, May 17, 2010

Configuration in .net

When ever .net application runs in any computer, it requires storing some user preference data, connection string if it’s interacting with database and setting for user’s custom control over application. To do so, user adds custom class that stores all information and retrieve when need arise. Usually system administrator wishes to change setting information.

If information is stored in XML file, its easy to store, edit and retrieve by application, with help of System.Configuration namespace that task can be fulfilled.

There are two types of configuration files exist. Machine.Config, it is one which stores information for all application running in a computer, that defines setting for machine. Application .cofing files which stores information for a particular application and which resides in executable folder of running assembly.

Some of the settings which are exists in Machine.Config can be overridden in application configuration but only whose setting allowDefination property set to MachineToApplication , whose property set to MachineOnly can’t be override in application configuration.

To play with setting files, System.Configuration require, we can add reference to it by selecting add reference to our project and once its added to our application, it can be used by Imports in vb.net and using in C#.

To edit Machine.Configue file following steps are useful.

Create instance of Configuration by calling ConfigurationMangaer.OpenMachineConfiguration();

Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration();

There are different sections exist in it, let’s check ProtectedConfigurationSection.
ProtectedConfigurationSection pcs =
(ProtectedConfigurationSection)machineSettings.GetSection( "configProtectedData");

Its provider can be displayed as
MessageBox.Show(pcs.DefaultProvider);

Parameters of section can be accessed by.

MessageBox.Show(pcs.Providers[“DataProtectionConfigurationProvider”].Parameters[“description”]);


Configuration section has unique class, and that c

Each configuration section has a unique class. To determine which class a configuration section uses, call ConfigurationManager.OpenMachineConfiguration().GetSection(
"").ElementInformation.Type.ToString.

To edit application configuration file
Create instance of Configuration by method OpenExeConfiguration
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

Values can be added as
config.AppSettings.Settings.Add("MyKey", "MyValue");

Save new value to configuration file
config.Save(ConfigurationSaveMode.Modified);

After running above code check your configuration file, it should look like


Application settings can be read as ..
Configuration.AppSettings(“KeyName”);

Above code will return values of “KeyName” key.

Configuration.AppSettings return NameValueCollection, for database connection string we have ConnectionStringCollection.

The three most useful property of ConnectionStringClass are
Name -- defines name of connection string
ProviderName –type of database connection i.e sql servr, oracle, oledb etc
ConnectionString –defines a string how to connect with database.

We have following connection string in configuration file
Integrated Security=SSPI; AttachDBFilename=|DataDirectory|aspnetdb.mdf; User Instance=true"
providerName="System.Data.SqlClient" />

Though in above connections string split in many lines, in actual it can be placed in a single line.
We can access this connection as
ConfigurationManager.ConnectionStrings["mySqlServer"].ConnectionString

To create custom section in our application configuration there are two way to do that in first create a class that inherits from IConfigurationSectionHandler interface and create a class derived from ConfigurationSection class.

Friday, May 14, 2010

Show Tray Icon for your application In .net.

In our daily life we see many applications that run in background; we can see them in system tray. Let me tell you, System Tray at the bottom right corner of the screen which shows datetime, network connection, firewall or any programs that running but not showing in taskbar.

We can also put our application’s Icon in system Tray. To achieve it, just go through below steps.
-->Drag NotifiyIcon to your main form (Form which is going to run at start up)

-->Wire up event for form’s resized and add code as...
if(this.WindowState == FormWindowState.Minimized)
this.Hide();

-->Now we have two choice to again show our application in taskbar, either simply clicking on notifyIcon just call this.Show() or add a context menu.

-->This context menu have one or more options like restore application, close application etc.

NotifyIcon control has Icon property to show Icon of your application, and ContextMenuStrip to set contextmenu when you right click on it at system tray.

Thursday, May 13, 2010

Windows Service (Part-2)

In last post we learn how to build windows service in Visual studio, but work does not complete here. Once windows service is developed we need to install it.

We didn’t talk about how to give name to myservice or what property should be set when building it.

Firstly in windows service, we have ServiceBase if you look on designer view, check properties windows of it. Set ServiceName property, this will be our service name.

As we discussed we should write code in OnStart and OnStop method, we can even override other methods OnPause and OnContinue. Pause service is continued to serve users who are already consuming it, but don’t serve to new request. OnContinue is called when service is resumed from stop. To implement these methods set CanPauseAndContinue to true.

To override OnShutdown method, set CanShutdown to true. This method is called at the time of shutdown of computer.

To override OnPowerEvent method, set CanHandlePowerEvent to true. This method is invoked at the time of suspended mode of computer.

As we know to consume windows service, firstly we need to install it. To install it .net has provided ServiceInstaller and ServiceProcessInstaller classes.

ServiceInstaller class is used to define service description, display name, service name and startup type.

ServiceProcessInstaller class is used to define service account information.

àBy right clicking on designer of ServiceBase we can add ProjectInstaller.

àSet StartType property of ProjectInstaller from below list

Automatic: The service starts automatically after the computer starts, whether or not a user logs in.

Manual: A user must start the service manually. This is the default.

Disabled: The service does not start automatically, and users cannot start the service without first changing the start-up type.

àSet Description and DisplayName properties.

àSet ServiceDependedOn property. It may be possible service which we create is depends on some of serviced provided by operating system. We can add one more service in this list.

àSet Security Context of your service by specifying your Account property from one of the following value.

LocalService: Runs in the context of an account that acts as a nonprivileged user on the local computer, and presents anonymous credentials to any remote server. Use LocalService to minimize security risks.

NetworkService: Enables the service to authenticate to another computer on the network. This authentication is not required for anonymous connections, such as most connections to a Web server.

LocalSystem: The service runs with almost unlimited privileges and presents the computer’s credentials to any remote server. Using this account type presents a severe security risk; any vulnerabilities in your application could be exploited to take complete control of the user’s computer.

User: Causes the system to prompt for a valid user name and password when the service is installed. You can set values for both the Username and Password properties of your ServiceProcessInstaller instance. This is the default.

àSet your service project startup object as we have set as startup form in windows application.

Now last task is to install service on computer, we can do that either manually or by creating installer with .msi file.

To manually install service run InstallUtil “service.exe”. here “service.exe” is name of service assembly. InstallUtil is available in ...windows\Microsoft.Net\Framework\Versoion\Folder…

For installer, we can add installer project to our service solution as per other project give Primary output in installer. In primary output give output of windows service.

Once service is installed, we can start , stop from services. Services can be accessed from administrative tools in control panel or by right clicking on mycomputer and manage of it. One of manage list have node services, that is showing all available list of windows service.

By right clicking on service we can pause, run, restart, and stop service. We can even set start up type form there.

Wednesday, May 12, 2010

Windows Service (Part-1)

Windows service are application that don’t have any visual element or visual effect, they run in back ground. Windows service run under particular user session as long as we have configured it.

Windows operating system it self provides many services we are familiar with IIS, telnet, Security Center services. We don’t use all services provided by operating system, sometime we require to have some application that run automatically and do work independently without interruption from user interaction. Application starts as we start our computer and run as long as computer don’t shutdown.

In such type of situation we can build up windows service application and host on our computer where we want to have automatic run and stop functionality.

Before we start to talk about how to develop windows service, we check how is it different from other application types?

We can’t run or debug windows service from visual studio development environment so there is no use of F5 and F11 in case of windows service project.

We have to create installer to run windows service, unlike other project we don’t have dll or exe files and can use easily. We need to install windows service by installing to a particular computer.

The main method of your windows service project must have run command, which loads service to service control manager on appropriate computer.

Unlike other application, you would not able to show message box when application crash, or something happened, it will run on background, you will not get any information once service start as after it fully controlled by operating system.

Windows services run on their own security context, we should take care of user account and security problem.

Creation of Windows service project

àChoose windows service template for windows project type.

àwrite your code on OnStart and OnStop procedures, we can override other methods too.

Once windows service started, we can’t have any control on it, we don’t get any thing, in that situation we can create timer object and start timer once windows service start. After that we can write event for timer time elapsed. In such a way we do useful work by using windows services.

Monday, May 10, 2010

Application Domain and its configuration (Part-2)

In previous post we see how to create application domain, how to load and unload application domain. Sometime we don’t have idea of running assembly as we have loaded it from internet or some third party vendor. Such type of assembly may have possibly contains code, which create security vulnerabilities. Malicious code may corrupt your file system, application and damage to your hardware. To reduce this attack we can allow assembly to run in application domain but with limited privileges.

When you create an application domain, you have complete control over host evidence. Host evidence is the information of assembly, form which code group assembly belongs to.

With help of System.Security and System.Security.Policy you can provide evidence for particular application domain.

You can pass zone or code group for assembly when creating application domain with help of System.Security.Policy.Zone and System.Security.SecurityZone enumeration.

object[] hostEvidence = {new Zone(SecurityZone.Internet)};

Evidence internetEvidence = new Evidence(hostEvidence, null);

AppDomain myDomain = AppDomain.CreateDomain("MyAppDomain");

myDomain.ExecuteAssembly("myAssembly.exe", internetEvidence);

In above sample code we have created hostEvidence object with Internet code group and passed evidence object to ExecuteAssembly method.

Now “MyAppDomain” application domain will run “myAssembly.exe” with internet group privileges. As we know there is a very low control to run code which has been downloaded from internet or running directly from internet. By default Internet zone has very limited permission. There are other code groups are exist like “MyComputer” they can be useful when we want to give more permission to executable assembly in application domain.

We can pass evidence object when creating application domain as.

object [] hostEvidence = {new Zone(SecurityZone.Internet)};

Evidence appDomainEvidence = new Evidence(hostEvidence, null);

AppDomain d = AppDomain.CreateDomain("MyAppDomain", appDomainEvidence);

d.ExecuteAssembly("myAssembly.exe");

To fully customize application domain environment .net has provided AppDomainSetup class. By assigning various property and method to this class we can built up environment for new application domain.

AppDomainSetup has some properties like ApplicaitonBase which used to set root path for assembly, ApplicationName, ConfigurationFile, LicenceFile most of them are self describing from their name.

We can examine current application domains by using.

AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;

Saturday, May 8, 2010

Application Domain and its configuration (Part-1)

In .net all application assembly run under an application domain that is created by default for each application, we don’t need to create it. Common Language Runtime does it for application.

Application domain is logical unit to run different application in a single process. IIS is the very good example of it, in IIS more than one website or application are hosted, still they run independent with out interfering to any other application, hosted on same IIS.

Application domain creates a separate layer for application; .net run time is responsible for the various application runtime, while operating system manage process. In a process, we can run more than one application domain and each application domain has one or more assembly, application running. Each of these application domains can’t access resource or memory used by another application domain.

To create an application domain is as simple as we create an object of a class. The benefit of application domain is that when we don’t require or our work has been completed we can unload resource occupied by application runtime.

System.AppDomain class provides many methods and property to manipulate application domain.

-->Create an application domain
AppDomain ad = new AppDomain(“myAppDomain”);

We can run our assembly under this newly created Application domain.
ad.ExecuteAssembly(“myAssembly.exe”);

We can either call ExecuteAssemblyByName method to run assembly, in that case we need to pass name of assembly.
ad.ExecuteAssembly(“myAssembly.exe”);

There are so many properties and methods provide by AppDomain which gives ability to specify ID to process, friendlyname etc. Methods like Load, ApplyPolicy,CreateIntance etc.

If you notice in above code, we don’t have any constructor to create application domain, we are using static method of AppDomain class.

We can access current domains by ..


AppDomain myCurrentDomain = AppDomain.CurrentDomain;
To unload application domain, call Unload method of AppDomain

AppDomain.Unload(ad);

Friday, May 7, 2010

Threading in .net (Part -2)

In previous post, we have got idea of what is threading and how it can be done easily by calling ThreadPool.QueueUserWorkItem. But threading is not that mean only we need more control on our threading activity.

Like we need to ensure that all thread must work, give priority to my thread than other once, weather my thread has been completed or not, what is status of my thread etc.. all thing can be done by various type of mechanism provided by .net. Yes it’s surely a tedious and complex task to implement but if we do it carefully it not only reduces response time but application behaves very nicely and manages resources.

ThreadPool.QueueUserWorkItem provides a way to run thread in back ground and let it run until it finish. For more control on thread we can create instance of thread, we can even control start, pause, abort, priority. We can handle ThreadAbortException when thread has been aborted.

àCreate thread instance

Thread myThread = new Thread(new ThreadStart(myWork));

àStart thread

myThread.Start();

àWait for some time to run myThread

Thread.Sleep(2000);

àAbort myThread

myThread.Abort();

myWork method has following implementation

public static void myWork()

{

Console.WriteLine("myWork is running on another thread.");

try

{

Thread.Sleep(5000);

}

catch (ThreadAbortException ex)

{

Console.WriteLine("myWork was aborted.");

}

finally

{

Console.WriteLine("Use finally to close all open resources.");

}

Console.WriteLine("myWork has ended.");

}

In above code “myWork has ended” will never display as I have aborted thread. If I comment that line that it will be displayed.

We can call Thread.Suspend and Thread.Resume to stop and resume thread execution but sometime they can create problem. Say for example I am stopping a thread which has acquired my printer, so it will create deadlock condition as my other thread may need printer.

We can set thread priority before starting thread by ThreadPriority enumeration. Enumeration has following values.

àHighest

àAboveNormal

àNormal

àBelowNormal

àLowest

By default foreground and background run on normal priority.

Thread’s state can be checked with Thread.ThreadState property. There are various types of it like Unstarted, Running, Stopped, Suspended, Aborted etc. At a time a thread may have one or more thread state.

Sometime there is requirement to know status of thread which is running in background we want to pass some data to thread and let us know what is the output of that data after certain time elapsed. We can achieve this task by creating delegate and callback. For that we need to create a delegate at class level and a method to handle that delegate. Create a class for which you want to run in background, add delegate to class. Create an instance of class and in constructor pass delegate with appropriate method.

When there are more than one thread runs simultaneously, situation may happen it acquires resource and in turn deadlock. So it means instead of improvement in performance our application become slow and unresponsive. At that time we need to manage resource by synchronizing thread resource.

Use lock keyword in C# and SynLock keyword in vb.net. It does not allow using resource of any other thread till it completes it work. One thing should be kept in mind that these keywords work only with reference type not on value type.

When there is requirement of separate read and write lock on resource we can use ReaderWriterLock class. Create instance of this class and use separate read and write lock.

ReaderWriterLock rwl = new ReaderWriterLock()

To acquire read lock

rwl.AcquireReaderLock(10000);

Release reader lock

rwl.ReleaseReaderLock();

Acquire writer lock and release it.

rwl.AcquireWriterLock(10000);

rwl.ReleaseWriterLock();

Another method to synchronize thread is to use object of Interlocked class. It will add numeric value to thread. It also provides various numeric methods.

There are also so many things to wait for thread to complete and start another thread once complete previous one.

NOTE: In visual basic we need to add attribute to main method to run main thread as multithread. MTA (Multithread Apartment) is by default provided in C#, so there is no need to add it. MTA supports calling WaitHandle.WaitAll.

Thursday, May 6, 2010

Threading in .net (Part -1)

Most of the time developer chooses to develop program in linear way. In this mechanism user would need to wait sometime in some situation like application is going to download page from server, application is going to print document, applications is going to access remote database. Those cases are time consuming, user needs to wait till main thread completes work, sometime user get frustrated by response time, and application does not response to user till task has been completed.

To overcome, .net has provided threading mechanism. Our main thread executes as and in background we can execute process. So user will not feel that application is not responding, in background thread method executes and once result will be available, it would be shown to user.

Threading means in a single process execute more than one task among different processors. Now days most of computers are more than one core, we can use another core when main core is busy to complete task. We can distribute work task among different processors.

Though multithreading seems to be very complex, .net has provided a simple way to implement in programming. At a time there can be more than 250 threads run in back ground. We can even change it to more if require.

To work with thread we need to add System.Threading namespace to our application. We can run background thread by using ThreadPool.QueueUserWorkItem and passing method name or address of in vb.net.

static void Main(string[] args)

{

int workerThreads;

int completionPortThreads;

ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);

ThreadPool.QueueUserWorkItem(ThreadProc, "Thread 1");

ThreadPool.QueueUserWorkItem(ThreadProc, "Thread 2");

ThreadPool.QueueUserWorkItem(ThreadProc, "Thread 3");

ThreadPool.QueueUserWorkItem(ThreadProc, "Thread 4");

ThreadProc("ForgroundThread");

Thread.Sleep(1000);

Console.WriteLine("Worker Threads: {0} CompletePortThreads: {1}", workerThreads, completionPortThreads);

ThreadPool.QueueUserWorkItem(ThreadProc, "Thread 5");

ThreadPool.QueueUserWorkItem(ThreadProc, "Thread 6");

Console.WriteLine("Now main is continue");

}

Above code shows how many threads can be run, default value is 250. We have used ThreadProc method which will run in background thread. When main thread has no work at that time background thread will run and execute code. We can add as many threads as we wish as per limit of 250 and if required we can increase this maximum thread limit.

Thread which runs first is called Forground and other called background.

static void ThreadProc(object msg)

{

string threadMsg = (string)msg;

if (Thread.CurrentThread.IsBackground)

{

Console.WriteLine("Background Thread");

Console.WriteLine("My Threading method with:" + threadMsg);

}

else

{

Console.WriteLine("Forground Thread");

Console.WriteLine("My Threading method with:" + threadMsg);

}

}

We can check weather thread is background or not with Thread.CurrentThread.IsBackGround property.

Some time threading also overheads on processors, so need to take care while implementing threading as it distribute loads to different processor, more memory is required to manage resource.

Wise use of threading may improve application’s performance. It depends on requirement and application problem to use of Threading.

Wednesday, May 5, 2010

Custom Serialization (Part -3)

.Net has provided a way to serialize object as you wish, you can have all control when serializing and deserializing any object. You even decided format of storing serialized object. All custom serialization can be done by implementing ISerializable interface and applying Serializable attribute to class.

[Serializable]

class ShoppingCartItem : ISerializable

{

public Int32 productId;

public decimal price;

public Int32 quantity;

[NonSerialized]

public decimal total;

// Constructor used to initialized member of my ShoppingCartItem object.

public ShoppingCartItem(int _productID, decimal _price, int _quantity)

{

productId = _productID;

price = _price;

quantity = _quantity;

total = price * quantity;

}

// Constructor will be called on deserialization

protected ShoppingCartItem(SerializationInfo info,

StreamingContext context)

{

productId = info.GetInt32("Product ID");

price = info.GetDecimal("Price");

quantity = info.GetInt32("Quantity");

total = price * quantity;

}

// The following method is called during serialization

[SecurityPermissionAttribute(SecurityAction.Demand,

SerializationFormatter=true)]

public virtual void GetObjectData(SerializationInfo info,

StreamingContext context)

{

info.AddValue("Product ID", productId);

info.AddValue("Price", price);

info.AddValue("Quantity", quantity);

}

}

Above class shows how to implement custom serialization, we have implemented a constructor, that is called on deserialization. That will assign value to our object member.

We have also added a method, GetObjectData which is used to store value at the time of Serialization.

If we notice on constructor and methods, it uses SerializationInfo object that is used to convert value to different datatype combatable to our member’s type.

BinaryFormatter provides a way to handle serialized and deserialized events. There are four types of events

Serializing: This event is raised just before serialization takes place. Apply the

OnSerializing attribute to the method that should run in response to this event.

Serialized: This event is raised just after serialization takes place. Apply the OnSerialized attribute to the method that should run in response to this event.

Deserializing: This event is raised just before deserialization takes place. Apply the OnDeserializing attribute to the method that should run in response to this event.

Deserialized: This event is raised just after deserialization takes place and after IDeserializationCallback.OnDeserialization has been called. Apply the OnDeserialized attribute to the method that should run in response to this event.

Respond to one of the above events methods should follow below criteria

àStreamingContext object passed to method as parameter

àReturn Void

àAppropriate attribute should be specified on the method.

[OnSerializing]

void CalculateTotal(StreamingContext sc)

{

total = price * quantity;

}

[OnDeserialized]

void CheckTotal(StreamingContext sc)

{

if (total == 0) { CalculateTotal(sc); }

}

We can add above methods to our class to handle serialized events.

With the help of StrreamingContext, application can decide how to serialize or deserailzed object, we get idea of platform, weather object is serialized with same process or else, from where object is coming, object location etc.

To create custom formatter we should implement IFormatter interface, both of the BinaryFormatter and SoapFormatter have implementation of IFormatter. IFormatter provides many method to implement serialization and deserialization as per own custom way.