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;
}

DateTimePickerColumn in DataGridView



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SIMS.MesoftControl
{
    class CalendarColumn : DataGridViewColumn
    {
        public CalendarColumn()
            : base(new CalendarCell())
        {
        }
        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                if (value != null && !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
                {
                    throw new InvalidCastException("Must be a CalendarCell");
                }
                base.CellTemplate = value;
            }
        }
    }
    public class CalendarCell : DataGridViewTextBoxCell
    {
        public CalendarCell()
            : base()
        {
            this.Style.Format = "d";
        }
        public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
            dataGridViewCellStyle);
            CalendarEditingControl ctl =
            DataGridView.EditingControl as CalendarEditingControl;
            ctl.Value = (DateTime)this.Value;
        }
        public override Type EditType
        {
            get
            {
                return typeof(CalendarEditingControl);
            }
        }
        public override Type ValueType
        {
            get
            {
                return typeof(DateTime);
            }
        }
        public override object DefaultNewRowValue
        {
            get
            {
                return DateTime.Now;
            }
        }
    }
    class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool valueChanged = false;
        int rowIndex;
        public CalendarEditingControl()
        {
            this.Format = DateTimePickerFormat.Short;
        }
        public object EditingControlFormattedValue
        {
            get
            {
                return this.Value.ToShortDateString();
            }
            set
            {
                if (value is String)
                {
                    this.Value = DateTime.Parse((String)value);
                }
            }
        }
        public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }
        public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
            this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
        }
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
               rowIndex = value;
            }
        }
        public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
        {
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return false;
            }
        }
        public void PrepareEditingControlForEdit(bool selectAll)
        {
        }
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }
        public bool EditingControlValueChanged
        {
            get
            {
                return valueChanged;
            }
            set
            {
                valueChanged = value;
            }
        }
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }
        protected override void OnValueChanged(EventArgs eventargs)
        {
            valueChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnValueChanged(eventargs);
        }
    }
}

Group Chat Example



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace MulticastChat
{
    public partial class Form1 : Form
    {
        Socket cs;
        Thread t;
        IPEndPoint gip;
        public Form1()
        {
            InitializeComponent();
            gip = new IPEndPoint(IPAddress.Parse(GroupIptextBox.Text), 7080);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                panel1.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void Receive()
        {
            try
            {
                EndPoint ep = (EndPoint)gip;
                byte[] data = new byte[2048];
                string Msg;
                int recv;
                while (true)
                {
                    recv = cs.ReceiveFrom(data, ref ep);
                    Msg = Encoding.ASCII.GetString(data, 0, recv);
                    string UserName = "";
                    UserName = Msg.Substring(0, Msg.IndexOf(":"));
                    Msg = Msg.Substring(Msg.IndexOf(":") + 1);
                    ReceverichTextBox.Text = ReceverichTextBox.Text + UserName + " : " + Msg + "\n";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Sendbutton_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] msg = Encoding.ASCII.GetBytes(UserNametextBox.Text + " : " + SendtextBox.Text);
                SendtextBox.Clear();
                cs.SendTo(msg, SocketFlags.None, gip);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Connectbutton_Click(object sender, EventArgs e)
        {
            try
            {
                if (GroupIptextBox.Text != "")
                {
                    if (UserNametextBox.Text != "")
                    {
                        if (Connectbutton.Text == "Connect")
                        {
                            cs = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                            IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 7080);
                            cs.Bind(ipe);
                            cs.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.10.0.1")));
                            t = new Thread(new ThreadStart(Receive));
                            t.IsBackground = true;
                            t.Start();
                            panel1.Enabled = true;
                            Connectbutton.Text = "Disconnect";
                            GroupIptextBox.ReadOnly = true;
                            UserNametextBox.ReadOnly = true;
                        }
                        else if (Connectbutton.Text == "Disconnect")
                        {
                            t.Abort();
                            cs.Close();
                            GroupIptextBox.ReadOnly = false;
                            UserNametextBox.ReadOnly = false;
                            panel1.Enabled = false;
                            Connectbutton.Text = "Connect";
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please Enter Your Name...", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter Group Ip...", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}