Get list of computer name from network




using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections;
using System.Windows.Forms;
namespace Mesoft.Network
{
    public sealed class NetworkBrowser
    {
        #region Dll Imports
         //declare the the Netapi32 : NetServerEnum method import
        [DllImport("Netapi32", CharSet = CharSet.Auto, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        /// <summary>
        /// Netapi32.dll : The NetServerEnum function lists all servers
        /// of the specified type that are visible in a domain. For example, an 
        /// application can call NetServerEnum to list all domain controllers only
        /// or all SQL servers only.
        ///    You can combine bit masks to list several types. For example, a value 
        /// of 0x00000003  combines the bit masks for SV_TYPE_WORKSTATION 
        /// (0x00000001) and SV_TYPE_SERVER (0x00000002)
        /// </summary>
        public static extern int NetServerEnum(
            string ServerNane, // must be null
            int dwLevel,
            ref IntPtr pBuf,
            int dwPrefMaxLen,
            out int dwEntriesRead,
            out int dwTotalEntries,
            int dwServerType,
            string domain, // null for login domain
            out int dwResumeHandle
            );
        //declare the Netapi32 : NetApiBufferFree method import
        [DllImport("Netapi32", SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        /// <summary>
        /// Netapi32.dll : The NetApiBufferFree function frees 
        /// the memory that the NetApiBufferAllocate function allocates. 
        /// Call NetApiBufferFree to free the memory that other network 
        /// management functions return.
        /// </summary>
        public static extern int NetApiBufferFree(
            IntPtr pBuf);
        //create a _SERVER_INFO_100 STRUCTURE
        [StructLayout(LayoutKind.Sequential)]
        public struct _SERVER_INFO_100
        {
            internal int sv100_platform_id;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string sv100_name;
        }
        #endregion
        #region Public Constructor
        public NetworkBrowser()
        {
        }
        #endregion
        #region Public Methods
        /// <summary>
        /// Uses the DllImport : NetServerEnum with all its required parameters
        /// (see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/netserverenum.asp
        /// for full details or method signature) to retrieve a list of domain SV_TYPE_WORKSTATION
        /// and SV_TYPE_SERVER PC's
        /// </summary>
        /// <returns>Arraylist that represents all the SV_TYPE_WORKSTATION and SV_TYPE_SERVER
        /// PC's in the Domain</returns>
        public ArrayList getNetworkComputers()
        {
            //local fields
            ArrayList networkComputers = new ArrayList();
            const int MAX_PREFERRED_LENGTH = -1;
            int SV_TYPE_WORKSTATION = 1;
            int SV_TYPE_SERVER = 2;
            IntPtr buffer = IntPtr.Zero;
            IntPtr tmpBuffer = IntPtr.Zero;
            int entriesRead = 0;
           int totalEntries = 0;
            int resHandle = 0;
            int sizeofINFO = Marshal.SizeOf(typeof(_SERVER_INFO_100));
            try
            {
                //call the DllImport : NetServerEnum with all its required parameters
                //see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/netserverenum.asp
                //for full details of method signature
                int ret = NetServerEnum(null, 100, ref buffer, MAX_PREFERRED_LENGTH,
                    out entriesRead,
                    out totalEntries, SV_TYPE_WORKSTATION | SV_TYPE_SERVER, null, out 
                    resHandle);
              //if the returned with a NERR_Success (C++ term), =0 for C#
                if (ret == 0)
                {
                    //loop through all SV_TYPE_WORKSTATION and SV_TYPE_SERVER PC's
                    for (int i = 0; i < totalEntries; i++)
                    {
                        //get pointer to, Pointer to the buffer that received the data from
                        //the call to NetServerEnum. Must ensure to use correct size of 
                        //STRUCTURE to ensure correct location in memory is pointed to
                        tmpBuffer = new IntPtr((int)buffer + (i * sizeofINFO));
                        //Have now got a pointer to the list of SV_TYPE_WORKSTATION and 
                        //SV_TYPE_SERVER PC's, which is unmanaged memory
                        //Needs to Marshal data from an unmanaged block of memory to a 
                        //managed object, again using STRUCTURE to ensure the correct data
                        //is marshalled 
                        _SERVER_INFO_100 svrInfo = (_SERVER_INFO_100)
                            Marshal.PtrToStructure(tmpBuffer, typeof(_SERVER_INFO_100));
                        //add the PC names to the ArrayList
                        networkComputers.Add(svrInfo.sv100_name);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problem with acessing network computers in NetworkBrowser " + "\r\n\r\n\r\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            finally
            {
                //The NetApiBufferFree function frees 
                //the memory that the NetApiBufferAllocate function allocates
                NetApiBufferFree(buffer);
            }
            //return entries found
            return networkComputers;
        }
        #endregion
    }
}

Create Database driven MenuBar

***************************************************************************
Create Database Table
(1) Menu

SR int Not Null
MENU varchar(50) Not Null
MENUPROMPT varchar(50) Null
-------------------------------------------------------------------------------------
(2)Menu Item

SR int Not Null
ITEM varchar(50) Not Null
ITEMPROMPT varchar(50) Not Null
MENU varchar(50) Not Null
FORM varchar(50) Null
ICONPATH varchar(50) Null *****************************************************************************

Write this code
****************************************************************************

private void frmMAIN_Load(object sender, EventArgs e)
{
    try
    {
        timer1.Start();
        Flag = 0;
        frmBG ObjBg = new frmBG();
        ObjBg.MdiParent = ObjMainTemp;
        ObjBg.Show();
        DataTable dt = ObjGn.FillData("SELECT * FROM MENU ORDER BY SR");
        for (int i = 0; i < objmenu =" new" forecolor =" Color.White;" dropmenu =" ObjGn.FillData(" menu="'" j =" 0;" objsubmenu =" new" name =" DropMenu.Rows[j][" image =" Image.FromFile(DropMenu.Rows[j]["> 2)
        {
            Flag = 0;
        }
        Flag++;
        if (Flag == 2)
        {
            DataTable dt = ObjGn.FillData("SELECT * FROM MENUITEM WHERE ITEM='" + e.ClickedItem.Name + "'");
            CSharpCodeProvider c = new CSharpCodeProvider();
            ICodeCompiler icc = c.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("system.xml.dll");
            cp.ReferencedAssemblies.Add("system.data.dll");
            cp.ReferencedAssemblies.Add("system.windows.forms.dll");
            cp.ReferencedAssemblies.Add("system.drawing.dll");
            cp.ReferencedAssemblies.Add("WindowApplicationMenuTest.exe");
            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;
            StringBuilder sb = new StringBuilder("");
            sb.Append("using System;\r\n");
            sb.Append("using System.Xml;\r\n");
            sb.Append("using System.Data;\r\n");
            sb.Append("using System.Data.SqlClient;\r\n");
            sb.Append("using System.Windows.Forms;\r\n");
            sb.Append("using System.Drawing;\r\n");
            sb.Append("using WindowApplicationMenuTest; \r\n");
            sb.Append("namespace WindowApplicationMenuTest{ \r\n");
            sb.Append("public class CSCodeEvaler{ \r\n");
            sb.Append("public object EvalCode(){ \r\n");
            sb.Append(dt.Rows[0]["FORM"].ToString() + " ObjTemp = new " + dt.Rows[0]["FORM"].ToString() + "();");
            sb.Append("ObjTemp.MdiParent = frmMAIN.ObjMainTemp; \r\n");
            sb.Append("ObjTemp.Show();\r\n");
            sb.Append("ObjTemp.WindowState = FormWindowState.Maximized;\r\n");
            sb.Append("ObjTemp.Title.Text = \"" + dt.Rows[0]["ITEMPROMPT"].ToString() + "\";\r\n");
            sb.Append(" try{");
            sb.Append("ObjTemp.TempPic.Image = Image.FromFile(\"" + dt.Rows[0]["ICONPATH"].ToString() + "\");");
            sb.Append("return ObjTemp; \r\n}");
            sb.Append("catch { return null; }");
            sb.Append("} \r\n");
            sb.Append("} \r\n");
            sb.Append("} \r\n");
            CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, " Error evaluating cs code", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            System.Reflection.Assembly a = cr.CompiledAssembly;
            object o = a.CreateInstance("WindowApplicationMenuTest.CSCodeEvaler");
            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("EvalCode");
            object s = mi.Invoke(o, null);
            Flag = 0;
        }
    }catch(Exception ex){}
}

Clear Control using panel

NOTE : you have just take all controls in panel.
Call this method in clear button event. pass that panel in method argument




public void Control(System.Windows.Forms.Panel Pan)
{
    foreach (System.Windows.Forms.Control ctl in Pan.Controls)
    {
        if (ctl.GetType().ToString().Contains("TextBox"))
        {
            ((System.Windows.Forms.TextBox)ctl).Clear();
        }
        if (ctl.GetType().ToString().Contains("ComboBox"))
        {
            ((System.Windows.Forms.ComboBox)ctl).SelectedIndex = -1;
        }
    }
}

Change system date formate runtime



using Microsoft.Win32;

//then
RegistryKey rkey = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);
rkey.SetValue("sShortDate", "M/d/yyyy");
rkey.Close();

Get Percentage of matching two string

write this code in main method or as per you need
==============================================================
CalcSimilarity("romit.mewada", "RomitMewada", true)
==============================================================



private static int CalcLevensteinDistance(string left, string right)
{
    if (left == right)
    return 0;
    int[,] matrix = new int[left.LeMngth + 1, right.Length + 1];
    for (int i = 0; i <= left.Length; i++)
    // delete
    matrix[i, 0] = i;
    for (int j = 0; j <= right.Length; j++)
    // insert
    matrix[0, j] = j;
    for (int i = 0; i <>
    {
        for (int j = 0; j <>
        {
            if (left[i] == right[j])
                matrix[i + 1, j + 1] = matrix[i, j];
            else
            {
                // deletion or insertion
                matrix[i + 1, j + 1] = System.Math.Min(matrix[i, j + 1] + 1, matrix[i + 1, j] + 1);
 
                // substitution
                matrix[i + 1, j + 1] = System.Math.Min(matrix[i + 1, j + 1], matrix[i, j] + 1);
            }
        }
    }
    return matrix[left.Length, right.Length];
}
public static double CalcSimilarity(string left, string right, bool ignoreCase)
{
    if (ignoreCase)
    {
        left = left.ToLower();
        right = right.ToLower();
    }
    double distance = CalcLevensteinDistance(left, right);
    if (distance == 0.0f)
    return 1.0f;
    double longestStringSize = System.Math.Max(left.Length, right.Length);
    double percent = distance / longestStringSize;
    return 1.0f - percent;
}