Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, December 11, 2008

Shoestring toolkit for startup projects


Integrated Development Environments

Database Environment

  • SQL Server Express 2008 (available in the above download page)

Web Framework

More Frameworks might be added based on requirements.

ORM

Testing

No code would be accepted without proper tests and high code-coverage. More on it during our discussions.

Source Control

Register with xp-dev.com and give me your username. I would later post the details on how to checkout the source code. I would also show you on how to work with the source control using TortiseSVN tools. All our source code checks into the xp-dev project repository. More details later. For now, download the SVN tools from here.

Additional tools

  • Code Analysis – FxCop
  • Text Editor – InType
  • Command Line - PowerShell (Pick your version - x86 or x64 based on your CPU)
  • XAML Editor - KaXAML (for some XAML/WPF/Silverlight learning)
  • Paint.NET – Graphics
  • .NET Reflector - I will give you later, when required.

Feel free to comment on what you think or if you have good general tools in mind, advice me.

Wednesday, October 01, 2008

Does Multi-Threaded Winforms application really exist?

For my thesis, I wanted a powerful MDI application. By powerful, I mean which can process at least 100 child forms at a time. Each form does a bunch of background work and for this reason I wanted a truly multithreaded windows application. So I went ahead and spawned the child forms using ThreadPool.

The child form is pretty simple for this example, it does not do any major background work. It just has a browser control and when clicked on a menu item, it sleeps for 10 seconds and sets the text of the form to "Done". I have two menu options, one to do work in the background and one which does not do that work in the background. But when you launch a Multithreaded MDI, you expect the work to be done in the background, irrespective of the way you code it.

private void someWorkNotInBackgroundToolStripMenuItem_Click(object sender, EventArgs e)
{
Thread.Sleep(10000);
this.Text = "Done";
}
A true multithreaded application should not stuck up other child windows when it does the above shown work.


But that is not the case. So you have do something like shown below, for the application to be truly responsive irrespective of the background work it does.



private void someWorkInBackgroundToolStripMenuItem_Click(object sender, EventArgs e)
{
new MethodInvoker(() => Thread.Sleep(10000)).BeginInvoke(new AsyncCallback(it => this.Text = "Done"), null);
}

A delegate is used to asynchronously perform background jobs inside a windows form. Doing so does not stuck up the application unlike the first case.


Using ThreadPool to spawn threads



Well, if you want a truly multithreaded application, then you have do all tasks in background using BeginInvoke() as shown the previous code snippet. Spawning child threads to create MDI Children would not help. But anyway, in this section, I show you how to use ThreadPool and just because we are talking about Multithreaded Windows, I show the windows in the worker thread.



Firstly, in order to use thread pool, we need a worker item. For this worker item, it is recommended you create a class that represents this worker item. My worker item is shown below.



class ThreadPoolWorkerItem
{
/// <summary>
///
The tracker supposedly keeps track of the worker item status.
///
Though in this example, it does not work. Usually in the work method,
///
you do a Set() on this tracker which signals the WaitHandle.
/// </summary>
private ManualResetEvent tracker;

/// <summary>
///
Initializes a new instance of the <see cref="ThreadPoolWorkerItem"/>
class.
/// </summary>
/// <param name="tracker">
The tracker.</param>
14:
public ThreadPoolWorkerItem(ManualResetEvent tracker)
{
this.tracker = tracker;
}

/// <summary>
///
Performs the work done by the current ThreadPool Worker Item.
/// </summary>
/// <param name="threadState">
State of the thread.
</param>
public void work(object threadState)
{
ChildForm cf = threadState as ChildForm;
//cf.Show() is invalid. It throws an InvalidOperationException, since cf was not created in this thread.
cf.Invoke(new MethodInvoker(() => cf.Show()));
cf.FormClosed += new FormClosedEventHandler(cf_FormClosed);
//The two statements below simulate a job that takes 1 second to work and then it notifies using the tracker.
//That is the way usually ThreadPool worker items should work.
//Thread.Sleep(1000);
//tracker.Set();
}

/// <summary>
///
Handles the FormClosed event of the cf control.
///
In this event, we supposedly inform the waiting thread about the current worker item's job done.
///
It does not work in this example.
/// </summary>
/// <param name="sender">
The source of the event.
</param>
/// <param name="e">
The <see cref="System.Windows.Forms.FormClosedEventArgs"/> instance containing the event data.
</param>
void cf_FormClosed(object sender, FormClosedEventArgs e)
{
tracker.Set();
}
}

The code explains how threadpool worker items should be created.


The code for adding worker items to the ThreadPool is shown below.





   1: /// <summary>


   2: /// Does the work.It creates ThreadPoolWorkerItems and adds it to the ThreadPool.


   3: /// </summary>


   4: private void DoWork()


   5: {


   6:     ThreadPool.SetMaxThreads(2, 2);


   7:     ManualResetEvent[] trackers = new ManualResetEvent[Maxthreads];


   8:     for (int i = 0; i < Maxthreads; i++)


   9:     {


  10:         trackers[i] = new ManualResetEvent(true);


  11:         ThreadPoolWorkerItem item = new ThreadPoolWorkerItem(trackers[i]);


  12:         this.Invoke(new MethodInvoker(() =>{                                                  {


  13:                      ThreadPool.QueueUserWorkItem(item.work, new ChildForm("http://google.com") { MdiParent = this });


  14:                 }));


  15:     }


  16:     WaitAll(trackers);


  17: }




The code explains how you actually create and add worker items to  thread pool. In this case using a "ThreadPool.QueueUserWorkItem(item.work,new ChildForm("http://google.com"){MdiParent = this});" would give a ThreadStateException (for other cases, you might see a InvalidOperationException). For that reason, a this.Invoke() is used to create the child form and spawn it.



So you schedule some jobs in the ThreadPool and you should wait for them to complete. So how do you wait? We use WaitHandle.WaitAll(trackers); which suspends the current thread until all the spawned worker items in the ThreadPool are completed, whose manual reset events are the "trackers".



But in our case, it does not work. So I thought, it has some issues and researched online. I found an alternative WaitAll() to be used in Windows Forms.





   1: /// <summary>


   2: /// Waits on all the wait handles to complete execution.


   3: /// The WaitHandle in this case is a manual reset event.


   4: /// </summary>


   5: /// <param name="waitHandles">The wait handles.</param>


   6: private void WaitAll(ManualResetEvent[] waitHandles)


   7: {


   8:     foreach (WaitHandle myWaitHandle in waitHandles)


   9:         WaitHandle.WaitAny(new WaitHandle[] { myWaitHandle });


  10: }




The WaitAll() to be used in Windows Forms. Note that none of the concepts explained would really create a multi-threaded windows forms applications where each child form run in its own thread. But the information I obtained is shared here.



Using Threads without ThreadPool



Threads could directly be created and spawned which shows the Child Forms. Something like that could be done as shown.





   1: for (int i = 0; i < Maxthreads; i++)


   2: {


   3:         new Thread(() =>{


   4:            this.Invoke(new MethodInvoker(() => 


   5:                 new ChildForm("http://google.com") { MdiParent = this }.Show()));


   6:                          }).Start();


   7: }




We create a thread which again delegates its job of creating a child window the the parent form. So is this going to be helpful? So can you create a truly multithreaded MDI application?



Again, I repeat, from what I know and from what I researched, you cannot create Child forms in an MDI application where each Child runs in its own thread. The form UI thread has to be spawned from the parent MDI form itself, thereby making it impossible for the thread to survive. As soon as the Show() is done, the thread dies, because it has nothing else to do!



Using Application.Run() to create child MDI forms



First of all, this is something I found out just now. So it has to be lame and you should probably not use this at any cost. But anyway here the code is.





   1: /// <summary>


   2: /// Handles the Click event of the launchUsingApplicationRunToolStripMenuItem control.


   3: /// It launches the Child windows using Application.Run().


   4: /// For it work, you should set the AparmentState of the thread to STA. Right now, I use a depricated way


   5: /// to do that. Optionally you can add a method with attribute set to STAThread, like in the Program.cs Main()


   6: /// </summary>


   7: /// <param name="sender">The source of the event.</param>


   8: /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>


   9: private void launchUsingApplicationRunToolStripMenuItem_Click(object sender, EventArgs e)


  10: {


  11:     for (int i = 0; i < 10; i++)


  12:     {


  13:         new Thread(() =>


  14:                        {


  15:                            ChildForm cf = new ChildForm("http://google.com") { };


  16:                            this.Invoke(new MethodInvoker(() => cf.MdiParent = this));


  17:                            Application.Run(cf);


  18:                        }) { ApartmentState = ApartmentState.STA }.Start();


  19:     }


  20: }




Do no use this. It just shows how retard I am.



Finally, how to make Multithreaded MDI?



From what I know, you cannot make a child form run in its own thread. But you can make the work it performs using asynchronous calls or threads.



So for every heavy job your child form does, you have spawn a thread or use asynchronous calls, iff you want your application to be responsive.



Disclaimer: I am no guru either in WinForms or Multi-threading. But I tried to share what I learnt writing applications for my thesis and job.

Saturday, February 09, 2008

Asynchronous Programming in .NET (C#)

Asynchronous Programming is supported by several areas in the CLR like Sockets, Remoting, Web Services, File IO, etc. In order to fully take advantage of these features, I think, one should know how to make asynchronous method calls, in the first place.
Asynchronous Calls -> You invoke the method and do not wait for it to complete. Instead you go ahead executing the subsequent calls. This is advantageous for situations where the subsequent code has got nothing to do with this method call. For example, you have obtained some data which you wish to write to a socket. In this situation you might not have to wait until the data is written. In this case, you can write the data asynchronously. Refer to this article for more detailed explanation of APM (Asynchronous Programming Model)
In order to make asynchronous calls, follow the steps...

1. Create the method you wish to call asynchronously.
public static void HelloWorld(string message)
{
Console.WriteLine("Welcome to my blog : "+message);
}
2. Write a delegate with the same signature as that of your method. Note delegates are declared outside a class or a struct, but not within.

public delegate void AsyncHelloWorld(string message);
3. Within Main() or wherever you wish to make this call, create an instance of this delegate passing the method you wish to be invoked.

AsyncHelloWorld acm = new AsyncHelloWorld(HelloWorld);
4. Invoke the method using BeginInvoke() which returns an instance of IAsyncResult. The first parameter is the parameter that is to be passed to the method HelloWorld. If there are more than one parameters that the method takes, then pass them in the same order. So we should say the BeginInvoke() takes a variable set of parameters and except the last two, the rest of the parameters are passed to the method. The last two parameters are the AsyncCallBack (you pass a method that is to be invoked on completion of execution of this method) and AsyncState. More about the arguments is here.
IAsyncResult res = acm.BeginInvoke("Krishna",null,null);
5. This call does not block unlike other method calls and instead proceeds further with execution. Now you might at sometime require to wait until this method is actually executed. In that case you make use of EndInvoke() method which takes in argument as the IAsyncResult object returned by the BeginInvoke().
acm.EndInvoke(res); //wait until the method is completed
6. On completion of execution, this method returns.

The complete code is shown below and is written in Snippet compiler
using System;
using System.Collections.Generic;
//should import the following namespaces...Important!
using System.Runtime.InteropServices;
using System.Threading;

public delegate void AsyncHelloWorld(string message);
public class MyClass
{
public static void HelloWorld(string message)
{
Console.WriteLine("Welcome to my blog : "+message);
}


public static void Main()
{
Console.WriteLine("Method to be called");
AsyncHelloWorld acm = new AsyncHelloWorld(HelloWorld);
IAsyncResult res = acm.BeginInvoke("Krishna",null,null);
//HelloWorld("Krishna");
Console.WriteLine("Method has returned");
acm.EndInvoke(res);
}
}


Asycnhronous Programming Screencast ....
[Developed with DeBugMode Wink]

Sunday, January 27, 2008

.NET 3.5 : VB and C#

[The code in this post appears weird for some reasons, I used LiveWriter and few good but buggy plugins to attach code]

I recently made a list of ASP.NET Videos that are out there online. Excluding the MSDN Nuggets and Microsoft Webcast events, the listings spanned over 4 pages!!! I am really concerned and am cursing myself for not having watched any of those for years. I have actually been a close follower of videocasts/screencasts right from those days when there weren't that many online for free. Now Microsoft, I should say is the largest provider of screencasts, of course only about MS technologies and yet there are tons of their videos that I should be watching. (Of course, lets not forget about Channel 9 where there are quiet a lot more screencasts about everything from MS)

Anyway there is also this dnrTV.com which is run by .NET Rocks guys and provides .NET TV Sessions. The most recent two shows are really something that everyone who is learning .NET should watch. It is by Kathleen Dollard and gives a first hand explanation about .NET 3.5 and shows VB 9.0 and C# 3.0 side by side which is really something! The actual show can be watched here.

I am writing down some important points for my own use and others might find it useful. I hope I am not violating any rights(hopefully).The disclaimer is that the images shown below is taken from the show using Snipping Tool which is shipped along with Windows Vista. This is not my work and I hope not to make any violations. In case of any, please let me know so that I can remove this post online.
Anyway my notes follows ....

.NET 3.5 Assemblies:

.NET 3.5 The important aspect is that .NET 3.5 still has the same Core - .NET 2.0. Simply put .NET 3.5 is nothing but .NET 3.0 plus additional features and we know that .NET 3.0 is nothing but .NET 2.0 Core plus few amazing libraries like the WPF, WCF, WF, CardSpace. It is also mentioned by Kathleen that Speech library is shipped in the .NET 3.0 and it is not that well known.

.NET Versions

.NET Versions There have been five versions of .NET till date. While VB 7 and C# was for .NET 1.0 and 1.1; VB 8 and C# 2.0 was for .NET 2.0 and .NET 3.0.

Now the brand new C# 3.0 and VB 9.0 adds a lot of new features makes programming in these languages very exciting.

Anyway the slides look amazing, you should watch the show without fail if you are interested!


Nullable in VB vs. C#

Declaring Nullable in VB

   1: Dim x as Nullable(Of Boolean) = False
   2: Dim y as Boolean? = False   

C# Nullables and bit more code to help you understand what Nullables are!


   1: bool? x = null;
   2: if(x.HasValue)
   3:  Console.WriteLine("x does have a value!");
   4: else
   5:  Console.WriteLine("x do not have a value and is null!");
   6: bool? y = x.GetValueOrDefault(); //y is initialized to false!
   7: Console.WriteLine("y is "+y);

Differences:

Suppose x and y are nullable booleans and x is set to null/nothing while y is set to false. Look at these:
x == y => False in C# and Nothing is VB (since one of them is nothing!). So can you guess the output of the following VB code snippet!

   1: Dim x As Nullable(Of Boolean) = Nothing    
   2: Dim y As Boolean = Nothing    
   3: Console.WriteLine("x = " + ((x = y) Is Nothing).ToString)


Another note for beginners! Consider the C# code:

   1: Employee emp = null;    
   2: if(emp==null)    
   3:  Console.WriteLine("Emp object is set to null!");

The equivalent VB code is:

   1: Dim emp as Employee = Nothing    
   2: If(emp = Nothing) 'This does not return true, = Nothing is not equivalent to == null    
   3:  Console.WriteLine("You would not see this line in the output!")    
   4: If emp Is Nothing ' This is how you check for null!    
   5:  Console.WriteLine("emp Object is set to null!")


If you read the above code snippet, I have conveyed the message in the comment on Line 2.

Frankly there are lot more differences with respect to how operators work differently in C# than in VB. Simply put the key point to remember is that

In Visual Basic, comparison between anything that is null(Nothing) to anything else returns Null/Nothing!!

In C#, you cannot use any operator but == on boolean

Note: By the way a great tool for .NET Developers in Snippet Compiler!

Operators in VB vs C#

Ternary Operator in C#:

   1: bool buddi = false;    
   2: string nameOfBuddi = buddi?"Bhargav":"Someone";    
   3: Console.WriteLine("Buddi is "+nameOfBuddi); //Displays "Someone"    
   4: buddi = true;    
   5: Console.WriteLine("Buddi is "+buddi?"Bhargav":"Someone"); //Displays "Bhargav"

Ternary Operator in VB:

IIf was used as ternary operator in VB but it is actually a function! But in VB 9.0, IIF is an operator! The actual difference would be understood when you look at this snippet:
   1: Shared Sub Main()    
   2:   Console.WriteLine(IIf(true,Method1(),Method2()))    
   3: End Sub    
   4:      
   5: Function Method1 as Integer    
   6:     Console.WriteLine("Method 1")    
   7:     Method1 = 1    
   8: End Function    
   9:      
  10: Function Method2 as Integer    
  11:     Console.WriteLine("Method 2")    
  12:     Return 5    
  13: End Function


The output of the above snippet is

Method 1
Method 2
1

As you can see, Method1() and Method2() are first evaluated and then the appropriate return value is returned. Here since its true, return value of Method1() is returned on the screen.

Another note for beginners, in Visual Basic, you can return a value in two ways. The first way is shown in the above code snippet in Line 7 where you assign FunctionName = returnValue and the second way is to use return keyword, like in other languages. You can use which ever makes more sense to you, well based on your choice.

The next few features were actually present in earlier versions of VB and unavailable in C# ( the above talked features were in C# only until VB 9.0)

Contd...

Saturday, October 27, 2007

C# 3.0 - Changes ! Learn them Quick!

Thanks to Mike Taulty, famous for MSDN Nuggets, that I started to learn LINQ. Will post the exact link sometime later.
But these are the various LINQ techs coming up:
1. LINQ to SQL
2. LINQ to XML
3. LINQ to Entities
4. DLinq
5. BLinq
and much more.

Before that I would recommend to learn the new changes in C# 3.0. The nuggets could be found here
http://www.microsoft.com/uk/msdn/nuggets/tags/C%23%20Version%203.0/default.aspx?pg=1

I am yet to watch these videos and once done! I would post some hello world! kind of programs that can help people like me to learn easily. Most of these videos usually use a very complex kind of examples and sometimes it is good while sometimes it is not so good!

More later...