Thursday, March 27, 2014

Make Corner Curve in Win C#

I have taken reference from below url for this code
http://stackoverflow.com/questions/10674228/form-with-rounded-borders-in-c


Code:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
-----
    public partial class Form1 : Form
    {
        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
        (
            int nLeftRect, // x-coordinate of upper-left corner
            int nTopRect, // y-coordinate of upper-left corner
            int nRightRect, // x-coordinate of lower-right corner
            int nBottomRect, // y-coordinate of lower-right corner
            int nWidthEllipse, // height of ellipse
            int nHeightEllipse // width of ellipse
         );

        public Form1()
        {
            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.None;
            Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
        }
    }

Tuesday, March 25, 2014

Check Application Installed in C#

Use the Following function to check the application is installed in User System or not. This code reference is taken from below link :
http://stackoverflow.com/questions/16379143/check-if-application-is-installed-in-registry


public static bool checkInstalled (string c_name)
{
            string displayName;

            string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null)
            {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
                {
                    displayName = subkey.GetValue("DisplayName") as string;

                    if (displayName != null && displayName.Contains(c_name))
                    {
                        return true;
                    }
                }
                key.Close();
            }

            registryKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
            key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null)
            {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
                {
                    displayName = subkey.GetValue("DisplayName") as string;

                    if (displayName != null && displayName.Contains(c_name))
                    {
                        return true;
                    }
                }
                key.Close();
            }
            return false;

}

and Use this as follow

if(checkInstalled("Application Name"))

Attach external file in excel sheet by C#

Just add file in your worksheet by following code

ws.Shapes.AddOLEObject(Filename: @"c:\data\filename.pdf", Height: 10, Width: 10, Top: 150, Left: 300);

Wednesday, March 19, 2014

Write Excel from C#

I am creating Excel sheet from ListViewItem Collection i.e. from System.Windows.Forms.ListView.ListViewItemCollection, You can take any array for this.

So here is my code to generate the excel sheet

public static void createExcel(System.Windows.Forms.ListView.ListViewItemCollection items)
{
     //Creating Excel Sheet for Report
     Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
     if (xlApp == null)
     {
         Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
         return;
     }
     xlApp.Visible = true;

     Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
     Worksheet ws1 = (Worksheet)wb.Worksheets[1];
     ws1.Name = "Failed Result";
     Worksheet ws2 = (Worksheet)wb.Worksheets.Add();
     ws2.Name = "Success Result";

     if (ws1 == null || ws2 == null)
     {
         Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
     }

     int success = 0;
     int failed = 0;
     for (int i = 1; i <= items.Count; i++)
     {
         // Fill the cells in the selected range of the worksheet with the number 6.
         if (items[i - 1].BackColor == Color.LightSeaGreen)
         {
             success++;
             ws2.Cells[success, 1] = i.ToString();
             //This will increase the column width
             ws2.Cells[success, 2].EntireColumn.ColumnWidth = 20;
             ws2.Cells[success, 2] = items[i - 1].SubItems[1].Text.ToString();
             ws2.Cells[success, 3] = items[i - 1].SubItems[2].Text.ToString();
         }
         else
         {
             failed++;
             ws1.Cells[failed, 1] = i.ToString();
             ws1.Cells[failed, 2] = items[i - 1].SubItems[1].Text.ToString();
             ws1.Cells[failed, 3] = items[i - 1].SubItems[2].Text.ToString();
             //Link Second Sheet Cell link to First Sheet Cell
             ws1.Hyperlinks.Add(ws1.get_Range("C" + failed, Type.Missing), "#Sheet1!A"+failed, Type.Missing, "Link to Issue");
         }
     }
     DateTime date = new DateTime();
      wb.SaveAs("C:\\data\\Result"+date.ToString("g")+".xlsx");
}

Clear Safari Cache from C#

I have taken this reference from below URL, but modified some code.

http://www.catonmat.net/blog/clear-privacy-ie-firefox-opera-chrome-safari/

1. Make a .bat file and paste the following lines in that (I saved as "SafariClearCache.bat")

@echo off

set DataDir=C:\Users\%USERNAME%\AppData\Local\Applec~1\Safari
set DataDir2=C:\Users\%USERNAME%\AppData\Roaming\Applec~1\Safari

del /q /s /f "%DataDir%\History"
rd /s /q "%DataDir%\History"

del /q /s /f "%DataDir%\Cache.db"
del /q /s /f "%DataDir%\WebpageIcons.db"

del /q /s /f "%DataDir2%"
rd /s /q "%DataDir2%"

2. Now in your C# code include

using System.Diagnostics;

3. Now add following code of C#

public static void ClearSafariCache()
{
   Process proc = null;
   try
   {
       proc = new Process();
       proc.StartInfo.FileName = "SafariClearCache.bat";
       proc.StartInfo.CreateNoWindow = false;
       proc.Start();
       proc.WaitForExit();
   }
   catch (Exception ex)
   {
       Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
   }

}

Clear FireFox Cache from C#

I have taken this reference from below URL, but modified some code.

http://www.catonmat.net/blog/clear-privacy-ie-firefox-opera-chrome-safari/

1. Make a .bat file and paste the following lines in that (I saved as "FireFoxClearCache.bat")

@echo off

set DataDir=C:\Users\%USERNAME%\AppData\Local\Mozilla\Firefox\Profiles

del /q /s /f "%DataDir%"
rd /s /q "%DataDir%"

for /d %%x in (C:\Users\%USERNAME%\AppData\Roaming\Mozilla\Firefox\Profiles\*) do del /q /s /f %%x\*sqlite

2. Now in your C# code include

using System.Diagnostics;

3. Now add following code of C#

public static void ClearFireFoxCache()
{
   Process proc = null;
   try
   {
       proc = new Process();
       proc.StartInfo.FileName = "FireFoxClearCache.bat";
       proc.StartInfo.CreateNoWindow = false;
       proc.Start();
       proc.WaitForExit();
   }
   catch (Exception ex)
   {
       Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
   }

}

Tuesday, March 18, 2014

Clear Chrome Cache from C#

I have taken this reference from below URL, but modified some code.

http://www.catonmat.net/blog/clear-privacy-ie-firefox-opera-chrome-safari/

1. Make a .bat file and paste the following lines in that (I saved as "ChromeClearCache.bat")

@echo off

set ChromeDir=C:\Users\%USERNAME%\appdata\Local\Google\Chrome\User Data\Default\Cache

del /q /s /f "%ChromeDir%"
rd /s /q "%ChromeDir%"

2. Now in your C# code include

using System.Diagnostics;

3. Now add following code of C#

public static void ClearChromCache()
{
   Process proc = null;
   try
   {
       proc = new Process();
       proc.StartInfo.FileName = "ChromeClearCache.bat";
       proc.StartInfo.CreateNoWindow = false;
       proc.Start();
       proc.WaitForExit();
   }
   catch (Exception ex)
   {
       Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
   }

}

Wednesday, March 12, 2014

How to read XML in easy way in Win C#

I have an XML like below

<?xml version="1.0" encoding="UTF-8"?>
<xd:xmldiff xmlns:xd="http://schemas.microsoft.com/xmltools/2002/xmldiff" fragments="no" options="IgnoreChildOrder IgnoreNamespaces IgnorePrefixes " srcDocHash="41SGFJBSJ43294" version="1.0">
      <xd:node match="2">
            <xd:change match="@version">5.3.7.0</xd:change>
            <xd:node match="3">
                  <xd:change match="@market">default</xd:change>
            </xd:node>
            <xd:node match="14">
                  <xd:node match="8">
                  <xd:change match="@iconFilename">Icons/fav.ico</xd:change>
            </xd:node>
      </xd:node>
 </xd:xmldiff>

Now to read this. (If this is in in some file)
use like below
first of all add:
using System.Xml;

Now write the below code 
XmlDocument doc1 = new XmlDocument();
doc1.Load(xmlFilePath);

And then 
XmlNodeList rootNodeList = doc1.GetElementsByTagName("xd:change");
foreach (XmlNode nd in rootNodeList)
{
  if(nd.ChildNodes.Count>0)
    Console.WriteLine(nd.Attributes["match"].Value + ", " + nd.ChildNodes.Item(0).Value);
  else
    Console.WriteLine(nd.Attributes["match"].Value);
}

Above code will show match attribute of all "xd:change" node. Either that is Parent Node or Child Node.

Thursday, March 6, 2014

Clear Cache of IE in Winform C#

I found this logic from below URL and it works fine for me, as well.

http://www.gutgames.com/post/Clearing-the-Cache-of-a-WebBrowser-Control.aspx

Code is as below

Just Save this as WebBrowserHelper.cs Class and call as WebBrowserHelper.ClearCache() Thats it :)

/**
     * Modified from code originally found here: http://support.microsoft.com/kb/326201
     **/
    #region Usings
    using System;
   using System.Runtime.InteropServices;
     
    #endregion

namespace Utilities.Web.WebBrowserHelper
{
    /// <summary>
    /// Class for clearing the cache
    /// </summary>
    public static class WebBrowserHelper
    {
        #region Definitions/DLL Imports
        /// <summary>
        /// For PInvoke: Contains information about an entry in the Internet cache
        /// </summary>
        [StructLayout(LayoutKind.Explicit, Size = 80)]
        public struct INTERNET_CACHE_ENTRY_INFOA
        {
            [FieldOffset(0)]
            public uint dwStructSize;
            [FieldOffset(4)]
            public IntPtr lpszSourceUrlName;
            [FieldOffset(8)]
            public IntPtr lpszLocalFileName;
            [FieldOffset(12)]
            public uint CacheEntryType;
            [FieldOffset(16)]
            public uint dwUseCount;
            [FieldOffset(20)]
            public uint dwHitRate;
            [FieldOffset(24)]
            public uint dwSizeLow;
            [FieldOffset(28)]
            public uint dwSizeHigh;
            [FieldOffset(32)]
            public System.Runtime.InteropServices.ComTypes.FILETIME LastModifiedTime;
            [FieldOffset(40)]
            public System.Runtime.InteropServices.ComTypes.FILETIME ExpireTime;
            [FieldOffset(48)]
            public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
            [FieldOffset(56)]
            public System.Runtime.InteropServices.ComTypes.FILETIME LastSyncTime;
            [FieldOffset(64)]
            public IntPtr lpHeaderInfo;
            [FieldOffset(68)]
            public uint dwHeaderInfoSize;
            [FieldOffset(72)]
            public IntPtr lpszFileExtension;
            [FieldOffset(76)]
            public uint dwReserved;
            [FieldOffset(76)]
            public uint dwExemptDelta;
        }

        // For PInvoke: Initiates the enumeration of the cache groups in the Internet cache
        [DllImport(@"wininet",
            SetLastError = true,
            CharSet = CharSet.Auto,
            EntryPoint = "FindFirstUrlCacheGroup",
            CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr FindFirstUrlCacheGroup(
            int dwFlags,
            int dwFilter,
            IntPtr lpSearchCondition,
            int dwSearchCondition,
            ref long lpGroupId,
            IntPtr lpReserved);

        // For PInvoke: Retrieves the next cache group in a cache group enumeration
        [DllImport(@"wininet",
            SetLastError = true,
            CharSet = CharSet.Auto,
            EntryPoint = "FindNextUrlCacheGroup",
            CallingConvention = CallingConvention.StdCall)]
        public static extern bool FindNextUrlCacheGroup(
            IntPtr hFind,
            ref long lpGroupId,
            IntPtr lpReserved);

        // For PInvoke: Releases the specified GROUPID and any associated state in the cache index file
        [DllImport(@"wininet",
            SetLastError = true,
           CharSet = CharSet.Auto,
            EntryPoint = "DeleteUrlCacheGroup",
            CallingConvention = CallingConvention.StdCall)]
        public static extern bool DeleteUrlCacheGroup(
            long GroupId,
            int dwFlags,
            IntPtr lpReserved);

        // For PInvoke: Begins the enumeration of the Internet cache
        [DllImport(@"wininet",
            SetLastError = true,
            CharSet = CharSet.Auto,
           EntryPoint = "FindFirstUrlCacheEntryA",
           CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr FindFirstUrlCacheEntry(
            [MarshalAs(UnmanagedType.LPTStr)] string lpszUrlSearchPattern,
            IntPtr lpFirstCacheEntryInfo,
            ref int lpdwFirstCacheEntryInfoBufferSize);

        // For PInvoke: Retrieves the next entry in the Internet cache
        [DllImport(@"wininet",
            SetLastError = true,
            CharSet = CharSet.Auto,
            EntryPoint = "FindNextUrlCacheEntryA",
            CallingConvention = CallingConvention.StdCall)]
        public static extern bool FindNextUrlCacheEntry(
            IntPtr hFind,
            IntPtr lpNextCacheEntryInfo,
            ref int lpdwNextCacheEntryInfoBufferSize);

        // For PInvoke: Removes the file that is associated with the source name from the cache, if the file exists
        [DllImport(@"wininet",
            SetLastError = true,
            CharSet = CharSet.Auto,
            EntryPoint = "DeleteUrlCacheEntryA",
            CallingConvention = CallingConvention.StdCall)]
        public static extern bool DeleteUrlCacheEntry(
            IntPtr lpszUrlName);
        #endregion

        #region Public Static Functions

        /// <summary>
        /// Clears the cache of the web browser
        /// </summary>
        public static void ClearCache()
        {
            // Indicates that all of the cache groups in the user's system should be enumerated
            const int CACHEGROUP_SEARCH_ALL = 0x0;
            // Indicates that all the cache entries that are associated with the cache group
            // should be deleted, unless the entry belongs to another cache group.
            const int CACHEGROUP_FLAG_FLUSHURL_ONDELETE = 0x2;
            // File not found.
            const int ERROR_FILE_NOT_FOUND = 0x2;
            // No more items have been found.
            const int ERROR_NO_MORE_ITEMS = 259;
            // Pointer to a GROUPID variable
            long groupId = 0;

            // Local variables
            int cacheEntryInfoBufferSizeInitial = 0;
            int cacheEntryInfoBufferSize = 0;
            IntPtr cacheEntryInfoBuffer = IntPtr.Zero;
            INTERNET_CACHE_ENTRY_INFOA internetCacheEntry;
            IntPtr enumHandle = IntPtr.Zero;
            bool returnValue = false;

            // Delete the groups first.
            // Groups may not always exist on the system.
            // For more information, visit the following Microsoft Web site:
            // http://msdn.microsoft.com/library/?url=/workshop/networking/wininet/overview/cache.asp            
            // By default, a URL does not belong to any group. Therefore, that cache may become
            // empty even when the CacheGroup APIs are not used because the existing URL does not belong to any group.            
            enumHandle = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, IntPtr.Zero, 0, ref groupId, IntPtr.Zero);
            // If there are no items in the Cache, you are finished.
            if (enumHandle != IntPtr.Zero && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error())
                return;

            // Loop through Cache Group, and then delete entries.
            while (true)
            {
                if (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error() || ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error()) { break; }
                // Delete a particular Cache Group.
                returnValue = DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, IntPtr.Zero);
                if (!returnValue && ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error())
                {
                    returnValue = FindNextUrlCacheGroup(enumHandle, ref groupId, IntPtr.Zero);
                }

                if (!returnValue && (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error() || ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error()))
                    break;
            }

            // Start to delete URLs that do not belong to any group.
            enumHandle = FindFirstUrlCacheEntry(null, IntPtr.Zero, ref cacheEntryInfoBufferSizeInitial);
            if (enumHandle != IntPtr.Zero && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error())
                return;

            cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
            cacheEntryInfoBuffer = Marshal.AllocHGlobal(cacheEntryInfoBufferSize);
            enumHandle = FindFirstUrlCacheEntry(null, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
            while (true)
            {
                internetCacheEntry = (INTERNET_CACHE_ENTRY_INFOA)Marshal.PtrToStructure(cacheEntryInfoBuffer, typeof(INTERNET_CACHE_ENTRY_INFOA));
                if (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error()) { break; }

                cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize;
                returnValue = DeleteUrlCacheEntry(internetCacheEntry.lpszSourceUrlName);
                if (!returnValue)
                {
                    returnValue = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
                }
                if (!returnValue && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error())
                {
                    break;
                }
                if (!returnValue && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize)
                {
                    cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
                    cacheEntryInfoBuffer = Marshal.ReAllocHGlobal(cacheEntryInfoBuffer, (IntPtr)cacheEntryInfoBufferSize);
                    returnValue = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
                }
            }
            Marshal.FreeHGlobal(cacheEntryInfoBuffer);
        }
        #endregion
    }
}

Wednesday, March 5, 2014

Right Click Menu in C# Winform

This is called as ContextMenu in coding terms. and I have written a simple code to add 2 menus items for right click menu i.e. ContextMenu


ContextMenu mnuContextMenu = new ContextMenu();
this.trackList.ContextMenu = mnuContextMenu;//trackList is the listview for me.
MenuItem mnuItemScroll = new MenuItem();
mnuItemScroll.Text = "&AutoScroll List";
MenuItem mnuItemCompare = new MenuItem();
mnuItemCompare.Text = "&Compare Files";
mnuContextMenu.MenuItems.Add(mnuItemScroll);
mnuContextMenu.MenuItems.Add(mnuItemCompare);


Tuesday, March 4, 2014

Web Traffic Handling by C# in Winform

I have made an application using FiddlerCore dll file. with the help of Site : http://fiddlerbook.com/Fiddler/Core/ 

First of all, Download the software from above link then you will get 3 dlls from this software i. e.
1. BCMakeCert.dll
2. CertMaker.dll
3. FiddlerCore.dll

Add these dll by Reference.

Now add the following code at respective place

using Fiddler;
***************************************

Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;

Fiddler.FiddlerApplication.Startup(8764,Fiddler.FiddlerCoreStartupFlags.Default);
****************************************
void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession)
{
     Console.WriteLine(String.Format("REQ: {0}", oSession.url));
     Console.WriteLine(oSession.GetResponseBodyAsString());
}

Thats it :) So Simple hmmm