Tuesday, 21 May 2013

How to: Hide Column Headers in the Windows Forms DataGridView Control ?





Sometimes you will want to display a DataGridView without column headers. In the DataGridView control, the ColumnHeadersVisible property value determines whether the column headers are displayed.



To hide the column headers

  • Set the System.Windows.Forms.DataGridView.ColumnHeadersVisible property to false.

    dataGridView1.ColumnHeadersVisible = false
    
    
    //this line of code will hide the ColumnHeaders from gridview.


Wednesday, 15 May 2013

Background and Foreground thread in c# ?




  • Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.
  • Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.
  • It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the Thread.Start() method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require.
    Example:
    Thread Foreground Background






    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace TestThread
    {
    class Program
    {
    static void Main(string[] args)
    {

    //Create object of parameterized thread, so that you can pass parameter to any thread

    ParameterizedThreadStart pst = new ParameterizedThreadStart(obj.function1);

    //Bydefault threads are Foreground Thread
    Thread t1 = new Thread(pst);

    //Set Thread Name
    t1.Name = "Thread1";

    //Passs Parameter to thread
    t1.Start(true);

    //Create object of ThreadStart, it does not have any parameter
    ThreadStart ts = new ThreadStart(obj.function2);
    Thread t2 = new Thread(ts);
    t2.Name = "Thread2";

    //Make it Background Thread
    t2.IsBackground = true;

    //Run the thread
    t2.Start();

    Console.ReadKey();
    }

    public void function1(object val)
    {
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("This is parameterized function1 by {0} and Value passed is {1} ", Thread.CurrentThread.Name, val);
    }
    }
    public void function2()
    {
    for (int i = 0; i < 5; i++)
    {
    Console.WriteLine("This is function2 by : " + Thread.CurrentThread.Name);
    }
    }

    }
    }

    WaitHandles - Auto/ManualResetEvent and Mutex



    WaitHandles - Auto/ManualResetEvent and Mutex
    Monitor.Wait/Pulse isn't the only way of waiting for something to happen in one thread and telling that thread that it's happened in another. Win32 programmers have been using various other mechanisms for a long time, and these are exposed by the AutoResetEventManualResetEvent and Mutex classes, all of which derive from WaitHandle. All of these classes are in the System.Threading namespace. (The Win32 Semaphoremechanism does not have a managed wrapper in .NET 1.1. It's present in .NET 2.0, but if you need to use it before then, you could either wrap it yourself using P/Invoke, or write your own counting semaphore class.)
    Some people may be surprised to learn that using these classes can be significantly slower than using the various Monitor methods. I believe this is because going "out" of managed code into native Win32 calls and back "in" again is expensive compared with the entirely managed view of things which Monitor provides. A reader has also explained that monitors are implemented in user mode, whereas using wait handles require switching into kernel mode, which is fairly expensive.
    WaitHandle itself only exposes a few useful instance methods/properties:
    • WaitOne() - used to wait for the handle to be free/signalled. The exact meaning of this depends on the concrete type being used (MutexAutoResetEvent or ManualResetEvent).
    • Close()/Dispose() - used to release the resources used by the handle.
    • Handle - used to get the native handle being wrapped. Most developers won't need to use this.
    In addition, it has two useful static methods which deal with sets of WaitHandles:
    • WaitAny() - used to wait for any of the handles in a set to be free/signalled.
    • WaitAll() - used to wait for all of the handles in a set to be free/signalled.
    All of the WaitXXX() methods have overloads allowing you to specify a timeout and whether or not to exit the "synchronization domain". The default value is false. What is a synchronization domain, you ask? Well, it's to do with some automatic thread handling that .NET has to offer in the guise of Transactional COM+. Most .NET developers won't need to use this, but Juval Löwy has an article on the topic if you wish to find out more, and likewise Richard Grimes wrote one for Dr. Dobb's journal.


    Auto/ManualResetEvent
    The two "event" classes (which are entirely different from .NET events - don't get the two confused) come as a sort of pair, and are very similar. You can think of them like doors - when they're in the "signalled" (or "set") state they're open, and when they're in the "non-signalled" (or "reset") state, they're closed. 

    A call to WaitOne() waits for the door to be opened so the thread can "go through it" in some sense. The difference between the two classes is that an AutoResetEvent will reset itself to the non-signalled state immediately after a call to WaitOne() - it's as if anyone going through the door closes it behind them. 

    With a ManualResetEvent, you have to tell the thread to reset it (close the door) when you want to make calls to WaitOne() block again. Both classes can manually be set or reset at any time, by any thread, using the Set and Reset methods, and can be created in the signalled/set or non-signalled/reset state. (These methods return a boolean value saying whether or not they were successful, but the documentation doesn't state why they might fail.)

    Here's some sample code which simulates 10 runners. Each runner is passed a ManualResetEvent which is initially non-signalled. When the runner completes the race, it signals the event.
    The main thread usesWaitHandle.WaitAny to wait for the first runner to finish, and uses the value returned by the method to say who won the race. It then uses WaitHandle.WaitAll to wait for everyone to finish. Note that if we'd usedAutoResetEvent instead, we'd have to call Set on the event of the winner, as it would have been reset when we detected it being set with the call to WaitAny.
       
    Example...


    using System;
    using System.Threading;

    class Test
    {
        static void Main()
        {
            ManualResetEvent[] events = new ManualResetEvent[10];
            for (int i=0; i < events.Length; i++)
            {
                events[i] = new ManualResetEvent(false);
                Runner r = new Runner(events[i], i);
                new Thread(new ThreadStart(r.Run)).Start();
            }
           
            int index = WaitHandle.WaitAny(events);
           
            Console.WriteLine ("***** The winner is {0} *****",
                               index);
           
            WaitHandle.WaitAll(events);
            Console.WriteLine ("All finished!");
        }
    }

    class Runner
    {
        static readonly object rngLock = new object();
        static Random rng = new Random();
       
        ManualResetEvent ev;
        int id;
       
        internal Runner (ManualResetEvent ev, int id)
        {
            this.ev = ev;
            this.id = id;
        }
       
        internal void Run()
        {
            for (int i=0; i < 10; i++)
            {
                int sleepTime;
                // Not sure about the thread safety of Random...
                lock (rngLock)
                {
                    sleepTime = rng.Next(2000);
                }
                Thread.Sleep(sleepTime);
                Console.WriteLine ("Runner {0} at stage {1}",
                                   id, i);
            }
            ev.Set();
        }
    }


    Mutex
    Whereas Auto/ManualResetEvent have a lot in common with using Monitor.Wait/PulseMutex has even more in common with Monitor.Enter/Exit. A mutex has a count of the number of times it's been acquired, and a thread which is the current owner. If the count is zero, it has no owner and it can be acquired by anyone. If the count is non-zero, the current owner can acquire it however many times they like without blocking, but any other thread has to wait until the count becomes zero before they can acquire it. The WaitXXX() methods are used to acquire the mutex, and ReleaseMutex() is used by the owner thread to decrease the count by one. Only the owner can decrease the count.
    So far, so much like Monitor. The difference is that a Mutex is a cross-process object - the same mutex can be used in many processes, if you give it a name. A thread in one process can wait for a thread in another process to release the mutex, etc. When you construct a named mutex, you should be careful about making assumptions as to whether or not you will be able to acquire initial ownership of it. Fortunately, there is a constructor which allows the code to detect whether the system has created a whole new mutex or whether it's used an existing one. If the constructor requested initial ownership, it will only have been granted it if it created a new mutex - even if the existing mutex can immediately be acquired.
    Mutex names should start with either "Local\" or "Global\" to indicate whether they should be created in the local or global namespace respectively. (I believe that local is the default, but why take the risk? Make it explicit in the name.) If you create a mutex in the global namespace, it is shared with other users logged into the same machine. If you create a mutex in the local namespace, it is specific to the current user. Make sure you pick a suitably unique name so you don't clash with other programs.
    To be honest, I think the principle use that mutexes will be put to in .NET is the one mentioned earlier - detecting that another instance of an application is already running. Most people don't need inter-process communication on this kind of level. The other use is to enable you to block until either one or all of a set of WaitHandles is released. For other purposes, where Monitor is good enough, I suggest using that - especially as C# has the lock statement specifically to support it. Here's an example of detecting a running application, however:


    using System;
    using System.Threading;

    class Test
    {
        static void Main()
        {
            bool firstInstance;
            
            using (Mutex mutex = new Mutex(true,
                                           @"Global\Jon.Skeet.MutexTestApp",
                                           out firstInstance))
            {
                if (!firstInstance)
                {
                    Console.WriteLine ("Other instance detected; aborting.");
                    return;
                }
               
                Console.WriteLine ("We're the only instance running - yay!");
                for (int i=0; i < 10; i++)
                {
                    Console.WriteLine (i);
                    Thread.Sleep(1000);
                }
            }
        }
    }
    Run the example in two different console windows - one will count to ten slowly; the other will abort after it detects that the other application instance is running. Note the using statement around the mutex: this should extend across the whole of the application's execution, otherwise another instance would be able to create a new mutex with the same name, after the old one had been destroyed. For instance, suppose you use a local variable without a using statement, like this:


    using System;
    using System.Threading;

    class Test
    {
        static void Main()
        {
            bool firstInstance;
           
            // Bad code - do not use!
            Mutex mutex = new Mutex(true,
                                    @"Global\Jon.Skeet.MutexTestApp",
                                    out firstInstance);
           
            if (!firstInstance)
            {
                Console.WriteLine ("Other instance detected; aborting.");
                return;
            }
           
            Console.WriteLine ("We're the only instance running - yay!");
            for (int i=0; i < 10; i++)
            {
                Console.WriteLine (i);
                Thread.Sleep(1000);
            }
        }
    }


    In that case, you'd probably find that everything would work fine under debug, where the GC is very conservative about what it collects. When not running under the debugger, however, the GC can tell that the mutexvariable isn't used after its initial assignment, so for the main duration of the app, it can be garbage collected at any time - and that destroys the mutex! The using statement shown earlier is only one way round this. You could make it a static variable instead, or use GC.KeepAlive(mutex); at the end of the method to make sure that the GC doesn't ignore the variable.

    How to make a loop to wait until background thread completes its execution(Multi Threading)?


    some times we want to use the same thread  again and again inside the loop, but problem occurs when the thread is executing at background by that loop completes its execution, we get unexpected exceptions.

    i too faced this probs, after struggling a lot i got the solution how to effectively use threads inside loop. so thought of posting to help others.

    as in my previous blog i wrote how to create a thread How to create a Background running thread

    suppose i had this thread that i want to call again inside loop.


    Thread thread = new Thread(new ThreadStart(WorkThreadFunction));


    now inside loop


    for(int i = 0;i<10;i++)
       {   
         thread = new Thread(new ThreadStart(WorkThreadFunction));
             thread.IsBackground = true;
              thread.Start();
    //now here i will use wait handle that will check that the previous process is alive or dead(means completed its execution or not)
    
            WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) };
            while ( thread.IsAlive)
            {
                WaitHandle.WaitAny(AWait, 50, false);
                System.Windows.Forms.Application.DoEvents();
            } 
        }


    if the thread is alive the loop will not move  the next item as while condition will be true everytime until thread is alive. and you can perform your form events and your GUI will not hang..

    hope this helps ....

    post your valuable comments





    How to create a Background running thread ?




    This example shows how to create a new thread in .NET Framework. First, create a newThreadStart delegate. The delegate points to a method that will be executed by the new thread. Pass this delegate as a parameter when creating a new Thread instance. Finally, call the Thread.Start method to run your method (in this case WorkThreadFunction) on background.
    [C#]
    using System.Threading;
    
    Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
    thread.IsBackground = true;
    thread.Name = "xyz";
    thread.Start();
    
    
    by making the background property to true.. is thread will start working backgroung and you GUI will not be effected.
    The WorkThreadFunction could be defined as follows.
    [C#]
    public void WorkThreadFunction()
    {
      try
      {
        // do any background work
      }
      catch (Exception ex)
      {
        // log errors
      }
    }

    Friday, 10 May 2013

    How To Open Elevated Command Prompt In Windows 7?


    How To Open Elevated Command Prompt In Windows 7?

    Do you know how to open an elevated command prompt in Windows 7? If you don’t, then read on to find out what an elevated command prompt is.
    How to run elevated command prompt in Windows 7

    An elevated command prompt is a command prompt that you run with administrator privileges. So, basically it allows you to run all the important system commands. It’s important to know the difference between a normal command prompt and an elevated, because with a normal command prompt you won’t be able to run many commands successfully.
    1. Click on Start and enter cmd.exe in to the big search field. Then right-click on the entry above and select “Run as administrator”:
    Open elevated command prompt Windows 7
    By clicking on “run as administrator” you are running it with administrator privileges, so you are opening an elevated command prompt rater than a normal command prompt.
    2. You can now enter your commands into the elevated command prompt:
    Elevated Command Prompt

    When do I need an elevated command prompt?

    You can always need an elevated command prompt when you have need admin privileges. If you want to replace the system files in Windows 7 for example you will need admin privileges or it won’t work at all!
    There are many other situations when you will have to run an elevated command prompt in Windows 7. Hint: you better bookmark this if you can’t remember it.

    How To Unregister DLL In Windows 7


    How To Unregister DLL In Windows 7

    We have previously registered DLL files in Windows 7, but I did not exactly give away how to unregister DLL files in Windows 7. So, let’s take a look at that!
    How to unregister DLL files in Windows 7

    As you might remember, to register a DLL file you only need to know the command regsvr32 and the name of the DLL file. Now there’s a command line option to unregister DLL files. Here’s an example:
    Register DLL file:
    regsvr32 shell32.dll
    Unregister DLL file: 
    regsvr32 /u shell32.dll
    As you can see, it’s really easy and should be doable by anyone. Simply open up anelevated command prompt and run the command, using the name of the DLL file that you want to unregister.
    Unregister DLL via Command Prompt
    This is of course only an example, you should not unregister important system DLL’s if you don’t really know why. It can sometimes help to solve system problems to unregister and then re-register a DLL file, but should only be considered when other steps fail.

    How To Register DLL Files In Windows 7


    How To Register DLL Files In Windows 7

    If you want to know how to register DLL files in Windows 7, read this quick guide that will teach you the basics.
    Register DLL files

    Registering DLL files is quite simple, all you need to know is the command to register DLL files and the name of the DLL file that you want to register.
    The command to register the files manually is called regsvr32. Now let’s take a quick look at the syntax of regsvr32:
    /u Used to unregister DLL files
    /s If you don’t want any dialogs you can use the “s” for silent option
    /c Get the console output
    /n Register DLL file without DllRegisterServer
    /i Register DLL file with DllInstall (or DllUninstall if /u is specified)
    With option /i you can pass an optional command via /i:cmdline.
    DllInstall is used only for application installation and setup.

    Manually Register DLL files via Command Prompt

    So, to register DLL files, simply open up an elevated command prompt and run commands like:
    regsvr32 shell32.dll
    regsvr32 shdocvw.dll
    If you successfully re-register a DLL file, you should get a message like this one:
    DllRegisterServer in shell32.dll succeeded.
    RegSVR32 - Register DLL files
    Re-registering a DLL file manually can often help to solve problems, so you might want to look into it if you have problems with DLL files. As you can see from the command line option above, you can also unregister DLL files.