Saturday, 9 November 2013

Redirect from HTTP to HTTPS using Error Pages - ASP.Net

In this article we are going to handle the redirection of Http request to Https by using a error pages. when an error raised due to 403.4 code our error page is called , in that htm we are creating a redirect function in javascript which redirect to the secured site.To do this follow the simple steps

1 . Enable the RequireSSl in SSL settings for web application in IIS.
2. create a Intermediate HTM error page.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Redirect to Https</title>
    <script type="text/javascript" language="javascript">
        function HttpToHttps() {

            var https = window.location.hostname + window.location.pathname;
            https = "https://" + https;
            window.location = https;
        }
        HttpToHttps();
    </script>
</head>
<body>
</body>
</html>


 3. Configure the IIS for error handling click the IIS server and select the Error Pages icon then Add a new status code by click the Add button Then mention the status code as 403.4 and give the error handle htm path in file path. Now click the Edit feature settings and select the custom error pages and select the file path for handle the error 403.4. Now the redirect will happen from http to https.

From this article you can learn how to do the redirection from http to https using error pages 

ASP.Net - Redirect Http to Https protocol

In this article we are going to see how to redirect a link from HTTP request to HTTPS, To do that we have to do the SSL by Server Certificate which can be issued certificate authority. For this article we are going to create a self signed certificate for testing purpose .Then we need the  Url-Rewrite extension for IIS to rewrite the Url.

Whenever a User clicks the normal url like the first mention in the below image it automatically redirects to the HTTPS for secure mode. which is shown in second url image. Let we take a Login page as Demo page.

What is HTTPS ?
  A secured transaction of encrypted messages between the browser client and Server through wire.To do this encryption it takes the server certificate, Which have a one private key as well as an public key.uses a same key for encryption and decryption.




URL REWRITE : Click Here to download the extension

After download the Url Rewrite install it , then now you can add the rule for rewrite the URL in root  web.config file in project as well as in  IIS.

Steps to create a Self Signed Certificate :

1. windows + R to start the Run
2. Type inetmgr
3. now select the default website and add the bindings of https which have the default port of 443.
4. Launch the Url with Https and check the login page is launch in https mode.




Now if you try this in normal http url mode result in error 

HTTP Error 403.4 - Forbidden

The page you are trying to access is secured with Secure Sockets Layer (SSL).


url :  http://localhost/SSLSamples/. so how we can redirect it to https when even a user enter the url in http mode.To do that follow the simple steps mention below

1. uncheck the "RequireSSL" which is present under the ssl settings.
2. Create a Rule in Web.Config.

Here match tag specifies that any url comes action specifies the redirect to https with concate incoming HTTP_HOST and REQUEST_URI


<system.webServer>
    <httpRedirect enabled="false" destination="" httpResponseStatus="Found" />
    <rewrite>
      <rules>
        <rule name="Http to Https" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" />
          </conditions>
       <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>



Now if you launch the URL in HTTP it rewrites the URL to HTTPS.



From this article you can learn how make a redirect from http to https.


Thursday, 7 November 2013

WPF - Dependency Object and Data Binding

In this article we are going to see the Dependency object and the Data binding in WPF.So first create a class name with Employee and derive it from Dependency object , then give five properties FirstName, LastName, Address, Domain, Version. Now give a static value and attach in stack panel resource and bind the data to the textblock present in the Stack Panel.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfApplication1
{
    class Employee:DependencyObject
    {

        public static DependencyProperty FirstNameProperty = DependencyProperty.Register("FirstName", typeof(string), typeof(Employee));
        public string FirstName
        {
            set { SetValue(FirstNameProperty, value); }
            get { return (string)GetValue(FirstNameProperty); }
        }

        public static DependencyProperty LastNameProperty = DependencyProperty.Register("LastName", typeof(string), typeof(Employee));
        public string LastName
        {
            set { SetValue(LastNameProperty, value); }
            get { return (string)GetValue(LastNameProperty); }
        }

        public static DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(string), typeof(Employee));
        public string Address
        {
            set { SetValue(AddressProperty, value); }
            get { return (string)GetValue(AddressProperty); }
        }

        public static DependencyProperty DomainProperty = DependencyProperty.Register("Domain", typeof(string), typeof(Employee));
        public string Domain
        {
            set { SetValue(DomainProperty, value); }
            get { return (string)GetValue(DomainProperty); }
        }

        public static DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(Int32), typeof(Employee));
        public int Version
        {
            set { SetValue(VersionProperty, value); }
            get { return (int)GetValue(VersionProperty); }
        }

    }
}



<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Dependency Object" Height="184" Width="300" Background="CornflowerBlue">
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Name="Emp" Orientation="Vertical">
            <StackPanel.Resources>
                <local:Employee x:Key="empval" FirstName="Rajesh" LastName="G" Address="Porur" Domain="Dotnet" Version="4" />                                   
            </StackPanel.Resources>
            <TextBlock Foreground="Brown"  Text="{Binding FirstName}"/>
            <TextBlock Foreground="Brown" Text="{Binding LastName}"/>
            <TextBlock Foreground="Brown" Text="{Binding Address}"/>
            <TextBlock Foreground="Brown" Text="{Binding Domain}"/>
            <TextBlock Foreground="Brown" Text="{Binding Version}"/>
            <StackPanel.DataContext>
                <Binding Source="{StaticResource empval}" />
            </StackPanel.DataContext>
        </StackPanel>
    </Grid>
</Window>


Output :



From this article you can see the basics of Data binding and Dependency object.










Virtual Human - Speaking the Text written in Notepad C#

In this article we are going to see how to make a text to speech in computer using the speech synthesizer in C#.

Virtual HumanClick here to download EXE

Browse the text file or type the text in textbox then hit speak button , system starts to speak ur content in your preferred voice mode male or female voice by the selection of radio button.

If you want to save the speech as wav you can save the speech by hit save , save options only enable when you stop the speech

Output:

Load the Text File.


Save the audio by hit save.

Code :

         SpeechSynthesizer speak = new SpeechSynthesizer();
         speak.Volume = 100;
         //speak.Rate = 5
         if(radioButton1.Checked)
             speak.SelectVoiceByHints(VoiceGender.Male);
         else if(radioButton2.Checked)                          
              speak.SelectVoiceByHints(VoiceGender.Female);
         else
             speak.SelectVoiceByHints(VoiceGender.Neutral);
               

           speak.SpeakAsync(Content.Text);

I Hope this article will give you detailed about speech class in c#.

Wednesday, 6 November 2013

Make a Pendrive as Bootable Device

In this article we are going to see how to create a Bootable pendrive for Boot Windows 7 OS. Some time you were need this stuff,so note down the steps how to make a bootable pendrive for windows 7. Instead of booting Windows 7 OS from DVD we can make a boot from Pendrive. So to do this have a pendrive with or more than 4 GB

Following the Below Steps to make a pendrive bootable. Now Plugin the pendrive in your computer.

  •  Press Windows + R to get the Run (or) go to start up and type run and Enter.
  •  Now Type CMD in Run , and hit Ctrl + Shift + Enter.
  •  Next Type  DISKPART in command Window and ENTER
  •  Next Type  LISTDISK  
  • Type Select DISK 1  (Select Pendrive Disk as number )
  • Next Type CLEAN and Enter wait for few seconds.
  • Type CREATE PARTITION PRIMARY and press enter.
  • Type SELECT PARTITION 1 and Press enter.
  • Type ACTIVE and press enter
  • Type FORMAT FS=NTFS
     close the window 

Now my DVD drive is D:  and Pendrive is  H: , Type the following thing in the CMD window.Now load the windows 7 dvd 

Type CD "your dvd drive letter:\" and press enter. Ex: CD D:\ in cmd window
now it seems like follows in cmd windows for my dvd drive D:\. Now cmd window rediects to D drive.

Type D:\CD BOOT press enter.
Type BOOTSECT.EXE /NT60 H:   

Here H: refers pendrive, now copy the full setup of windows 7 to pendrive and boot it .







Tuesday, 5 November 2013

USB Detector - C#

In this post i am going to explain some more interesting thing, USB Detector so this article deals with create a application for detect the USB when inserted and removed from computer and make a notification to user on removal

USB DetectorClick Here To Download



Launch the application after the download, Then plug in the USB device in the computer now you will see a device add in the application and select a Notify checkbox to notify the user when it is try to remove





Now we see how to do this application.

USBDetector:

public class USBDetector : IDisposable
    {
     
     
        public event USBDetectorEventHandler DeviceArrived;
        public event USBDetectorEventHandler DeviceRemoved;
        public event USBDetectorEventHandler QueryRemove;

        public USBDetector()
        {
            DriveForm frm = new DriveForm(this);
            frm.Show();
            Init(frm, null);
        }

        public USBDetector(Control control)
        {
            Init(control, null);
        }

       
        public USBDetector(Control control, string FileToOpen)
        {
            Init(control, FileToOpen);
        }

       
        private void Init(Control control, string fileToOpen)
        {
            mFileToOpen = fileToOpen;
            mFileOnFlash = null;
            mDeviceNotifyHandle = IntPtr.Zero;
            mRecipientHandle = control.Handle;
            mDirHandle = IntPtr.Zero;  
            mCurrentDrive = "";
        }

       
        public bool IsQueryHooked
        {
            get
            {
                if (mDeviceNotifyHandle == IntPtr.Zero)
                    return false;
                else
                    return true;
            }
        }

      
        public string HookedDrive
        {
            get
            {
                return mCurrentDrive;
            }
        }

       
        public FileStream OpenedFile
        {
            get
            {
                return mFileOnFlash;
            }
        }

       
        public bool EnableQueryRemove(string fileOnDrive)
        {
            if (fileOnDrive == null || fileOnDrive.Length == 0)
                throw new ArgumentException("Drive path must be supplied to register for Query remove.");

            if (fileOnDrive.Length == 2 && fileOnDrive[1] == ':')
                fileOnDrive += '\\';        // append "\\" if only drive letter with ":" was passed in.

            if (mDeviceNotifyHandle != IntPtr.Zero)
            {
                // Unregister first...
                RegisterForDeviceChange(false, null);
            }

            if (Path.GetFileName(fileOnDrive).Length == 0 || !File.Exists(fileOnDrive))
                mFileToOpen = null;     // use root directory...
            else
                mFileToOpen = fileOnDrive;

            RegisterQuery(Path.GetPathRoot(fileOnDrive));
            if (mDeviceNotifyHandle == IntPtr.Zero)
                return false;   // failed to register

            return true;
        }

      
        public void DisableQueryRemove()
        {
            if (mDeviceNotifyHandle != IntPtr.Zero)
            {
                RegisterForDeviceChange(false, null);
            }
        }

     
        public void Dispose()
        {
            RegisterForDeviceChange(false, null);
        }


        #region WindowProc
      
        public void WndProc(ref Message m)
        {
            int devType;
            char c;

            if (m.Msg == WM_DEVICECHANGE)
            {
               
                switch (m.WParam.ToInt32())
                {

                  
                    case DBT_DEVICEARRIVAL:

                        devType = Marshal.ReadInt32(m.LParam, 4);
                        if (devType == DBT_DEVTYP_VOLUME)
                        {
                            DEV_BROADCAST_VOLUME vol;
                            vol = (DEV_BROADCAST_VOLUME)
                                Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                            
                            c = DriveMaskToLetter(vol.dbcv_unitmask);                         
                            USBDetectorEventHandler tempDeviceArrived = DeviceArrived;
                            if (tempDeviceArrived != null)
                            {
                                USBDetectorEventArgs e = new USBDetectorEventArgs();
                                e.Drive = c + ":\\";
                                tempDeviceArrived(this, e);

                                // Register for query remove if requested
                                if (e.HookQueryRemove)
                                {
                                    // If something is already hooked, unhook it now
                                    if (mDeviceNotifyHandle != IntPtr.Zero)
                                    {
                                        RegisterForDeviceChange(false, null);
                                    }

                                    RegisterQuery(c + ":\\");
                                }
                            }     // if  has event handler


                        }
                        break;

                  
                    case DBT_DEVICEQUERYREMOVE:

                        devType = Marshal.ReadInt32(m.LParam, 4);
                        if (devType == DBT_DEVTYP_HANDLE)
                        {                         
                            USBDetectorEventHandler tempQuery = QueryRemove;
                            if (tempQuery != null)
                            {
                                USBDetectorEventArgs e = new USBDetectorEventArgs();
                                e.Drive = mCurrentDrive;        // drive which is hooked
                                tempQuery(this, e);

                                // If the client wants to cancel, let Windows know
                                if (e.Cancel)
                                {
                                    m.Result = (IntPtr)BROADCAST_QUERY_DENY;
                                }
                                else
                                {                                   
                                    RegisterForDeviceChange(false, null);   // will also close the mFileOnFlash
                                }

                            }
                        }
                        break;


                    //
                    // Device has been removed
                    //
                    case DBT_DEVICEREMOVECOMPLETE:

                        devType = Marshal.ReadInt32(m.LParam, 4);
                        if (devType == DBT_DEVTYP_VOLUME)
                        {
                            devType = Marshal.ReadInt32(m.LParam, 4);
                            if (devType == DBT_DEVTYP_VOLUME)
                            {
                                DEV_BROADCAST_VOLUME vol;
                                vol = (DEV_BROADCAST_VOLUME)
                                    Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                                c = DriveMaskToLetter(vol.dbcv_unitmask);

                                //
                                // Call the client event handler
                                //
                                USBDetectorEventHandler tempDeviceRemoved = DeviceRemoved;
                                if (tempDeviceRemoved != null)
                                {
                                    USBDetectorEventArgs e = new USBDetectorEventArgs();
                                    e.Drive = c + ":\\";
                                    tempDeviceRemoved(this, e);
                                }
                               
                            }
                        }
                        break;
                }

            }

        }
        #endregion

        #region  Private Area

     
        private IntPtr mDirHandle = IntPtr.Zero;
     
        private FileStream mFileOnFlash = null;

        private string mFileToOpen;
       
        private IntPtr mDeviceNotifyHandle;

        private IntPtr mRecipientHandle;

        private string mCurrentDrive;

        private const int DBT_DEVTYP_DEVICEINTERFACE = 5;
        private const int DBT_DEVTYP_HANDLE = 6;
        private const int BROADCAST_QUERY_DENY = 0x424D5144;
        private const int WM_DEVICECHANGE = 0x0219;
        private const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device
        private const int DBT_DEVICEQUERYREMOVE = 0x8001;   // Preparing to remove (any program can disable the removal)
        private const int DBT_DEVICEREMOVECOMPLETE = 0x8004; // removed
        private const int DBT_DEVTYP_VOLUME = 0x00000002; // drive type is logical volume

        private void RegisterQuery(string drive)
        {
            bool register = true;

            if (mFileToOpen == null)
            {
               
            }
            else
            {
              
                if (mFileToOpen.Contains(":"))
                {
                    string tmp = mFileToOpen.Substring(3);
                    string root = Path.GetPathRoot(drive);
                    mFileToOpen = Path.Combine(root, tmp);
                }
                else
                    mFileToOpen = Path.Combine(drive, mFileToOpen);
            }


            try
            {               
                if (mFileToOpen == null// open root directory
                    mFileOnFlash = null;
                else
                    mFileOnFlash = new FileStream(mFileToOpen, FileMode.Open);
            }
            catch (Exception)
            {
                // just do not register if the file could not be opened
                register = false;
            }


            if (register)
            {
              
                if (mFileOnFlash == null)
                    RegisterForDeviceChange(drive);
                else
                    // old version
                    RegisterForDeviceChange(true, mFileOnFlash.SafeFileHandle);

                mCurrentDrive = drive;
            }


        }


        private void RegisterForDeviceChange(string dirPath)
        {
            IntPtr handle = Native.OpenDirectory(dirPath);
            if (handle == IntPtr.Zero)
            {
                mDeviceNotifyHandle = IntPtr.Zero;
                return;
            }
            else
                mDirHandle = handle;    // save handle for closing it when unregistering

            // Register for handle
            DEV_BROADCAST_HANDLE data = new DEV_BROADCAST_HANDLE();
            data.dbch_devicetype = DBT_DEVTYP_HANDLE;
            data.dbch_reserved = 0;
            data.dbch_nameoffset = 0;
            //data.dbch_data = null;
            //data.dbch_eventguid = 0;
            data.dbch_handle = handle;
            data.dbch_hdevnotify = (IntPtr)0;
            int size = Marshal.SizeOf(data);
            data.dbch_size = size;
            IntPtr buffer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(data, buffer, true);

            mDeviceNotifyHandle = Native.RegisterDeviceNotification(mRecipientHandle, buffer, 0);

        }

      
        private void RegisterForDeviceChange(bool register, SafeFileHandle fileHandle)
        {
            if (register)
            {
                // Register for handle
                DEV_BROADCAST_HANDLE data = new DEV_BROADCAST_HANDLE();
                data.dbch_devicetype = DBT_DEVTYP_HANDLE;
                data.dbch_reserved = 0;
                data.dbch_nameoffset = 0;
                //data.dbch_data = null;
                //data.dbch_eventguid = 0;
                data.dbch_handle = fileHandle.DangerousGetHandle(); //Marshal. fileHandle;
                data.dbch_hdevnotify = (IntPtr)0;
                int size = Marshal.SizeOf(data);
                data.dbch_size = size;
                IntPtr buffer = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(data, buffer, true);

                mDeviceNotifyHandle = Native.RegisterDeviceNotification(mRecipientHandle, buffer, 0);
            }
            else
            {
                // close the directory handle
                if (mDirHandle != IntPtr.Zero)
                {
                    Native.CloseDirectoryHandle(mDirHandle);
                    //    string er = Marshal.GetLastWin32Error().ToString();
                }

                // unregister
                if (mDeviceNotifyHandle != IntPtr.Zero)
                {
                    Native.UnregisterDeviceNotification(mDeviceNotifyHandle);
                }


                mDeviceNotifyHandle = IntPtr.Zero;
                mDirHandle = IntPtr.Zero;

                mCurrentDrive = "";
                if (mFileOnFlash != null)
                {
                    mFileOnFlash.Close();
                    mFileOnFlash = null;
                }
            }

        }

        private static char DriveMaskToLetter(int mask)
        {
            char letter;
            string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            // 1 = A
            // 2 = B
            // 4 = C...
            int cnt = 0;
            int pom = mask / 2;
            while (pom != 0)
            {
                // while there is any bit set in the mask
                // shift it to the righ...               
                pom = pom / 2;
                cnt++;
            }

            if (cnt < drives.Length)
                letter = drives[cnt];
            else
                letter = '?';

            return letter;
        }

        #endregion

        #region Native Win32 API
        /// <summary>
        /// WinAPI functions
        /// </summary>       
        private class Native
        {
            //   HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient,LPVOID NotificationFilter,DWORD Flags);
            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, uint Flags);

            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            public static extern uint UnregisterDeviceNotification(IntPtr hHandle);

            //
            // CreateFile  - MSDN
            const uint GENERIC_READ = 0x80000000;
            const uint OPEN_EXISTING = 3;
            const uint FILE_SHARE_READ = 0x00000001;
            const uint FILE_SHARE_WRITE = 0x00000002;
            const uint FILE_ATTRIBUTE_NORMAL = 128;
            const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
            static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);


            // should be "static extern unsafe"
            [DllImport("kernel32", SetLastError = true)]
            static extern IntPtr CreateFile(
                  string FileName,                    // file name
                  uint DesiredAccess,                 // access mode
                  uint ShareMode,                     // share mode
                  uint SecurityAttributes,            // Security Attributes
                  uint CreationDisposition,           // how to create
                  uint FlagsAndAttributes,            // file attributes
                  int hTemplateFile                   // handle to template file
                  );


            [DllImport("kernel32", SetLastError = true)]
            static extern bool CloseHandle(
                  IntPtr hObject   // handle to object
                  );

            /// <summary>
            /// Opens a directory, returns it's handle or zero.
            /// </summary>
            /// <param name="dirPath">path to the directory, e.g. "C:\\dir"</param>
            /// <returns>handle to the directory. Close it with CloseHandle().</returns>
            static public IntPtr OpenDirectory(string dirPath)
            {
                // open the existing file for reading         
                IntPtr handle = CreateFile(
                      dirPath,
                      GENERIC_READ,
                      FILE_SHARE_READ | FILE_SHARE_WRITE,
                      0,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,
                      0);

                if (handle == INVALID_HANDLE_VALUE)
                    return IntPtr.Zero;
                else
                    return handle;
            }


            public static bool CloseDirectoryHandle(IntPtr handle)
            {
                return CloseHandle(handle);
            }
        }


        // Structure with information for RegisterDeviceNotification.
        [StructLayout(LayoutKind.Sequential)]
        public struct DEV_BROADCAST_HANDLE
        {
            public int dbch_size;
            public int dbch_devicetype;
            public int dbch_reserved;
            public IntPtr dbch_handle;
            public IntPtr dbch_hdevnotify;
            public Guid dbch_eventguid;
            public long dbch_nameoffset;
            //public byte[] dbch_data[1]; // = new byte[1];
            public byte dbch_data;
            public byte dbch_data1;
        }

        // Struct for parameters of the WM_DEVICECHANGE message
        [StructLayout(LayoutKind.Sequential)]
        public struct DEV_BROADCAST_VOLUME
        {
            public int dbcv_size;
            public int dbcv_devicetype;
            public int dbcv_reserved;
            public int dbcv_unitmask;
        }
        #endregion

    }



UsbDetectorEventArgs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace USB_Detector
{
    // Delegate for event handler to handle the device events
    public delegate void USBDetectorEventHandler(Object sender, USBDetectorEventArgs e);

    /// <summary>
    /// Our class for passing in custom arguments to our event handlers
    ///
    /// </summary>
    public class USBDetectorEventArgs : EventArgs
    {


        public USBDetectorEventArgs()
        {
            Cancel = false;
            Drive = "";
            HookQueryRemove = false;
        }

        /// <summary>
        /// Get/Set the value indicating that the event should be cancelled
        /// Only in QueryRemove handler.
        /// </summary>
        public bool Cancel;

        /// <summary>
        /// Drive letter for the device which caused this event
        /// </summary>
        public string Drive;

        /// <summary>
        /// Set to true in your DeviceArrived event handler if you wish to receive the
        /// QueryRemove event for this drive.
        /// </summary>
        public bool HookQueryRemove;

    }

}


Now create a Form which is invisble at runtime because we need a WndProc to get the Notification from the Native OS.

public partial class DriveForm : Form
    {
        public DriveForm()
        {
           
        }


         private Label label1;
        private USBDetector mDetector = null;

        /// <summary>
        /// Set up the hidden form.
        /// </summary>
        /// <param name="detector">DriveDetector object which will receive notification about USB drives, see WndProc</param>
        public DriveForm(USBDetector detector)
        {

            mDetector = detector;
            this.MinimizeBox = false;
            this.MaximizeBox = false;
            this.ShowInTaskbar = false;
            this.ShowIcon = false;
            this.FormBorderStyle = FormBorderStyle.None;
            this.Load += new System.EventHandler(this.Load_Form);
            this.Activated += new EventHandler(this.Form_Activated);
        }



        /// <summary>
        /// This function receives all the windows messages for this window (form).
        /// We call the DriveDetector from here so that is can pick up the messages about
        /// drives arrived and removed.
        /// </summary>
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (mDetector != null)
            {
                mDetector.WndProc(ref m);
            }
        }

        private void Load_Form(object sender, EventArgs e)
        {
            InitializeComponent();
            this.Size = new System.Drawing.Size(5, 5);
        }

        private void Form_Activated(object sender, EventArgs e)
        {
            this.Visible = false;
        }

       
    }


From this article you will get some interesting tool to get notify for portable devices plug in computer.