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.








Windows Communication Foundation #WCF Example: Create a Random Number Generator Service,Client C#

In this post I will go through the steps needed to create a Windows Communcation Foundation service,client. The example is very basic and will illustrate the minimum steps required to create a WCF application.

The steps to create a WCF application are



  1. Define a WCF service contract
  2. Implement a WCF service contract
  3. Host/Run the WCF service
  4. Create a WCF client
  5. Configure the WCF client
  6. Consume the WCF service using WCF client
Step 1: Design the WCF service contract

To start with create a console application in Visual Studio 2010 and choose new project -> console application.Give it a name 


Add a reference System.ServiceModel


Define a ServiceContract in the program.cs by creating an Interface and define a method as an OperationContract

[ServiceContract(Namespace = "http://RandomNumberService")]
public interface IRandomNumberGenerator
{
        [OperationContract]
        int GetRandomNumber(int iSeed, int iRange);
}



Program.cs would now look like this

using System;
using System.ServiceModel;

namespace RandomNumberService
{
    [ServiceContract(Namespace = "http://RandomNumberService")]
    public interface IRandomNumberGenerator
    {
        [OperationContract]
        int GetRandomNumber(int iSeed, int iRange);
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Step 2: Implement the WCF Service Contract.

Add a class to program.cs file and implement the interface defined in Step 1



 class RandomNumberGenerator : IRandomNumberGenerator

 {

        public int GetRandomNumber(int p_iSeed, int p_iRange)

        {
            Console.WriteLine("Seed: " + p_iSeed.ToString() + " Range: " + p_iRange.ToString());
            Random oRandom = new Random();
            int iRandomNumber = oRandom.Next(p_iSeed,p_iRange);
            Console.WriteLine("Random Number generated: " + iRandomNumber.ToString());
            return iRandomNumber;
        }
 }

Program.cs would now look like this

using System;
using System.ServiceModel;

namespace RandomNumberService
{
    [ServiceContract(Namespace = "http://RandomNumberService")]
    public interface IRandomNumberGenerator
    {
        [OperationContract]
        int GetRandomNumber(int iSeed, int iRange);
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
    class RandomNumberGenerator : IRandomNumberGenerator
    {
        public int GetRandomNumber(int p_iSeed, int p_iRange)
        {
            Console.WriteLine("Seed: " + p_iSeed.ToString() + " Range: " + p_iRange.ToString());
            Random oRandom = new Random();
            int iRandomNumber = oRandom.Next(p_iSeed,p_iRange);
            Console.WriteLine("Random Number generated: " + iRandomNumber.ToString());
            return iRandomNumber;
        }
    }
}

Step 3:Host and run the service.

Inorder to host the service, you need to create a base address,service host at the base address,configure the service host's endpoint and start the service host.
The above steps are listed in the below code

//Create a base address for your service host
Uri oBaseAddress = new Uri("http://localhost:12345/ServiceExample/Service");
//Create a service host using the base address
ServiceHost oServiceHost = new ServiceHost(typeof(RandomNumberGenerator), oBaseAddress);

try
{
   ServiceHost.AddServiceEndpoint(typeof(IRandomNumberGenerator), new WSHttpBinding(), "RandomNumberGenerator");
   ServiceMetadataBehavior oServiceMetadataBehavior = new ServiceMetadataBehavior();
   oServiceMetadataBehavior.HttpGetEnabled = true;
 oServiceHost.Description.Behaviors.Add(oServiceMetadataBehavior);
   oServiceHost.Open();

   Console.WriteLine("The service is started.");
   Console.WriteLine("Press any key to stop service.")                          

   Console.WriteLine();
   Console.ReadLine();

   oServiceHost.Close();

}
catch (CommunicationException ex)
{
     Console.WriteLine(ex.Message);
     oServiceHost.Abort();

Step 4: Create the WCF Client

In the solution explorer create  new project --> console application.Give it a name





Add System.ServiceModel refernce to your client 


Next step is to generate the proxy using the svcutil.exe
Using the Visual Studio Command Prompt go to C:Windows\System32 and use the scvutil.exe to generate the proxy.
Make sure the service is started before you try to generate the proxy class.


Generate the proxy using svcutil



Next import the proxy.cs and app.config into your client project

The proxy.cs has the below auto generated code

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.269
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------



[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://RandomNumberService", ConfigurationName="IRandomNumberGenerator")]
public interface IRandomNumberGenerator
{
    
    [System.ServiceModel.OperationContractAttribute(Action="http://RandomNumberService/IRandomNumberGenerator/GetRandomNumber", ReplyAction="http://RandomNumberService/IRandomNumberGenerator/GetRandomNumberResponse")]
    int GetRandomNumber(int iSeed, int iRange);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IRandomNumberGeneratorChannel : IRandomNumberGenerator, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class RandomNumberGeneratorClient : System.ServiceModel.ClientBase<IRandomNumberGenerator>, IRandomNumberGenerator
{
    
    public RandomNumberGeneratorClient()
    {
    }
    
    public RandomNumberGeneratorClient(string endpointConfigurationName) : 
            base(endpointConfigurationName)
    {
    }
    
    public RandomNumberGeneratorClient(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public RandomNumberGeneratorClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public RandomNumberGeneratorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress)
    {
    }
    
    public int GetRandomNumber(int iSeed, int iRange)
    {
        return base.Channel.GetRandomNumber(iSeed, iRange);
    }
}

Step 5: Configure the WCF Client.
Import the app.config to the client and you should see the endpoint configured.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IRandomNumberGenerator" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Message">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:12345/ServiceExample/Service/RandomNumberGenerator"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IRandomNumberGenerator"
                contract="IRandomNumberGenerator" name="WSHttpBinding_IRandomNumberGenerator">
                <identity>
                    <userPrincipalName value="myname@office.mycompany.com" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

Step 6:  Consume the WCF service using WCF client  

In the progam.cs main method file of the client project write the code to consume the methods from the hosted service

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

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            RandomNumberGeneratorClient oClient = new RandomNumberGeneratorClient();
            Console.WriteLine("Please enter the seed for random number generator");
            int iSeed = int.Parse(Console.ReadLine());
            Console.WriteLine("Please enter the range for the random number generator");
            int iRange = int.Parse(Console.ReadLine());

            Console.WriteLine("Random Number returned from the service: " + oClient.GetRandomNumber(iSeed, iRange));
            oClient.Close();
            Console.WriteLine("Press any key to stop the client");
            Console.Read();
        }
    }
}

Compile the client code and now you are all set to run your WCF application

Output:
Run the host first















Start your client and enter the seed,range values.Your service host should print the Seed and Range sent from the client and generate the random number and send it back to the client.



That's it, There you have mine,your first WCF application.FUN !!!









Wednesday, August 1, 2012

asp.net - URL Decode Chinese Characters

I had to work on task where I had to decode a  file with a list of encoded strings.The person who asked me to decode the file also told me that the strings where a bunch of chineese characters and that he did not know how to decode it.
After trying different encodings finally I was able to figure out the encoding "gbk" with which I was able to decode the file.
Here is the code


protected void Page_Load(object sender, EventArgs e)
{
     using(StreamReader oReader = new StreamReader(@"C:\Data\Sample.csv"))
     {
           string sHeader = oReader.ReadLine();
           while (!oReader.EndOfStream)
           {
                string[] sList = oReader.ReadLine().Split(',');
                if (sList[6].Contains('%'))
                {               Response.Write(HttpUtility.UrlDecode(sList[6],Encoding.GetEncoding("gbk")));
                     Response.Write("</br>");
                }
            }
     }
 }