Friday, August 31, 2012

c# - Check SQL Server is running else send notification

I have posted code to list all the windows services on a server in my previous post.Recently I had to upgrade one of our production database server and over the weekend the server crashed.I did not catch it till the next monday when I tried to write a query against one of the databases on the production server.

So I decided to write a program that would run every 15 mins to check whether the production database server is down and if it is down send an email to me so that I can take necessary action.Below is the code.


 static void Main(string[] args)
        {
            try
            {
                string [] sServerList = ConfigurationSettings.AppSettings["SERVER_LIST"].Split(',');

                foreach(string sServer in sServerList)

                {
                    if(CheckServiceRunning(sServer,"SQL Server (MSSQLSERVER)") != "Running")
                        SendMail("WARNING:Production Database Server:"+  sServer + " is not running !","DATABASE SERVER DOWN",new string[] {"me@mycompany.com,mymanager@mycompany.com" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static string CheckServiceRunning(string sServerName, string sServiceName)
        {
            ServiceController[] oaServiceController = ServiceController.GetServices(sServerName);
            foreach (ServiceController sc in oaServiceController)
            {
                if (sc.DisplayName == sServiceName)
                    return sc.Status.ToString();
            }
            return string.Empty;
        }
        public static void SendMail(String message, String subject, String[] notificationList)
        {
            try
            {
                MailMessage MyMessage = new MailMessage();
                MyMessage.From = new MailAddress("me@mycompany.com");
                foreach (String email in notificationList)
                    MyMessage.To.Add(new MailAddress(email));

                MyMessage.Subject = subject;

                MyMessage.Body = message;

                SmtpClient emailClient = new SmtpClient("smtp.myoffice.mycompany.com");

                emailClient.Send(MyMessage);
            }
            catch
            {
            }
        }

Thursday, August 30, 2012

c# - List all Windows Services on a server/machine

I have a few c# windows services that have been hosted on multiple servers.I wanted to check the status of those services without having to log on to the server.The below code will list all the services and its status on the server.

using System.ServiceProcess;


try
{
       ServiceController[] oaServiceController = ServiceController.GetServices("myservername");
       foreach (ServiceController sc in oaServiceController)
             Console.WriteLine("Service Name: " + sc.DisplayName + " Service Status:" + sc.Status.ToString());
}
catch (Exception ex)
{
      Console.WriteLine(ex.Message);
}




Wednesday, August 22, 2012

c# - Pyramid Structure with 1 For Loop, GOTO

I came across a forum post where original poster wanted to print numbers in a pyramid format using just one for loop.Something like below.

1
2  3
4  5  6
7  8  9  10

Source Code:

static void Main(string[] args)
{
       int i = 1,j = 0,m=0;
       
       for (int k = 1; k <= 10; k++)
      {
           j = 0;
           JUMP:if (j < i)
          {
                Console.Write(m++);
                Console.Write('\t');
                 j++;
                 goto JUMP;
          }
          Console.WriteLine();
           i++;
     }
     Console.Read();
}

















Similarly for the below structure
1
2  2
3  3  3
4  4  4  4
5  5  5  5  5

Source Code:

static void Main(string[] args)
{
       int i = 1, j = 0;

       for (int k = 1; k <= 10; k++)
       {
            j = 0;
            JUMP: if (j < i)
            {
                  Console.Write(k);
                  Console.Write('\t');
                  j++;
                  goto JUMP;
             }
             Console.WriteLine();
             i++;
        }
        Console.Read();
}



Tuesday, August 21, 2012

[264] An attempt was made to send an email when no email session has been established SQL Server 2005

I started seeing this error on one of the SQL Server 2005












To resolve this error on SQL Server 2005 follow the below steps.

Right Click on SQL Server Agent --> Go Properties 


Click on Alert System --> Enable Mail Profile.



Thursday, August 16, 2012

c# - Converting TimeStamp to DateTime

Ever come across timestamps represented by large integer value? For example like this 1344938468,1344938468416? This is timestamp from Unix based system and represents the number of seconds/milliseconds elapsed since the Unix Epoch January 1st, 1970

Timestamp Seconds to DateTime


try
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);//Unix Epoch on January 1st, 1970
    Console.WriteLine("Converting timestamp in Seconds");
    Console.WriteLine(origin.AddSeconds(1344938468));
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
 
















Timestamp Milliseconds to DateTime


try
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);//Unix Epoch on January 1st, 1970
    Console.WriteLine("Converting timestamp in MilliSeconds");
    Console.WriteLine(origin.AddMilliseconds(1344938468416));
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}


      

Friday, August 10, 2012

c# - String.StartsWith , StringComparision.Ordinal Performance

I have a daily process that parses a huge file and creates an aggregated output file by reading each line.I wanted to improve the performance of the this process so I decided to visit each string operation in my code and see if I could there was any room for improvement.

I came across this piece of code and it was being executed for each line.The number of lines in the input file varied on a daily basis but was around 20+ million

if (x.StartsWith("a"))
           z = x.Replace("a", "");
else if (x.StartsWith("b"))
           z = x.Replace("b", "");

After reading through string comparisons,performance I decided to test it out in my process
(http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx)

I modified the above code to this


if (x.StartsWith("a", StringComparison.Ordinal))
           z = x.Replace("a", "");
else if (x.StartsWith("b", StringComparison.Ordinal))
           z = x.Replace("b", "");

Indeed there was a 21% performance gain.


Results:


Before


 











After





Thursday, August 9, 2012

c# - String.Format vs String.Join Performance

In one of my projects,I parse a huge raw text file (160+ GB) and create a delimited  text output file.I have always used String.Format for writing to the output file till I came across String.Join.After going through the forums regarding both the method's performance,I decided to test it myself

Here are the test results.I ran this test all day long, multiple times.

String.Join is faster but the difference is negligible. Also note that these tests may vary based on your data,requirements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StringFormatJoin

{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                for (int i = 0; i < 1000000; i++)

                {
                    Console.Write("Iteration:" + i);
                    Console.WriteLine(string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test"));
                }
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                    ts.Hours, ts.Minutes, ts.Seconds,
                    ts.Milliseconds);

                Stopwatch stopWatch1 = new Stopwatch();

                stopWatch1.Start();

                for (int i = 0; i < 1000000; i++)

                {
                    Console.Write("Iteration:" + i);
                    Console.WriteLine(string.Join("|", new string[] { "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test" }));
                }

                stopWatch1.Stop();

                TimeSpan ts1 = stopWatch1.Elapsed;

                string elapsedTime1 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                    ts1.Hours, ts1.Minutes, ts1.Seconds,
                    ts1.Milliseconds);

                Console.WriteLine("Format RunTime " + elapsedTime);

                Console.WriteLine("Join RunTime " + elapsedTime1);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

Output


Iterations:100,000




 Iterations:100,000



Iterations:1,000,000


Iterations:1,000,000




Monday, August 6, 2012

c#,asp.net - 3rd Party UI controls

I have worked with Infragistics,Obout,Xceed controls in my projects but the one I have always preferred and I am most comfortable with is Telerik.

More about telerik controls can be found here

www.telerik.com 

Friday, August 3, 2012

Atom RSS date,ISO8601 to SQL date conversion using SQL Server

In my earlier post I had listed the C# code to convert the ISO8601 date to SQL date.Here's the same in SQL Server.

select convert(datetime, '2008-10-23T18:52:47.513Z', 127)





Thursday, August 2, 2012

interop type cannot be embedded use the applicable interface instead Visual Studio 2010

I came across this error when I tried to reference a dll which I used without any issues in other projects and other versions of Visual Studio.
I found the solution for this error on stackoverflow here
http://stackoverflow.com/questions/2483659/interop-type-cannot-be-embedded

If you do not get the steps in the above solution, the below images should help you out.