Friday, November 30, 2012

c# - Convert a string to lowercase,uppercase without using builtin functions

LOWERCASE 

try
{
    string s = "This Is A Sentence!!!";
    char[] ca = s.ToCharArray();
    foreach (char c in ca)
    {
       if ((int)c < 91 && (int)c > 64)
          Console.Write(((char)((int)c + 32)));
       else
          Console.Write(c);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}















UPPERCASE

try
{
    string s = "This Is A Sentence!!!";
    char[] ca = s.ToCharArray();
    foreach (char c in ca)
    {
        if ((int)c < 123 && (int)c > 96)
           Console.Write(((char)((int)c - 32)));
        else
           Console.Write(c);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
 
     

Tuesday, November 27, 2012

SSPI handshake failed with error code - SQL Server 2008

If you have worked on SQL Server migration then its likely that you have come across this error message.I recently migrated a server from SQL Server 2005 to SQL Server 2008.Everything seemed to go well except that I started seeing this error message in the SQL Server Log,Event viewer.
























After searching the internet for the causes and trying the fixes, the issue wasn't fixed.Some of the checks I did were to recreate the SPN's,Set the DisableLoopbackCheck registry entry to 1 (Note this fix worked for another server) ,verify NTLM or KERBEROS authentication and so on.

So I decided to contact our DBA and it took 5 minutes to figure out the issue.
First thing was to figure out the offending application.So he ran a trace on Audit Login Events in SQL Profiler

















The account to connect to the report server was not configured correctly and that was causing the error.Once the Report Server was configured the error disappeared.

Open Report Server Configuration Manager



















Configure Report Server Service Account and provide the correct credentials




 The trace now correctly shows that the account login was successful.
Restart the Report Server and now SQL Server Log does not show the SSPI handshake failed error 


SQL Profiler Rocks !!! Hope this helps.

Wednesday, November 21, 2012

Bulk load: An unexpected end of file encountered in the data file - SQL Server

I have a SQL Server job that loads certain columns from a tab delimited text file into a SQL Server database table.The job was working fine until recently it started throwing the below error.






This error occurs when there are null values in the one the columns that you are trying load to the table.In order to fix the issue, the bulk insert command must be run with the 'KEEPNULLS' option.

For more information on the BULK INSERT with KEEPNULLS see the following link. http://msdn.microsoft.com/en-us/library/ms187887.aspx




Friday, November 16, 2012

Linked server was unable to start a distributed transaction - SQL Server

Recently I migrated a server  to Windows Server 2008 and the database from SQL Server 2003 to SQL Server 2008.After the migration one of the web applications started throwing this error.


























To fix this I had to enable the distributed transaction coordinator on the server that application was trying to access.


After I did this the error message changed to MSDTC is unavailable on the server .



To fix this I had to configure the MSDTC on the server that application was trying to access.The steps are listed in the following link.

Screenshots of the above steps is below.





Monday, November 12, 2012

Copy files between servers - Robocopy - Multithreaded option

Previously I have used XCOPY for copying huge files between two windows servers until I came across Robocopy's multithread option

Simplest form of robocopy with this option is below

robocopy source_folder destination_folder f* /MT /S /Z

where f* is all files starting with the letter f in the source_folder and /MT is the mulithreaded option.
Note that /MT automatically uses the total number of processors on the server you run the command.



Wednesday, November 7, 2012

c# - A to Z & a to z

Software Intern Interview question.Print A-Z using a loop

for (int iIndex = 65; iIndex <= 90; iIndex++)
    Console.WriteLine(((char)iIndex).ToString());



for (int iIndex = 97; iIndex <= 122; iIndex++)
     Console.WriteLine(((char)iIndex).ToString());



Friday, November 2, 2012

Copy files between servers - Windows Server

Previously I have always used the windows explorer GUI on the servers to copy files between two server network shares.I started getting errors "Insufficient System Resources to complete the requested service" once I started to copy huge files(20 GB) across the network.
This happens when the paged pool memory is insufficient.You can request IT to tweak the settings to get around the problem.

Instead of the GUI copy/paste option I now use XCOPY command to transfer files from one server to another.
More about xcopy here http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true

Simplest form of the command is  xcopy source destination

Log on the server and bring up the cmd prompt














In the command prompt type the command  

xcopy sourceserver_folderpath destinationserver_folderpath 


Wednesday, October 31, 2012

Named Pipes Provider, error: 40 - Could not open a connection to SQL Server

I started getting this error on one of the applications that I had created.The application was a wcf restful service that was hosted on IIS making a database call.For reasons that I could not understand I started getting this error and it was evident that the owner of the server had tweaked the settings on the database server.

After searching the cause and making sure all the steps listed in the this blog (http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/) were correct, I was still not able to resolve the issue.

So I came up with a workaround.I changed the default protocol in the connection string and Voila!!! it works now without any issues
Here is the previous and current connection strings


<add name="Production" connectionString="Persist Security Info=False;User ID=username;Password=password;Initial Catalog=databasename;Data Source=servername" />

<add name="Production" connectionString="Persist Security Info=False;User ID=username;Password=password;Initial Catalog=databasename;Data Source=tcp:servername,1434" />

*Note that owner of the server was using 1434 port number for tcp protocol.

Hope it helps !!!


Monday, October 15, 2012

c# - Small letters,capital letters,vowels in a string

I came across a forum post where the person wanted to count all the 
  1. small letters in a string
  2. capital letters in a string
  3. vowels in a string
This reminded me of my lab assignments from programming 101 days.Here is the basic code

                Console.WriteLine("Please enter a string");
                string myString = Console.ReadLine();
                byte[] ASCIIBytes = Encoding.ASCII.GetBytes(myString);
                int iSmallCount = 0;
                int iCapsCount = 0;
                int iVowelCount = 0;
                foreach (byte ASCII in ASCIIBytes)
                {
                    if (ASCII >= 65 && ASCII <= 90)
                        iCapsCount++;
                    else if (ASCII >= 97 && ASCII <= 122)
                        iSmallCount++;

                    switch (ASCII)
                    {
                        case 65:
                        case 69:
                        case 73:
                        case 79:
                        case 85:
                        case 97:
                        case 101:
                        case 105:
                        case 111:
                        case 117:
                            iVowelCount++;
                            break;
                    }
                }
                Console.WriteLine("Number of small letters in the entered string: " + iSmallCount);
                Console.WriteLine("Number of cap letters in the entered string: " + iCapsCount);
                Console.WriteLine("Number of vowel letters in the entered string: " + iVowelCount);


Friday, October 12, 2012

c# - Managed Multithreading to archive text files

I have a process that generates large text files on a daily basis.The data for these files come from different sources.The files are then loaded to the warehouse.Once the data is loaded to the warehouse the files are of no use and we usually delete them after a certain number of days based on the retention policy.In order to save space on the file server I have an archival process that zips up these files.

I had used GZipStream from .Net framework for most of my archival programs, however the .net framework GZipStream is limited for files of size 4 GB.More about .Net GZipStream here http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx

I use ICSharpCode.dll for archival program and it is a free library available for download here
http://www.icsharpcode.net/opensource/sharpziplib/. There are plenty of examples on the site as well.

Below is code for a managed multi threaded archival program that zips up all the text files in a given folder.The number of threads depends on the number of processor the server has and is controlled from a configuration file.Make sure to reference the dll in your project and import it to the program using the using statement


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;

namespace ZipFiles

{
    class Program
    {
        public static int iZipFileQueue = 0;
        public static int iMaxThreads = int.Parse(ConfigurationSettings.AppSettings["MAX_THREADS"]);
        static void Main(string[] args)
        {
            string sInputFolderPath = ConfigurationSettings.AppSettings["INPUT_FOLDER_PATH"];
            string sLogFilePath = ConfigurationSettings.AppSettings["LOG_FILE_PATH"];
            using (StreamWriter oWriter = new StreamWriter(sLogFilePath))
            {
                try
                {
                    Console.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Zip file started.");
                    oWriter.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Zip file started.");
                    DirectoryInfo oDirectoryInfo = new DirectoryInfo(sInputFolderPath);
                    foreach (FileInfo oFileInfo in oDirectoryInfo.GetFiles())
                    {
                        if (oFileInfo.Extension.Equals(".txt"))
                        {
                            oWriter.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Started zipping file " + oFileInfo.Name);
                            Console.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Started zipping file " + oFileInfo.Name);
                            ZipFile(oFileInfo);
                            oWriter.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Finished zipping file " + oFileInfo.Name);
                            Console.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Finished zipping file " + oFileInfo.Name);
                        }
                    }

                }

                catch (Exception ex)
                {
                    oWriter.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), ex.Message);
                    Console.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), ex.Message);
                }
                Console.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Zip file finished.");
                oWriter.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Zip file finished.");
            }
            while (iZipFileQueue >0)
            {
                Thread.Sleep(30000);
            }
        }

        private static void ZipFile(FileInfo oFileInfo)

        {
            while (iZipFileQueue >= iMaxThreads)
            {
                Thread.Sleep(30000);
            }
            FileCompress oFileCompress = new FileCompress(oFileInfo);
            if (ThreadPool.QueueUserWorkItem(new WaitCallback(CompressFile), oFileCompress))
            {
                Console.WriteLine("TIMESTAMP:{0} INFO:{1}", DateTime.Now.ToString(), "Started compressing " + oFileInfo.Name);
                iZipFileQueue++;
            }
        }
        public static void CompressFile(object p_oFileCompress)
        {
            try
            {
                FileCompress oFileCompress = (FileCompress)p_oFileCompress;
                oFileCompress.CompressFile();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            iZipFileQueue--;
        }
        
    }
    public class FileCompress
    {
        FileInfo oFileInfo;
        public FileCompress() { }
        public FileCompress(FileInfo p_oFileInfo)
        {
            oFileInfo = p_oFileInfo;
        }

        public void CompressFile()

        {
            byte[] buffer = new byte[int.Parse(ConfigurationSettings.AppSettings["BUFFER_SIZE"])];
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(oFileInfo.FullName.Replace(".txt", ".zip")));
            oZipStream.SetLevel(9);
            ZipEntry zipEntry = new ZipEntry(oFileInfo.Name);
            try
            {
                oZipStream.PutNextEntry(zipEntry);

                using (FileStream stream = File.OpenRead(oFileInfo.FullName))

                {
                    int data = 0;
                    while ((data = stream.Read(buffer, 0, buffer.Length)) > 0)
                        oZipStream.Write(buffer, 0, data);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                oZipStream.Close();
            }
        }
    }
}

Wednesday, September 12, 2012

asp.net - asp:scriptmanager is not a known element

You will get this error if the below assembly reference is missing in the web.config file when you add an asp.net script manager to the page.Add this to the assembly section of the web.config file.

<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

Thursday, September 6, 2012

c# - Ping production servers and send email notifications

Recently I had posted code to check whether production database SQL server service is running or not and send email notification if any of the SQL Server database server is down.I wanted a similar email alert for my production servers.I maintain about 21 servers which are used as web servers,file servers,database servers and so on.

The below code pings a list of servers and if any of the server is down then it will send an email notification.I have created a scheduled task out of this exe and this scheduled task runs every 10 minutes and  sends email alerts if any server is unreachable to the ping command.


using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Configuration;
using System.Net.Mail;

namespace PingServer

{
    public class PingExample
    {
        
        public static void Main(string[] args)
        {
            try
            {
                Ping ping = new Ping();
                string sServers = ConfigurationManager.AppSettings["SERVER_LIST"];
                string [] sServerList = sServers.Split(',');
                foreach (string server in sServerList)
                {
                    try
                    {
                        PingReply reply = ping.Send(server);
                        if (reply.Status == IPStatus.Success)
                            Console.WriteLine("Server " + server + " running");
                        else
                        {
                            Console.WriteLine("Server " + server + " down");
                            SendMail("Server " + server + " down", "SERVER_STATUS", new string[] { "me@mycompany.com", "mymanager@mycompany.com" });
                        }
                    }
                    catch
                    {
                        Console.WriteLine(server + " is not reachable.Exception raised by ping.Send()");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
        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.me.mycompany.com");

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

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