Using Background Process in WPF

by munnaonc 16. June 2008 19:30

WPF applications often needs to call time consuming methods or processes, the time consuming methods or processes can be, huge time consuming calculation or perhaps a web service call. In case of WPF specially XBAP (wpf browser application) which run on remote client machines browser, this sort of calls can make your user interface unresponsive.  I am working with WPF for more than four month. Lot of things come in to way and dealt with nicely. Well in this post I am going to share a simple trick for avoiding unresponsiveness of user interface. We have already used this technique in many cases in our application, but this is for WPF.

 

The "Thread & Invoke"

 

BackgroundWorker is a very smooth and useful tool for our purpose of making more responsive UI(user interface). Before discussing more about BackgroundWorker lets take a flash back of legacy technique (which is pretty smart)  implementation of making  more responsive UI. Previously I used threading for implementing such kind of UI smoothness. What I did is to create a background thread and call expansive operation on that thread. When the job is finished use the "MethodInvoker" method to let know the UI thread that the job is finished. And this model is called asynchronous model. And this is quite smart model and rest of the models are based on this approach. Here is a quick code snippet for demonstration the technique.

//first start the method with tread
System.Threading.ThreadStart ts = new System.Threading.ThreadStart(ExpansiveMethod);
System.Threading.Thread t = new System.Threading.Thread(ts);
t.Start();
protected void ExpansiveMethod()
{
//Very expansive call will go here...
//after the job is finished call method to update ui
MethodInvoker updaterMI = new MethodInvoker(UpdateChange);
this.BeginInvoke(UpdateChange);
}
protected void UpdateChange()
{
//again back to main ui thread
}

 

The "Background Worker"

 

Okay, its time to use the BackgroundWorker. An amazing thing about background worker is, its simple to use.  First, lets see what a background worker is. "BackgroundWorker" is a class under "System.ComponentModel" which executes an operation on a separate thread. Which is introduced from dot net framework 2.0. Things are again pretty simple just like tread, All you have to do is instantiate a BackgroundWorker and subscribe its events, and call the "RunWorkerAsync()" method. Lets put a code snippet. Since we are programmers we understand code better.

void MyMethodToCallExpansiveOperation()
{
//Call method to show wait screen
BackgroundWorker workertranaction = new BackgroundWorker();
workertranaction.DoWork += new DoWorkEventHandler(workertranaction_DoWork);
workertranaction.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workertranaction_RunWorkerCompleted);
workertranaction.RunWorkerAsync();
}
void workertranaction_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Call method to hide wait screen
}
void workertranaction_DoWork(object sender, DoWorkEventArgs e)
{
//My Expansive call will go here...
}

As you can see in above code I have subscribed two event "DoWork" (which is the main function) and "RunWorkerCompleted", In dowork event handler we will put our expansive time consuming operations, as the name imply's RunWorkerCompleted event is fired when the work is finished . BackgroundWorker also has "ProgressChanged" event which is used to let the main UI thread know how much work is completed.

 

The "Dispatcher"

 

In few cases the BackgroundWorker needs to access the main UI thread. In WPF we can use "Dispatcher" which is a class of "System.Windows.Threading" and a delegate to access the main thread. First of all we have to declare a delegate for our candidate methods, and then use the delegate to call the method using Dispatcher. Dispatcher has few thread priority and you can use various priority from DispatcherPriority enum. "Send" has the highest priority in DispatcherPriority.

//delegate for our method of type void
public delegate void Process();
//and then use the dispatcher to call the method. 
Process del = new Process(UpdateMyUI);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, del);
void UpdateMyUI()
{
//get back to main UI thread
}

 

For more reading about this Asynchronous Programming please visit the references.

 

Reference

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

http://weblogs.asp.net/justin_rogers/articles/126345.aspx

http://www.eggheadcafe.com/articles/20050926.asp

Wpf Image ,Working with Image Source

by munnaonc 1. June 2008 19:28

Hi after a long time I am back in my blog. In this post I will discuss few things about WPF image object. Recently I have been working in a project whose UI Layer is build entirely with windows presentation foundation.

Background

WPF has another way to display image. That is, using BitmapImage object. You can declare BitmapImage tag and in WPF XAML just like Image tag. But in case of BitmapImage the source property is a Uri name is UriSource. Luckily BitmapImage is the source property of Image. Here is a simple code segment of Image and BitmapImage.

ImageSource & BitmapImage

WPF has another way to display image. That is, using BitmapImage object. You can declare BitmapImage tag and in wpf xaml just like Image tag. But in case of BitmapImage the source property is a Uri name is UriSource. Luckily BitmapImage is the source property of Image. Here is a simple code segment of Image and BitmapImage

<Image Width="200" Margin="5" Grid.Column="1" Grid.Row="1" >
<Image.Source>
<BitmapImage UriSource="sampleImages/bananas.jpg" />
</Image.Source>
</Image>

Mouse hover effect

Bellow I have listed few lines of code when i change the image in mouse enter and mouse out of an image object. Of course I am using Uri to define the location of my image then using the Uri to make a new BitmapImage and finally use BitmapImage to assign Image.Source Property.

   1:  private void btnGoToHome_MouseEnter(object sender, MouseEventArgs e)
   2:  {
   3:      this.Cursor = Cursors.Hand;
   4:      Uri src = new Uri(@"C:/Images/DifferentTransaction_Icon_Active.png");
   5:      BitmapImage img = new BitmapImage(src);
   6:      btnGoToHome.Source = img;
   7:  }
   8:  
   9:  private void btnGoToHome_MouseLeave(object sender, MouseEventArgs e)
  10:  {
  11:      this.Cursor = Cursors.Arrow;
  12:      Uri src = new Uri(@"C:/Images/DifferentTransaction_Icon_Normal.png");
  13:      BitmapImage img = new BitmapImage(src);
  14:      btnGoToHome.Source = img;
  15:  }

Thats it you are done

Reference

http://msdn.microsoft.com/en-us/library/system.windows.controls.image.aspx

Creating web application and web site that run in IIS 7 of windows vista from vs2008

by munnaonc 28. January 2008 18:17

While creating a web site in vs2005 or vs2008 , web site location has three options and the options are 1. File System 2. HTTP 3. FTP

image

Previous version of Visual studio (VS2002,VS2003) supports web application that run only on IIS. User can easily create web applications cause Visual Studio automatically guide the user to create a web application. Since vs2005 come with whole new application suite for example, Web Site template , web application template and mix mode of Ajax templates user had options to chose between many things. I personally used IIS and File System web site and web applications (File System web run on Vs integrated vs development web server ) in windows XP. I have recently moved to windows vista and and VS2008 Team System. I found some interesting stuff regarding windows vista and vs2008 that I thought need little share with the community (might help some one).

Web site in VS2008 on windows vista that run on IIS

image

I wanted to create a web site in IIS so I opened vs2008 selected ASP.net "Web Site" project template and Choose Local IIS but I found a strange message and unable to proceed to create a virtual directory from the wizard. I didn't read the message carefully, I thought my IIS is not installed properly or my IIS is not running. I opened my IIS administration MMC from administrator tool and found that IIS is up and running well, then I got confused and performed the same site creation operation again. This time when the Local Internet Information Server tab got selected I read the message carefully and it says how to create web site from vs2008, and it says I got to run vs2008 with "Run as administrator" :)

image

I closed my IDE and opened IDE from start menu with "Run as administrator" options selected from right click menu and performed the same operation again, this time every thing worked just okay :).

image

Web app in VS2008 on windows vista that run on IIS

While creating a "web application" project (which is created via choosing new project, rather than new web site from File->New menu) user do not have any option to select between File system or IIS hosted project in project creation wizard. By Default a File System based web application is created for the user. Just follow the normal procedure to create a web application, after web application creation is completed select the project properties. When the project properties window appear select the Tab named "Web*". You will see in web tab by default "Use Visual Studio Development Server" option is selected. change it to "Use IIS Web Server" option. After that just click on the Create Virtual Directory button to finish the procedure. save the project and you are good to go.

image

Oh one more thing, for this operation, again you have to run IDE in Run as administrator mode.

Asp.net File Upload Control Using with just one step

by munnaonc 27. May 2007 19:12

In our projects sometimes we need to use the file upload control. Asp.net 2.0 have
a build-in File-upload. In asp.net 1.x web controls didn’t had any builtin file-upload
control. Then we had to use a html input tag with type attribute set to “file” and
to use in server side add runat=”server” attribute.

<input id="myfileuploader" type="file" runat="server"/>

We all know how to work with a file upload control, today we will be discussion
about a new approach of file-upload. file-upload consists of two step . first we
have to select the file and then submit the page with a button or some kind of other
mechanism. To day we will try to minimize one step. If we want to upload the file
with just one step that is selecting the file here is the Technique

A file upload control which is eventually truned into a input html element have
three client side events

    * onBlur      
    * onChange
    * onFocus

we will utilize the onChange event… here is what we will do. frist add a asp.net
2.0 fileupload control in our page. then in pageload event add a attribute in attribute
collection. then write a javascript funtion to submit the form and in code do what
ever we whan….

 
task 1 : add a fileupload control

task 2: add the onchange attribute as FileUpload1.Attributes.Add("onchange", "doSomeStuff()");

task 3: add the javascript to submit the page

<script language="javascript"
type="text/javascript">

function doSomeStuff()
{

         document.forms[0].submit();

}

</script>

Thats it you are good to go.. in page load event check wheither the filename is
empty or not and then do the file upload.

VS templates not working? Easy to get things back.

by munnaonc 6. March 2007 20:59

Recently I had to work with window SharePoint Service 3.0 and its development. I download the visual studio 2005 project templates for SharePoint development. I downloaded the project msi from Microsoft download site.

http://download.microsoft.com/download/e/8/a/e8aa8476-5af6-4f38-aed2-0247a99d2bc6/VSeWSS.msi

Installed in my local computer… but when I opened the IDE2005 project templates are not there…..

I got confused… and try reinstall the msi… but noting happed… I went to google and found few people is also suffering from this problem… the problem is my vs2005 is installed in different drive other that “c:\” and the installed temples are in default “c:\”… and then I moved my template in the drive where the IDE2005 is installed….

Location of the project templates is [your dive letter]:\Program Files\Microsoft Visual Studio 8\Common7\IDE…

There were two directories one if project template and other is item template… last thing that I did is to make ide identity the project templates….

For this I had to just a command in vs2005 comma prompt..

devenv /installvstemplates

I found help from the following forum… please go there for more detailed discussion…

http://geekswithblogs.net/ehammersley/archive/2005/11/08/59451.aspx

Hope this will help someone someday….

Install assembly into Global Assembly Cache

by munnaonc 3. March 2007 20:52

Option One

Step One add the sn.exe to External Section of VS2005

1. Click on Menu->Tools->External Tools
2. A window with all external tool listed will popup.. click on add button
3. In title type “String Name tool”
4. In command brows for sn.exe tool [Generally in the bin directory of your sdk folder]
5. Check the use output window and prompt for argument check box…
6. Click on apply to dismiss the widow…

Now you can see that in tools menu you will have a menu item named “Strong Name Tool”. Click on the menu will launch a window asking the argument …. In the argument text box type

–k “c:\\mykeypair.snk”Click on okey to dismiss the window… in output window you will see that successful keypart creation message will be shown…

Your key is reated but not yet associated with any

Adding the key to the project to associate with assembly1. Open your project…
2. Open the property of the project…
3. You will see a tab called signning is bottom of the window… click on the signning button
4. In siginning tab check the sign the assembly check box.
5. In choose a strong name key file … click on brows …. And brows for your mykeypair.snk file…
6. save the project and build it…

That’s it your assembly is strong name signed on….

Option Two [Too Easy]

1. Open your project…
2. Open the property of the project…
3. You will see a tab called signning is bottom of the window… click on the signning button
4. In siginning tab check the sign the assembly check box.
5. In choose a strong name key file … click on new…
6. A window asking for snk file will popup… type the desiered name and click on okey to dismiss the window… save the project and build it…

That’s it your assembly is strong name signed on….

Deploy the assembly in GAC…

1. Add the gacutil.exe tool just like the sn.exe tool
2. Now open the gacutil tool from tools….
3. In the argument window type….
4. -i "$(ProjectDir)\bin\debug\DataBaseHelper.dll" or [-I “yourprojectdir\buildmode[debug or release]\bin\filename.dll”]
5. Click on okay to dismis the window..
6. In output window you will see a successful message….
7. “Assembly successfully added to the cache”

Happy programming!

Tags: , , , , , ,

.net | .net 1.1 | .net 2.2 | .net 3.0 | .net 3.5 | dll | GAC

CSS Problem of Ajax Tool Kit Calendar

by munnaonc 19. February 2007 20:35

AjaxControlTookKit is a very nice addition of Asp.net 2.0 Ajax Extension. Recently I had very nice experience using asp.net 2.0 Ajax in few of my projects. "update panel" is very use full control as far as easy Ajax is concern. I haven't explored the whole area of client side scripting, but so far the experience with the server side controls are pretty much good and satisfactory.

Problem with Calender

In one of my project, I had to use the Calendar Extender of Ajax. Well in the page level the Calender Extender worked fine. but when i put the extender in one of my usercontrol. after the page render in browser the calender popup's position is pretty strange. No deterministic behavior was found in popup. when I click on the button of the calender the popup window appeared way up where it should actually show.


I went on trying few things to fix the thing and succeed on the setting position to relative. I just put the position behavior of the parent div of the Extender to relative.


style="position:relative"

worked like cramp

Another problem

If you set the css property of the calender extender suddenly the calender loose all its default behaviour and color skim. And no detail guide line is found in the ajax.asp.net site for customizing the style of the calender control.


Since ajaxControlToolKit is under development we hope this issues will be fixed in the actual release product.

Asp.net Tree view control, very useful But.

by munnaonc 26. November 2006 20:30

Asp.net 2.0 ships with a whole new set of controls. Navigation controls are one of them. In navigation control we have three options

  1. Sitemap path
  2. Menu
  3. Tree View

TreeView

 

Recently I have worked in a project which is a demo project where I had the pleasure of using the asp.net 2.0 tree view control. Below I will be demonstrating a simple way to use the treeview and some things that we should know while we use tree view control of asp.net 2.0 in our projects.

 

Obviously tree view control has node property and nodes can be create dynamically and modify the node collection on runtime. But it’s for only level one node. For level two nodes node is created just the way it is, but need to add in the child node property. So in a sense tree view has node property and nodes have no recursive node property and to deal with child node, node has child node collection.

 

Constructor of Node class has several overloads. Actually 5 of them are there.

 

TreeNode tn = new TreeNode("Text");

TreeNode tn = new TreeNode("Text", _value);

 

Here we should always be careful about the value property. This value property must be distinct for each collection.

 

For example if we have a Tree Node consists of three Nodes and each and every done has value property as a same value. SelectedNodeChanged even returns always the first node of the collection.

 

TreeNode tn1 = new TreeNode("Node One",-1);

TreeNode tn2 = new TreeNode("Node Two",-1);

TreeNode tn3 = new TreeNode("Node Three",-1);

TreeView1.Nodes.Add(tn1);

TreeView1.Nodes.Add(tn2);

TreeView1.Nodes.Add(tn3);

 

In the web application if we select node three that is tn3 … in SelectedNodeChanged event we will have th1 as SelectedNode. I don’t know how this happened but surely it happened. But if we provide different value in the value field of the node constructor this was okay. Even if we don’t provide any value things work just fine.

 

Tree view has a wide range of configuration and style settings. Among these StaticItemStyle and StaticItemHoverStyle is most useful.

 

Well sometime we need to disable a node in our view. But TreeNode class do not have any enable or disable property, rather it has selection Action Property. We need to set the selection property value to none to make a node disabled.

Try.Catch. is not a good Practice

by munnaonc 12. September 2006 20:09
I don’t know using try catch in your code is good or bad. But I am sure that it makes your code run more slowly. For the early edge of my programming carrier I believed that c# language has managed the try catch or exception handling quite well. So we can use try catch as much as we can in our code to deal with the exception. But while working on the International Tax Expert project I found try catch is making my program working slow... this happens specially in paring a string to integer.

Let say

We have a code portion like

bool IsValidInteger(string s)
{
try
{
int x = int.parse(s);
return true;
}
catch
{
return false;
}
}

If we manage to provide an invalid string which is not an integer the program returns the accurate value that is false. And for only one case this works fine and no performance degradation occurs.

But if we have to fill a data grid which has 1000 rows and one columns value is filed using the above mentioned function to show an icon or assign formatting for the data to show on the cell. The performance hit shows, and the program run slow.

So it is better to avoid “try catch” as much as you can in your code, there is always a good way to code such things. We should always remember coding is also an art and we can make it stylish.

Our senior software Engineer Hasan Shahriar Masud provided a good example on this matter the example is given bellow.

“We should not use try-catch if we can logically conclude the exception. It will help the performance, which munna(that is me) proved.

For example

//We should not write
Try
{
C=A/B;
//Do Something 1
}
Catch
{
//Do Something 2
}
//We should write
If (B==0)
{
Do Something 2
}
Else
{
C=A/B;
//Do Something 1
}
I have investigated this on Xceed grid 3.1 in case of data convertion. May be its a problem of xceed grid.

Tags: , , , , ,

Xceed | .net 3.5 | .net | .net 1.1 | .net 2.2 | .net 3.0