Tuesday, 15 November 2016

How to host WCF service in IIS manager

To host the WCF service, follow the below steps:
  1. Add virtual directory in "IIS Manager"
    1. PC Name -> Sites -> Default Web Site -> Add virtual directory
    2. Type in the alias (name) and browse to the physical path (where .svc file resides).
  2. Right click on the added application, select "Convert to application".
  3. Test the hosted application by clicking the "Browse button".

Possible issues:
  1. HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
Solution:
Turn on/off windows features: Make sure that the below features are turned on:
  • .net framework 3.5 and 4.5.
  • IIS


  1. If you can't access WCF service hosted on IIS remotely but can access it locally
Solution: 
Make sure firewall on the hosted machine is OFF.

Wednesday, 28 September 2016

How to Enable, Disable and Start the task of task scheduler in C#.Net

Below function demonstrates how to enable, disable and run the already created scheduled task. It will first check if the task exists in task scheduler:

public static void updateUserTaskInScheduler(string action)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe";
                startInfo.Arguments = "/C schtasks /query /TN <<TaskNameWithQuotes>>; //Check if task exists
                startInfo.RedirectStandardOutput = true;
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                if (System.Environment.OSVersion.Version.Major < 6)
                {
                    startInfo.Verb = "runas";
                }
                using (Process process = Process.Start(startInfo))
                {
                    // Read in all the text from the process with the StreamReader.
                    using (StreamReader reader = process.StandardOutput)
                    {
                        string stdout = reader.ReadToEnd();
                        if (stdout.Contains("<<TaskName>>")) //If task exists
                        {
                            startInfo.RedirectStandardOutput = false;
                            startInfo.UseShellExecute = true;
                            switch (action)
                            {
                                case "Enable":
                                    startInfo.Arguments = "/C schtasks /Change /TN <<TaskNameWithQuotes>>  /Enable";
                                    break;

                                case "Disable":
                                    startInfo.Arguments = "/C schtasks /Change /TN <<TaskNameWithQuotes>> /Disable";
                                    break;

                                case "Run":
                                    startInfo.Arguments = "/C schtasks /RUN /TN <<TaskNameWithQuotes>> ";
                                    break;
                            }
                            Process.Start(startInfo).WaitForExit();
                        }
                        else
                        {
                             //Task doesnot exist
                        }
                        stdout = null;
                        reader.Close();
                        reader.Dispose();
                    }
                }
                startInfo = null;
            }
            catch (Exception ex)
            {
                    MessageBox.Show(ex.Message);
            }
        }


The above function can be called in the below manner:

1. To run the task:
            updateUserTaskInScheduler("Run");

2. To enable the task:
            updateUserTaskInScheduler("Enable");

3. To disable the task:
            updateUserTaskInScheduler("Disable");

Friday, 26 August 2016

How to load registry hive of logged off users in C#.Net

In HKEY_USERS, SIDs of only logged in users are present by default. If you need to make changes in any user's registry in logged off state, you will have to load the registry hive of that particular user.

Registry hive can be loaded by using NTUser.dat file loacted in "C:\Users\{Username}". {Username} is the name of the logged off user.

Following is the sample code required for this task:

 internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));

[DllImport("advapi32.dll", SetLastError = true)]
static extern Int32 RegLoadKey(IntPtr hKey, string lpSubKey, string lpFile);

Create a below function:

 public static void loadUserRegistryHive(string username, string keyName)
        {
            try
            {
                string path ="C:\Users\{Username}\NTUSER.DAT";
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    int retVal = RegLoadKey(HKEY_USERS, keyName, path);
                    if (retVal  == 0)
                            MessageBox.Show("Success");
                    else
                            MessageBox.Show("Failure");                  
                }
                else
                {
                    MessageBox.Show("NTUSER.DAT file does not exist in path");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

General Exception:

While using RegLoadKey in the above function, you may get 1314 as the return value. This is the indication that you don't have the necessary privileges to load the registry hive. To do so, use the below code:

public static void adjustPriviledge()
        {
            try
            {
                // Access token handle reused within the using block.
                using (AccessTokenHandle accessTokenHandle =
                    Process.GetCurrentProcess().GetAccessTokenHandle(
                        TokenAccessRights.AdjustPrivileges | TokenAccessRights.Query))
                {
                    // Enable privileges using the same access token handle.
                    AdjustPrivilegeResult backupResult = accessTokenHandle.EnablePrivilege(Privilege.Backup);
                    AdjustPrivilegeResult restoreResult = accessTokenHandle.EnablePrivilege(Privilege.Restore);
                }
            }
            catch (Exception ex)
            {
                      MessageBox.Show(ex.Message);
            }
        }

The above function will add the SE_BACKUP_NAME and SE_RESTORE_NAME privileges required to load the registry hive.

To use the function above you will have to include the below dll:
ProcessPrivileges.dll

You can download it from here:
https://processprivileges.codeplex.com/

It's an open source dll:
License details: https://processprivileges.codeplex.com/license

You will have to call function "adjustPriviledge" in function "loadUserRegistryHive" just before calling function "RegLoadKey" as shown below:

 adjustPriviledge();
 int retVal = RegLoadKey(HKEY_USERS, keyName, path);

Wednesday, 4 May 2016

How to clear clipboard text using C#.Net

Known exceptions:

Case 1:
It you use Clipboard.SetText(string.Empty) to clear clipboard text, you will get an ArgumentNullException exception: "Value cannot be NULL".

It is because you cannot set empty string or null using Clipboard.SetText function.

Case 2:
If you use Clipboard.Clear() function, you will get the below error:

"An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll

Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."

To fix the above 2 exceptions, use the following code:

 public void deleteClipboardText()
        {
            try
            {
                Thread th = new Thread(new ThreadStart(clearClipboardText));
                th.SetApartmentState(ApartmentState.STA);
                th.Start();
                th.Join();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void clearClipboardText()
        {
            System.Windows.Forms.Clipboard.Clear();
        }

Friday, 29 April 2016

How to get Clipboard data and its size in C#.Net

Following function will get the clipboard data:

        [DllImport("user32.dll")]
        static extern IntPtr GetClipboardData(uint uFormat);
        [DllImport("user32.dll")]
        static extern bool IsClipboardFormatAvailable(uint format);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool OpenClipboard(IntPtr hWndNewOwner);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool CloseClipboard();
        [DllImport("kernel32.dll")]
        static extern IntPtr GlobalLock(IntPtr hMem);
        [DllImport("kernel32.dll")]
        static extern bool GlobalUnlock(IntPtr hMem);

        const uint CF_UNICODETEXT = 13;
        public static string GetText()
        {
            if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
                return null;
            if (!OpenClipboard(IntPtr.Zero))
                return null;

            string data = null;
            var hGlobal = GetClipboardData(CF_UNICODETEXT);
            if (hGlobal != IntPtr.Zero)
            {
                var lpwcstr = GlobalLock(hGlobal);
                if (lpwcstr != IntPtr.Zero)
                {
                    data = Marshal.PtrToStringUni(lpwcstr);
                    GlobalUnlock(lpwcstr);
                }
            }
            CloseClipboard();

            return data;
        }


In order to get the size of clipboard text, you would need to copy the text in a file and then get the size of file as shown in the below code:

public long getClipboardTextSize()
        {
                string text = GetText();
                System.IO.File.WriteAllText("C:\\ClipboardText.txt", text);
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    return fi.Length;
                }
                else
                {
                    return 0;
                }
            }
        }

Thursday, 28 April 2016

Get startup programs of all users using C#.Net

The below code will demonstrate how to list all the startup programs (also listed in msconfig) using C#.Net.

A custom class (cStartupPrograms) is added to store a startup program and it's relevant properties.

 public class cStartupPrograms
    {
        public int StartupProgramId { get; set; }
        public int ComputerId { get; set; }
        public int StartupClassificationId { get; set; }
        public string StartupClassificationName { get; set; }
        public string ProgramName { get; set; }
        public string ProgramPath { get; set; }
        public bool? IsEnabled { get; set; }
        public bool? IsDeleted { get; set; }
        public string StartupType { get; set; }
        public string Publisher { get; set; }
        public string startupUserName { get; set; }
}

Below are the locations from where the startup programs are retrieved:

public static List<string> startupProgramsRegistryNames_Enabled = new List<string>()
        {
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", //HKLM, HKCU
            @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run",  //HKLM
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
        };

        public static List<string> startupProgramsRegistryNames_Disabled = new List<string>()
        {
            @"SOFTWARE\Microsoft\Shared Tools\MSConfig\startupfolder",  //HKLM
            @"SOFTWARE\Microsoft\Shared Tools\MSConfig\startupreg"  //HKLM          
        };

        public static List<string> startupProgramsRegistryNames_Enabled_OtherUsers = new List<string>()
        {
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", //HKEY_USERS
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
        };

        public static string startupProgramPath = @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup";


Below function will retrieve the list of startup program of all users:
private void getAllStartupPrograms()
        {
            List<cStartupPrograms> cStartupProgramList = null;

            RegistryInfo rInfo1 = new RegistryInfo();
            rInfo1.registryKey = Registry.CurrentUser;

            RegistryInfo rInfo2 = new RegistryInfo();
            rInfo2.registryKey = Registry.LocalMachine;

            List<RegistryInfo> rInfoList = new List<RegistryInfo>();
            rInfoList.Add(rInfo1);
            rInfoList.Add(rInfo2);

            try
            {
                cStartupProgramList = new List<cStartupPrograms>();
                //Enabled programs
                //All users
                string[] files = Directory.GetFiles(startupProgramPath, "*");
                foreach (string fileName in files)
                {
                    if (File.Exists(fileName))
                    {
                        string target = GetShortcutTargetFile(fileName);
                        if (!String.IsNullOrEmpty(target))
                        {
                            cStartupPrograms startupProgram = new cStartupPrograms();

                            startupProgram.ComputerId = Convert.ToInt32(frmPreferences.ComputerId);
                            startupProgram.IsDeleted = false;
                            startupProgram.IsEnabled = true;
                            startupProgram.ProgramName = System.IO.Path.GetFileName(fileName);
                            startupProgram.ProgramPath = target;
                            startupProgram.StartupClassificationName = cEnum.eStartupClassification.Windows.ToString();
                            startupProgram.startupUserName = "All Users";
                            startupProgram.StartupType =startupProgramPath;
                           
                            //if (!cStartupProgramList.Exists(p => p.ProgramName == fileName && p.ProgramPath == target))
                            cStartupProgramList.Add(startupProgram);
                        }
                    }
                }

                //All users
                foreach (RegistryInfo rInfo in rInfoList)
                {
                    RegistryKey regKey = rInfo.registryKey;
                    foreach (string registryName in startupProgramsRegistryNames_Enabled)
                    {
                        string runOrRunOnceString = null;
                        int n = registryName.LastIndexOf("\\");
                        runOrRunOnceString = registryName.Substring(n + 1);
                        using (RegistryKey startupKey = regKey.OpenSubKey(registryName))
                        {
                            if (startupKey == null)
                                continue;

                            var valueNames = startupKey.GetValueNames();
                            foreach (var name in valueNames)
                            {
                                cStartupPrograms startupProgram = new .cStartupPrograms();

                                startupProgram.ComputerId = Convert.ToInt32(frmPreferences.ComputerId);
                                startupProgram.IsDeleted = false;
                                startupProgram.IsEnabled = true;
                                startupProgram.ProgramName = name;
                                startupProgram.ProgramPath = Convert.ToString(startupKey.GetValue(name));
                                startupProgram.StartupClassificationName = cEnum.eStartupClassification.Windows.ToString();
                                startupProgram.startupUserName = "All Users";
                                startupProgram.StartupType = startupKey.ToString();

                                //if (!cStartupProgramList.Exists(p => p.ProgramName == name && p.ProgramPath == startupProgram.ProgramPath))
                                cStartupProgramList.Add(startupProgram);
                            }
                        }
                    }
                }

                //Other users
                string[] hkeyUserNames = Registry.Users.GetSubKeyNames();
                foreach (string key in hkeyUserNames)
                {
                    string userName = GetOwnerName(key);
                    if (string.IsNullOrEmpty(userName))
                        continue;

                    RegistryKey startupKey = Registry.Users.OpenSubKey(key);
                    if (startupKey == null)
                        continue;

                    foreach (string registryName in startupProgramsRegistryNames_Enabled_OtherUsers)
                    {
                        string runOrRunOnceString = null;
                        int n = registryName.LastIndexOf("\\");
                        runOrRunOnceString = registryName.Substring(n + 1);

                        using (RegistryKey userKey = startupKey.OpenSubKey(registryName))
                        {
                            if (userKey == null)
                                continue;

                            var valueNames = userKey.GetValueNames();
                            foreach (var name in valueNames)
                            {
                                cStartupPrograms startupProgram = new cStartupPrograms();
                                startupProgram.ComputerId = Convert.ToInt32(frmPreferences.ComputerId);
                                startupProgram.IsDeleted = false;
                                startupProgram.IsEnabled = true;
                                startupProgram.ProgramName = name;
                                startupProgram.ProgramPath = Convert.ToString(userKey.GetValue(name));
                                startupProgram.StartupClassificationName = cEnum.eStartupClassification.Windows.ToString();
                                startupProgram.startupUserName = userName;
                                startupProgram.StartupType = userKey.ToString();
                                //if (!cStartupProgramList.Exists(p => p.ProgramName == name && p.ProgramPath == startupProgram.ProgramPath && p.startupUserName==userName))
                                cStartupProgramList.Add(startupProgram);
                            }
                        }
                    }
                }

                //Disabled programs
                foreach (string registryName in startupProgramsRegistryNames_Disabled)
                {
                    using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) //
                    {
                        using (RegistryKey startupkey = hklm.OpenSubKey(registryName))
                        {

                            if (startupkey == null)
                                continue;

                            foreach (string key in startupkey.GetSubKeyNames())
                            {
                                using (RegistryKey rk = startupkey.OpenSubKey(key))
                                {
                                    cStartupPrograms startupProgram = new cStartupPrograms();

                                    startupProgram.ComputerId = Convert.ToInt32(frmPreferences.ComputerId);
                                    startupProgram.IsDeleted = false;
                                    startupProgram.IsEnabled = false;
                                    startupProgram.ProgramName = Convert.ToString(rk.GetValue("item"));
                                    startupProgram.ProgramPath = Convert.ToString(rk.GetValue("command"));
                                    startupProgram.StartupClassificationName = cEnum.eStartupClassification.Windows.ToString();
                                    var hkeyVal = rk.GetValue("hkey");
                                    if (hkeyVal != null)
                                    {
                                        string keyVal = Convert.ToString(rk.GetValue("key"));
                                        string runOrRunOnceString = null;
                                        int n = keyVal.LastIndexOf("\\");
                                        runOrRunOnceString = keyVal.Substring(n + 1);

                                        if (hkeyVal.ToString() == "HKLM")
                                        {
                                            startupProgram.StartupType = Registry.LocalMachine.ToString() + "\\" + keyVal;
                                           
                                        }
                                        else if (hkeyVal.ToString() == "HKCU")
                                        {
                                            startupProgram.StartupType = Registry.CurrentUser.ToString() + "\\" + keyVal;
                                         
                                        }
                                    }
                                    else
                                    {
                                        startupProgram.StartupType = Convert.ToString(rk.GetValue("location"));
                                    }
                                    startupProgram.startupUserName = "All Users";
                                 
                                    //if (!cStartupProgramList.Exists(p => p.ProgramName == startupProgram.ProgramName && p.ProgramPath == startupProgram.ProgramPath))
                                    cStartupProgramList.Add(startupProgram);

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               
                return;
            }
        }

Wednesday, 13 April 2016

Convert content of XML file to JSON string in C#.Net

The below function will convert the content of XML file to JSON string:

private string convertXMLToJSON()
        {
            string xmlLogPath = "<<Path to the xml file>>";

            // Load the XML file
            var xDocument = System.Xml.Linq.XDocument.Load(xmlLogPath);

            // Read the XML file content and write it to string
            string xml = xDocument.ToString();

            // Load the XML string
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            // Convert the XML string to JSON string
            string jsonText = JsonConvert.SerializeXmlNode(doc);

            //Release the memory
            doc = null;
            xmlLogPath = null;
            xml = null;
            xDocument = null;
     
            //Return the JSON string
            return jsonText;

        }

IMPORTANT NOTE:

Releasing object memory is very important. Even if your object went out of scope, it is not removed from the garbage collection. It happens because the variable still has some value in it. So Garbage collector think that the variable is in use and it doesn't remove it from the memory.

Setting it to NULL, tells the garbage collector that the object is no longer in use and can be removed from the garbage collection.

Tuesday, 12 April 2016

Start and stop a console application using C#

Start a console application:


System.Diagnostics.Process aspProcess = null;
private void start_console_app()
        {
            try
            {
                string pathToExe = @"<<Path to the exe >> ";
                
                if (aspProcess == null)
                {
                    aspProcess = new System.Diagnostics.Process();
                }
                
                //Path and file name of command to run
                aspProcess.StartInfo.FileName = pathToExe;
                aspProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                //Parameters to pass to program
                aspProcess.StartInfo.Arguments = "<<arguments you want to pass>>";

                aspProcess.StartInfo.UseShellExecute = true;
                aspProcess.StartInfo.CreateNoWindow = true;

                //Start the process
                aspProcess.Start();

                //Wait for process to finish
                aspProcess.WaitForExit();
                aspProcess = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

1. For starting a console application, you would need to create an object of class "System.Diagnostics.Process".
2. "FileName" is the path of the exe (console application).
3.  "Arguments" - It will send arguments to your console application.
4.  ProcessWindowStyle.Hidden will hide the console window.
5. Start () method will start the process.

Stop a console application by sending "Control + C" Signal:


public void stop_console_app()
        {
            // Release the current console, as you cannot attach 2 consoles at the same time
            if (aspProcess != null)
            {
                uint pid = (uint)aspProcess.Id;
                FreeConsole();

                // This does not require the console window to be visible.
                if (AttachConsole(pid))
                {
                    // Disable Ctrl-C handling for our program
                    SetConsoleCtrlHandler(null, true);
                    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

                    // Must wait here. If we don't and re-enable Ctrl-C
                    // handling below too fast, we might terminate ourselves.
                    Thread.Sleep(2000);

                    FreeConsole();

                    // Re-enable Ctrl-C handling or any subsequently started
                    // programs will inherit the disabled state.
                    SetConsoleCtrlHandler(null, false);
                }
            }
        }

You can add "Console_CancelKeyPress" event in your console application to nicely terminate it. If you want to call this method from another application (from where you've started your console application), add the above method.

Thursday, 26 November 2015

How to make the Windows Desktop application work well on High-DPI Displays and Fix Blurry Fonts

If you change the DPI of your machine from 100% to any other higher value, your desktop applications may appear somewhat blurry when you compare them with other applications on the screen. Alternately, display problems may exist such as truncated text.



In order to fix this issue, you would need to Disable DPI virtualization for the application. To do this, right-click the application’s shortcut and then click Properties. On the Compatibility tab, select Disable Display Scaling on High DPI Settings, and then click OK.




Alternatively, you may also disable this setting using the below Registry keys.

Registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers

String: “Path to your application exe”
Value:   ~ HIGHDPIAWARE
Please note there is a space between ‘tilde’ and ‘HIGHDPIAWARE’.



There are number of ways to set a value in the registry. Below steps will show the process to set this value in registry using Inno setup:

var
str_MyAppFullExePath: String;

str_MyAppFullExePath := ExpandConstant('{app}') ;

RegWriteStringValue(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers', str_MyAppFullExePath + '\' + '{#MyAppExeName}' , '~ HIGHDPIAWARE');

Possible Issues:

If your application is 32 bit, then the above command will set the value at

“HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers” 

instead of 

“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers”. 

This will not set the “Disable Display Scaling on High DPI Settings” property. This can be fixed by using the below command:

if IsWin64 then
 begin
 RegWriteStringValue(HKLM64, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers', str_MyAppFullExePath + '\' + '{#MyAppExeName}' , '~ HIGHDPIAWARE');
 end
 else
 begin
 RegWriteStringValue(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers', str_MyAppFullExePath + '\' + '{#MyAppExeName}' , '~ HIGHDPIAWARE');
 end ;

It will force the setup to store value in 64 bit registry.

Monday, 23 November 2015

How to extract the associated icon of any file in C#.Net

To extract icon of any file, define the below class and the structure:

[StructLayout(LayoutKind.Sequential)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };


class Win32
        {
            public const uint SHGFI_ICON = 0x100;
            public const uint SHGFI_LARGEICON = 0x0;    // 'Large icon
            public const uint SHGFI_SMALLICON = 0x1;    // 'Small icon

            [DllImport("shell32.dll")]
            public static extern IntPtr SHGetFileInfo(string pszPath,
                                        uint dwFileAttributes,
                                        ref SHFILEINFO psfi,
                                        uint cbSizeFileInfo,
                                        uint uFlags);

            [DllImport("User32.dll")]
            public static extern int DestroyIcon(IntPtr hIcon);
        }

Now define the following function:

SHFILEINFO shinfo = new SHFILEINFO();
/* Define it globally so that you can use the same object for all  the files. */
public Bitmap extractAssociatedIcon(string fName)
        {
            Icon myIcon = null;
            try
            {
                IntPtr hImgSmall;    //the handle to the system image list              

                hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo,
                                 (uint)Marshal.SizeOf(shinfo),
                                  Win32.SHGFI_ICON |
                                  Win32.SHGFI_SMALLICON);

                if (shinfo.hIcon != IntPtr.Zero)
                    myIcon = Icon.FromHandle(shinfo.hIcon);              

            }
            catch (Exception ex)
            {
                // Handle any exception here
            }
            return myIcon.ToBitmap();
        }


Get the icon by calling the above defined function.

Bitmap image = extractAssociatedIcon("fullPath to the file");

Once you get the icon, make sure you destroy the icon. This is very important, else you will run into memory issues.

Win32.DestroyIcon(shinfo.hIcon);




Friday, 20 November 2015

Dealing with “Application has stopped responding” issue in C#.Net

Suppose in your application, on a click event you are doing some calculations which is taking a lot of time. During that time, if a user perform unnecessarily clicks on the screen, it might give a “Page is not responding” or "Application has stopped responding" error.

This can be resolved by following the below steps:

1.   Put your long running code in a thread.

2. Set “Cursor.Current = Cursors.WaitCursor;”

3. UseWaitCursor = true;

4. Inside the thread use the try-finally block.

5. In the finally block, set “this.Cursor = Cursors.Default;”

6. UseWaitCursor = false;

7. Start that thread.

Example:
     Cursor.Current = Cursors.WaitCursor;
     UseWaitCursor = true;

            new Thread(() =>
            {
     try
            {                             
                // Your long running code                                   
            }
            catch (Exception ex)
            {
                 // Handle any exception here
            }
            finally
            {                           
  Cursor.Current = Cursors.Default;
                UseWaitCursor = false;
            }
           }) { Name = "longTask" }.Start();


Now even if you click 100 times, the page will not show “Not Responding” error.

Wednesday, 18 November 2015

Adding a new item to context menu of Windows Explorer in C#.Net



Requirement: Whenever user right clicks on any folder in windows explorer, display a new option and if user selects that option, launch your application. The below steps will add a new option on right click of any folder:

You would need to add 2 sub keys in registry at the below location:

HKEY_CLASSES_ROOT\Folder\shell

Key 1: Folder\\shell\\MyProduct

Set the value of above key and the same will be shown in the context menu. You can also add a icon to the context menu item by adding a value to the key 1 and name it "Icon" as shown below:

Icon  "Path to your icon file"

Key 2: Folder\\shell\\MyProduct\\command

Set the value of above key and it will launch the application:

Eg. C:\Program Files (x86)\myProduct.exe "%1"

Here "%1" will give the path of the folder which is right clicked.



Programmatically this can be done as below:

private static void updateRegistryToAddContextMenu()
        {
            string MenuName = "Folder\\shell\\MyProduct";
            string Command = "Folder\\shell\MyProduct\\command";

            RegistryKey regmenu = null;
            RegistryKey regcmd = null;
            try
            {
                regmenu = Registry.ClassesRoot.CreateSubKey(MenuName);
                if (regmenu != null)
                    regmenu.SetValue("","New context menu option");
                regcmd = Registry.ClassesRoot.CreateSubKey(Command);
                if (regcmd != null)
                {
                    string exePath = Application.ExecutablePath;
                    regcmd.SetValue("", exePath + " " + "\"" + "%1" + "\"");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                if (regmenu != null)
                    regmenu.Close();
                if (regcmd != null)
                    regcmd.Close();
            }
        }

Thursday, 1 October 2015

Enumerate folder with “No Name” (blank space folder, AKA non-breaking space) in C#.Net:

A folder with no name can be created by following the below steps:
  1. Right-click on the folder and select Rename.
  2. Now press the Alt key and from the Numeric keypad, press 0160.
  3. Now press Enter or click anywhere on the desktop.


If you want to retrieve all the files and folders from any directory (in C#), you would do something like this:

string path = “Path to the directory”;
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dirInfo in di.GetDirectories())
{
       FileInfo[] fInfos = dirInfo.GetFiles();
       // You can easily iterate through the files here
}

But if you have any folder with a blank space as name, the above method would give you wrong result. You would need to make few changes as shown below:

string path = “Path to the directory” + “\\”;
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dirInfo in di.GetDirectories())
{
     if (dirInfo.Name == "\u00A0")
     {
          string fullPath = dirInfo.FullName + "\\";
          dirInfo = new DirectoryInfo(fullPath);
     } 

     FileInfo[] fInfos = dirInfo.GetFiles();
     // You can easily iterate through the files
}
  

Reduce flickering from controls in C#.Net

Flickering effect can be reduced by double buffering the controls. The below code will help you in reducing the flickering effect from any type of control.

public static class ControlExtensions
    {
        public static void SetDoubleBuffered(System.Windows.Forms.Control c)
        {
            if (System.Windows.Forms.SystemInformation.TerminalServerSession)
                return;

            System.Reflection.PropertyInfo aProp =
                  typeof(System.Windows.Forms.Control).GetProperty(
                        "DoubleBuffered",
                        System.Reflection.BindingFlags.NonPublic |
                        System.Reflection.BindingFlags.Instance);

            aProp.SetValue(c, true, null);
        }
    }

Whether it is a panel, or a Tab control, you can call the above defined function:

ControlExtensions.SetDoubleBuffered(MenuPanel);
ControlExtensions.SetDoubleBuffered(settingsTabControl);

Friday, 25 September 2015

Copy, Move and Delete Files and Folders in C#:


Below are the commonly used methods (using “System.IO” namespace):

For deleting:
 File:          File.Delete(“Path to the file”);
 Folder:     Directory.Delete(“Path to the folder”);

The above methods will delete the file \ folder permanently. User cannot restore them back.

For Copying:
File:          File. Copy(“source path” , “destination path”);
 Folder:     You will have to recursively traverse through the source directory and create directory and copy files.

For Moving:
File:          File.Move(“source path” , “destination path”);
 Folder:     Directory.Move(“ source path” , “destination path”);

The above methods wouldn’t display the error dialogs, in case of any error OR the progress dialog to show the progress.

"Microsoft.VisualBasic.FileIO"namespace provides a class “FileSystem” that shows all the dialog such as Error dialog, Progress dialog etc. and it’s very simple to use. 



For deleting:
 File:          FileSystem.DeleteFile(“Path to the file”, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

 Folder:     FileSystem.DeleteDirectory(“Path to the file”, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

Here  3rd Argument:  RecycleOption also provide 2 options:
  • Delete to Recycle Bin.
  • Delete permanently.


For Copying:
File:          FileSystem.CopyFile(“ source path” , “destination path”, UIOption.OnlyErrorDialogs);
Folder:     FileSystem.CopyDirectory(sourceFile, destFile, UIOption.OnlyErrorDialogs);

For Moving:
File:          FileSystem.MoveFile(sourcePath, targetPath, UIOption.OnlyErrorDialogs);
Folder:     FileSystem.MoveDirectory(sourcePath, targetPath, UIOption.OnlyErrorDialogs);


Argument UIOption passed above provide 2 options:
  • To show only error dialogs
  •  To show all dialogs.

Wednesday, 29 July 2015

Get the size of files having long path in C#.Net 3.5

Get the size of files having long path in  C#.Net 3.5


Suppose you want to get the size of all the files present in a directory. You would do something like this:

Method 1:

DirectoryInfo di = new DirectoryInfo(path); // path: It’s the path to the directory
FileInfo[] fInfos = di.GetFiles();
long fileSize = 0;
foreach (FileInfo fi in fInfos)
{     
fileSize = fi.Length;                   
}

But if you have files having full path (including directory name) more than 260 characters, “fi.Length” will throw FileNotFoundException. Even if the file exists, you will get this error, as shown in the screenshot below:


To fix this issue, include the following namespace:
using System.Reflection;
And use the below code:
public const int MAX_PATH = 260;
public const int MAX_ALTERNATE = 14;

[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;
};

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WIN32_FIND_DATA
{
public FileAttributes dwFileAttributes;
public FILETIME ftCreationTime;
public FILETIME ftLastAccessTime;
public FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ALTERNATE)]
public string cAlternate;
}

[DllImport("kernel32", CharSet = CharSet.Unicode)]public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

Define the below function that will return the size of files having long path:

private long getFileSize(string fileName, out WIN32_FIND_DATA findData)
        {
            long size = 0;
            IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
            IntPtr findHandle;

            findHandle = FindFirstFile(@"\\?\" + fileName , out findData);
            if (findHandle != INVALID_HANDLE_VALUE)
            {
                if ((findData.dwFileAttributes & FileAttributes.Directory) == 0)
                {
                    size = (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
                }
            }
            return size;
        }

Update the Method 1 with the below code:



DirectoryInfo di = new DirectoryInfo(path); // path: It’s the path to the directory
FileInfo[] fInfos = di.GetFiles();
long fileSize = 0;
if (fi.Exists)
{
fileSize = fi.Length;
}
else
{
// This will handle long paths
FieldInfo fld = typeof(FileSystemInfo).GetField( "FullPath",  BindingFlags.Instance |
BindingFlags.NonPublic);
string fullPath = fld.GetValue(fi).ToString();
WIN32_FIND_DATA findData;
fileSize = getFileSize(fullPath, out findData);
}



The function getFileSize outputs “findData” of type WIN32_FIND_DATA. It can be used to get the attribute, created date, last access date and other properties of file having long path as below:

string attribute = findData.dwFileAttributes.ToString();

DateTime CreationTime = DateTime.FromFileTimeUtc((((long)findData.ftCreationTime.dwHighDateTime) << 32) | ((uint)findData.ftCreationTime.dwLowDateTime));

DateTime LastAccessTime = DateTime.FromFileTimeUtc((((long)findData.ftLastAccessTime.dwHighDateTime) << 32) | ((uint)findData.ftLastAccessTime.dwLowDateTime));

DateTime LastWriteTime = DateTime.FromFileTimeUtc((((long)findData.ftLastWriteTime.dwHighDateTime) << 32) | ((uint)findData.ftLastWriteTime.dwLowDateTime));