Monday, December 29, 2008

Check if the Internet Connection State is active inC#

A small application which uploads Images of new products and therefore I had to check if the Internet Connection State is active, otherwise it would crash. There are actually two ways (and probably more) of doing this, depending on your system. You could go with a direct api call:
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

//Creating a function that uses the API function...
public static bool IsConnectedToInternet()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
The Description can be found on MSDN, depending on the Connection the proper Value has to be entered.

Another way would be resolving some host of which you are sure it is online all the time. That could be microsoft.com, your company’s website or something else. Here we go:

public static bool IsConnected()
{
System.Uri Url = new System.Uri("http://www.microsoft.com");

System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);

try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
return true;
}

catch
{
WebReq = null;
return false;
}
}


Read more!!!

How to resize Workarea of desktop in C#

public struct Rect
{
public Int32 Left, Top, Right, Bottom;
}

The code below is that the workarea is reduced by the height of Form and the Form is placed bottom of the workarea. It is like application of Cash Fiesta6

private void button1_Click(object sender, EventArgs e)
{
Rect DeskArea = new Rect();
SystemParametersInfo(48/*SPI_GETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
this.Left = 0;
this.Width = DeskArea.Right;
this.Top = DeskArea.Bottom - this.Height - 4;
DeskArea.Bottom = DeskArea.Bottom - 150;
SystemParametersInfo(47/*SPI_SETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
}

And now you need to replace the orkarea to its original size.

private void button2_Click(object sender, EventArgs e)
{
Rect DeskArea = new Rect();
SystemParametersInfo(48/*SPI_GETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
DeskArea.Bottom = DeskArea.Bottom + 150;
SystemParametersInfo(47/*SPI_SETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
}


Read more!!!

Friday, December 26, 2008

Hiding application from taskbar in C#

public class Taskbar
{
[DllImport( "user32.dll" )]
private static extern int FindWindow( string className, string windowText );
[DllImport( "user32.dll" )]
private static extern int ShowWindow( int hwnd, int command );

private const int SW_HIDE = 0;
private const int SW_SHOW = 1;

protected static int Handle
{
get
{
return FindWindow( "Shell_TrayWnd", "" );
}
}

private Taskbar()
{
// hide ctor
}

public static void Show()
{
ShowWindow( Handle, SW_SHOW );
}

public static void Hide()
{
ShowWindow( Handle, SW_HIDE );
}
}
Another very easy way:
this.ShowInTaskbar = false;


Read more!!!

Hiding titlebar /caption/ of Form in C#

It is very easy as below

this.Text = String.Empty;
this.ControlBox = false;


Read more!!!

Saturday, December 20, 2008

Another resource for Multithreading in C#

Introduction:

In this article let us see about multithreading. Multithreaded applications provide the illusion that numerous activities are happening at more or less the same time. In C# the System.Threading namespace provides a number of types that enable multithreaded programming.

Threading in C#

System.Threading Namespace

The System.Threading Namespace provides a number of types that enable multi-threading programming. In addition to providing types that represent a particular thread, this namespace also describe types that can handle a collection of threads (Thread Pool), a simple (Non -GUI based) Timer class and several types to provide synchronized access to shared data.

The most primitive of all types in the System.Threading namespace is Thread. Thread:

Represents a thread that executes with in the CLR. Using this type, one can able to spawn additional threads in the owning AppDomain.This type defines a number of methods (both static and shared) that allow us to create new threads from a current thread, as well as suspend, stop, and destroy a given thread.

The following example will demonstrate Spawning of Secondary threads using C#.

internal class EmployeeClass
{
public void Performjob()
{

// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i=0;i<10;i++)
{
Console.write(i +",");
}
console.writeline();
}
}
The above code simply prints out a series of numbers by way of the performjob() member function.

Now assume that a class (Main class) creates a new instance of EmployeeClass. In order for the Main class to continue processing its workflow, it creates and starts a new thread that is used by the job. In the code below, notice that Thread type requests a new Threadstart delegate type:

Public class Mainclass
{
public static int Main (string[] args)
{
Console.Writeline("ID of primary thread is {0}",
Thread.CurrentTHread.GetHashCode() );

// Make Employee class.

EmployeeClass j = new EmployeeClass();

// Now make and start the background thread.

Thread backgroundThread =
new Thread(new ThreadStart(j.Performjob));
backgroundThread.Start();
return 0;
}
}
If we run the application we would find the following result.
ID of primary thread is: 2
ID of Employee thread is: 11
Employee says: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Press any key to continue
From the above example one can easily know how to spawning the secondary Threads.

Let us see another example regarding two active threads.

internal class EmployeeClass
{
public void Performjob()
{
// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i = 0; i < 20000 ; i++)
{
Console.write(i +",");
}
console.writeline();
}
}

Public class Mainclass
{
public static int Main (string[] args)
{
// Make Employee class
............
//Now make the thread.
............
//Now while background thread is working
//do some additional work.
MessageBox.show("BUSY");
return(0);
}
}
If we run this application we would see that the message box is displayed and it can be moved around the desktop, while the background Employee thread is busy pumping numbers to the console.

Thread Synchronization:

A multithreaded application usually has resources that can be accessed from multiple threads; for example, a global variable that is incremented or decremented by multiple threads. It is sometimes desirable to prevent multiple threads from concurrently altering the state of a resource. The .NET Framework includes several classes and data types that we can use to synchronize actions performed by two threads.

The simplest case is if we have a shared variable that we need to update from different threads. To do this, we can use the System.Threading.Interlocked class. For example, to increment or decrement the shared variable called num, we'd write Interlocked.Increment(num) or Interlocked.Decrement(num). we can also use Interlocked to set the variables to a specific value or to check the equality of two variables.

If there's a section of code in an object's method that should not be accessed concurrently by multiple threads, we can use the Monitor class to acquire a lock on that object by calling Monitor.Enter(object). Any other thread wanting to execute the same code would need to acquire the same lock and will be paused until the first thread releases the lock by calling Monitor. Exit(object).

For more control over thread synchronization or for cross-process synchronization, use the Mutex class, which is a named synchronization object that can be obtained from any thread in any process. Once we create or obtain the mutex, we use its GetHandle method to (as we'd expect) get a handle that we can use with the WaitHandle.WaitAny or WaitHandle.WaitAll methods. These two methods are blocking and will return only if the specified handle is signaled (that is, the mutex is not being used by another thread) or if the specified timeout expires. After we obtain the mutex, we perform the necessary synchronized processing and then call Mutex.ReleaseMutex to release it.

Sometimes we need a mechanism for one thread to notify other threads of some interesting event that occurred. In those cases we can use the .NET synchronization event classes, ManualResetEvent and AutoResetEvent. In the world of thread synchronization, an event is an object that has two states: signaled and nonsignaled. An event has a handle and can be used with WaitHandle just like a mutex. A thread that waits for an event will be blocked until another thread signals the event by calling ManualResetEvent.Set or AutoResetEvent.Set. If we are using a ManualResetEvent, we must call its Reset method to put it back to the nonsignaled state. An AutoResetEvent will automatically go back to nonsignaled as soon as a waiting thread is notified that the event became signaled.

Conclusion:

That's all it takes to create a multi-threaded application in C#.The System.Threading namespace in .NET SDK makes multi-threading easy.The System.Threading Namespace provides a number of types that enable multi-threading programming easily in C#. The Thread class in the System.Threading namespace exposes the properties and methods to allow the free threading.


Read more!!!

Multithreading in C#

Any Windows application must have one or more processes. A Process is structural unit with a memory block and using some set of resources. For each executable, the Windows operating system creates some isolated memory block. This C# .Net Tutorial tries to explain the basics of Multithreading in C# .Net.

Every process must have at least one thread. The first thread is created with a process and is known as primary thread. This Primary Thread is entry point of application. In traditional Windows applications it is the method WinMain() and in console applications it is named main().

Main goal of creating multithreading application is performance improvement. As an example, imagine a situation where in a user starts a long process (e.g. copying), he can?t use a single threaded application and wait for an infinite time for the operation to get completed. But if he uses multi?threading application he can set copying process in the background and interact with application without any problems.

At first, if one wants to create a multi-threaded application an important point to be remembered is, a global variable, which is being accessed by different threads, can try to modify the same variable. This is a generic problem, which is solved using a mechanism called Synchronization of threads. Synchronization is nothing but the process of creating some set of rules to operate data or resources.

The C# .Net language has a powerful namespace which can be used for programming with Threads as well as Thread Synchronization in C# .Net programming. The name of the namespace is Sytem.Threading. The most important class inside this namespace for manipulating the threads is the C# .Net class Thread. It can run other thread in our application process.

Sample program on C# Multithreading - C# Tutorial:

The example it creates an additional C# .Net class Launcher. It has only one method, which output countdown in the console.

//Sample for C# tutorial on Multithreading using lock

public void Coundown()
{

lock(this)
{

for(int i=4;i>=0;i--)
{

Console.WriteLine("{0} seconds to start",i);

}

Console.WriteLine("GO!!!!!");

}

}

There is a new keyword lock inside the above chunk of .Net C# tutorial code. This provides a mechanism for synchronizing the thread operation. It means at the same point of time only one thread can access to this method of created object. Unless the lock is released after completion of the code, the next routine or iteration cannot enter the block.

To understand it more clearly please have a look at the piece of main method?s code:

Launcher la = new Launcher();

Thread firstThread = new Thread(new ThreadStart(la.Coundown));
Thread secondThread =new Thread(new ThreadStart(la.Coundown));
Thread thirdThread = new Thread(new ThreadStart(la.Coundown));

firstThread.Start();
secondThread.Start();
thirdThread.Start();

As you see there were created three additional threads. These threads start a method of object that has Launcher type. The above program is a very simple example of using multi-threading in C#. Net. But C# .Net allows us to create more powerful applications with any level of complexity.

At last a few words about attached example. It can be compiled using Microsoft .NET command line. Just type csc filename.cs. After it CSC compiler creates an executable version of your code, since it can be run as standard exe file.


Read more!!!