Pixytech

Category: C#

  • SNMP Trap Listener

    Simple Network Management Protocol (SNMP) is an “Internet-standard protocol for managing devices on IP networks. Devices that typically support SNMP include routers, switches, Servers, workstations, printers, modem tracks etc. It is used mostly in network management systems to monitor network-attached devices for conditions that warrant administrative attention.

    SNMP exposes management data in the form of variables on the managed systems, which describe the system configuration. These variables can then be queried (and sometimes set) by managing applications.

    The code attached in this article is .net based windows service to trap SNMP messages (SNMP v2) and process them accordingly. The service is capable to handle thousands of messages per second by using .net threads. One thread listens for incoming messages and pump them in message queue while another thread will extract and process the messages from another end of the queue.

    The SNMP service in this article depends on windows “SNMP Trap Service”.

    The source code also includes project “(SNMPSendTrap)” to send test SNMP v2 traps. 

    Download source code for SNMP Listener (Vs2010)

  • SQL Server Discovery

    The objective of this article is to discover the presence of Microsoft SQL Server  across subnet. There are API’s to enumerate SQL Server instances in single subnet (Win32 API : NetServerEnum ) and Microsoft enterprise manger uses this API to populate the list of SQL server available in current subnet. The API NetServerEnum broadcast UDP packets in the network and SQL server respond the message by sending their details. Since UDP packets can’t cross subnets and hence it will only return the partial list in particular domain.

    I was working on project where I have to find if on given IP or IP range , any sql server exists or not and if sql server exists I need to find the instance names. etc.

    The SQL server discovery module is hosted on web server and will be accessed by Silverlight application via WCF service. The code can be used to determine if SQL server is running or not (Before trying to connect) to build more responsive applications.

    The code sends the UDP packet (point to point access) directly to provide ip address on port 1434 and revived the data back from machines.

    If server is there the another function connects on TCP channel on TCP IP port to extract Sql server Netlib version.

    public class SqlServerInfo
    {
        public string ServerName { get; private set; }
        public string IpAddress { get; private set; }
        public string InstanceName { get; private set; }
        public bool IsClustered { get; private set; }
        public string Version { get; private set; }
        public int tcpPort { get; private set; }
        public string NamedPipe { get; private set; }
        public string Rpc { get; private set; }
        public bool IsActive { get; private set; }
    
        static public List<SqlServerInfo> DiscoverSQLServer(string[] possibleIPs, bool requiredDeepCheck)
        {
            List<SqlServerInfo> servers = new List<SqlServerInfo>();
            foreach (string ip in possibleIPs)
            {
                servers.AddRange(SqlServerInfo.DiscoverSQLServer(ip));
            }
            return servers;
        }
    
        static public List<SqlServerInfo> DiscoverSQLServer(string ip)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.EnableBroadcast = true;
            socket.ReceiveTimeout = 1000;
            List<SqlServerInfo> servers = new List<SqlServerInfo>();
            try
            {
                byte[] msg = new byte[] { 3 };
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), 1434);
                socket.SendTo(msg, ep);
                int cnt = 0;
                byte[] bytBuffer = new byte[64000];
                do
                {
                    cnt = socket.Receive(bytBuffer);
                    string s = System.Text.ASCIIEncoding.ASCII.GetString(bytBuffer, 3, BitConverter.ToInt16(bytBuffer, 1));
                    string[] parts = s.Split(new string[] { ";;" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s1 in parts)
                    {
                        SqlServerInfo sInfo = new SqlServerInfo(s1);
                        sInfo.IpAddress = ip;
                        if (sInfo.CheckIsActive())
                        {
                            servers.Add(sInfo);
                        }
    
                    }
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 300);
                } while (cnt != 0);
            }
            catch
            {
    
            }
            finally
            {
                socket.Close();
            }
    
            return servers;
        }
    
        private SqlServerInfo()
        {
    
        }
    
        public  string SSNetlibVersion(string remoteIP, int port)
        {
            string str = "";
            try
            {
                TcpClient client = new TcpClient();
                client.SendTimeout = 300;
                client.ReceiveTimeout = 300;
                client.Connect(remoteIP, port);
                NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[] {
                    0x12, 1, 0, 0x34, 0, 0, 0, 0, 0, 0, 0x15, 0, 6, 1, 0, 0x1b,
                    0, 1, 2, 0, 0x1c, 0, 12, 3, 0, 40, 0, 4, 0xff, 8, 0, 1,
                    0x55, 0, 0, 0, 0x4d, 0x53, 0x53, 0x51, 0x4c, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0,
                    4, 8, 0, 0};
                stream.Write(buffer, 0, buffer.Length);
                byte[] buffer2 = new byte[0xff];
                string str2 = string.Empty;
                int count = stream.Read(buffer2, 0, buffer2.Length);
                str2 = Encoding.ASCII.GetString(buffer2, 0, count);
                string[] strArray = new string[] { buffer2[0x1d].ToString(), ".", buffer2[30].ToString(), ".", ((buffer2[0x1f] * 0x100) + buffer2[0x20]).ToString() };
                str = string.Concat(strArray);
                if (str.Substring(0, 1) == "0")
                {
                    str = "";
                }
            }
            catch
            {
            }
            return str;
        }
    
        private bool CheckIsActive()
        {
            string version= SSNetlibVersion(this.IpAddress, this.tcpPort);
            if (version.Length == 0)
            {
                this.IsActive = false;
                return false;
            }
            else
            {
                this.IsActive = true;
                this.Version = version;
                return true;
            }
    
        }
    
        private SqlServerInfo(string info)
        {
            string[] nvs = info.Split(';');
            for (int i = 0; i < nvs.Length; i += 2)
            {
                switch (nvs[i].ToLower())
                {
                    case "servername":
                        this.ServerName = nvs[i + 1];
                        break;
    
                    case "instancename":
    
                        this.InstanceName = nvs[i + 1];
                        break;
    
                    case "isclustered":
                        this.IsClustered = (nvs[i + 1].ToLower() == "yes");   //bool.Parse(nvs[i+1]);
                        break;
    
                    case "version":
                        this.Version = nvs[i + 1];
                        break;
    
                    case "tcp":
                        this.tcpPort = int.Parse(nvs[i + 1]);
                        break;
    
                    case "np":
                        this.NamedPipe = nvs[i + 1];
                        break;
    
                    case "rpc":
                        this.Rpc = nvs[i + 1];
                        break;
    
                }
            }
        }
    }

    using the code

    List<SqlServerInfo> sqlSrv = null;
    sqlSrv = SqlServerInfo.DiscoverSQLServer(address);
    //Or
    sqlSrv = SqlServerInfo.DiscoverSQLServer(
                        new string[]{ address+ ".01",
                            address+ ".02",
                            address+ ".03",
                            address+ ".04",
                            address+ ".05",
                            address+ ".06",
                            address+ ".07",
                            address+ ".08",
                            address+ ".09",
                            address+ ".10",
                            address+ ".21",
                            address+ ".51",
                            address+ ".100"},true);
  • LINQ Dynamic Query

    LINQ dynamic query code

    //Input : str=> string to search some text (First Name,Last Name,Date of Birth(dd/mm/yyyy) or post code) in any order;
    
    //output : result set
    
    str = str.ToLower().Replace("  ", " ").Trim();
    IList<vw_patient> patients = App.Patients;
    string[] parts = str.Split(" ".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
    Func<vw_patient, bool> predicate = null;
    
    foreach (string part in parts)
    {
        long retCode = 0;
        predicate = delegate(vw_patient p)
        {
            return p.Pati_FirstName.ToLower().StartsWith(part) ||
                   p.Pati_SurName.ToLower().StartsWith(part) ||
                   (long.TryParse(part.Replace("/", ""), out retCode) ? ((p.Pati_DOB.HasValue ? p.Pati_DOB.Value.ToShortDateString().Replace("/", "") : "").Contains(part.Replace("/", ""))) : false) ||
                   p.Pati_PostCode.Replace(" ","").ToLower().StartsWith(part);
        };
        patients =  patients.Where<vw_patient>(predicate).ToList();
    }
    
    this.dgPatients.ItemsSource = new PagedCollectionView(patients);
    //PagedCollectionView is used for paging with data grid
  • LG Remote Control

    LG LCD TV(LD35 Series) Remote Control

     

    Few weeks’ back I have purchased new LG LCD TV (22LG350).This model got USB port and RS232 serial port. You can attach you storage device like USB pen drive or external hard disk to play pictures and music. But unfortunately there is no option to play movies from you storage device.

    Technically, It should be possible to play movies(with movie player) as you play music with built in music player in LG TV. After going through several posts and forums like http://lgusb.wikispaces.com/ , I discovered that you need to just change one flag from 0 to 1 in some hidden menu known as EZ-Adjust menu. Information on Divx flag (in EZ-Adjust menu) can be found on lgusb web site.

    There are several tips to reach at EZ-Adjust (Hidden menu) where some suggests to buy universal remotes, IR hack and firmware upgrade/downgrade. Since there is RS232 port available on LG TV and manual suggest that this is for serial communication with TV. Actually TV has operating system “saturn6” and you can communicate with OS via serial port.

    So I thought to build Remote control for LCD TV running on my Laptop and communicate with TV via serial port (RS232). The source code for this application is attached here and setup for this application is here. If .net framework 4.0 is already installed on you system you may download executables only.
    What else you will need to run this.

    1.Cable (RS232);
    2. USB to Serial Convertor (If your system doesn’t have COM port)
    Before running this application you need to identify the com port on which your TV is connected. Run the application, select correct COM port and click on button “On” (Communication).

    * This article is not intended for Ez-Adjust menu options; Go through lgusb web site if you want to play with Ez-Adjust menus.

  • Silverlight Page Flip

    Page flip is a very impressive features in displaying your documents, images, media, etc.. The technique behind page flip is pretty complicated. Below is the page flip live application & source code link.

    You can download the source code here (VS 2010).

    I could not spare much time to write implementation notes , however, Rick Barraza has a very good articles describing all the mystery behind this technique in his post. The code is based on his article and can be further extended to create silverlight generic control which could even flip silverlight pages, documents, images etc.

    Another interested implementation of page turn effect is available on Microsoft by Jeff & Mitsu’s.

    Another page flip (book) control is available here