Wednesday, March 13, 2013

Use XPathDocument if you have plan to work with XPath Queries rather than XmlDocument

Don't use the XmlDocument class if you are going to work with XPath queries. .NET has its own class for this purpose called XPathDocument, which does not run any validation checking. When using XPath, avoid using to reduce the search, because searches the complete document.

XPathDocument Doc = new XPathDocument(FileName);
XPathNavigator nav = Doc.CreateNavigator();
XPathNodeIterator Iterator = nav.Select("/bookstore/book");
while (Iterator.MoveNext())
{
   Console.WriteLine(Iterator.Current.Name);
}

Get the list of installed drivers from command prompt

driverquery /v

Task Manager Tips

  • Hit Ctrl+Alt+Del and click on Task Manager
  • Hit Ctrl+Shift+Esc to bring up Task Manager

Catch a key stroke before the actual control

// KeyDown event of some control
private void SomeControl_KeyDown(object sender, KeyEventArgs e)
{
    // 1. Event is called directly after the key stroke
    // If the user hits Enter, we catch the
    // event and do our own things
    if (e.KeyCode == Keys.Enter)
    {
        // Suppress key stroke, so that
        // the control don't receives it
        e.SuppressKeyPress = true;
        // Perform something important...
    }
}
// KeyPress event of some control
private void SomeControl_KeyPress(object sender, KeyPressEventArgs e)
{
    // 2. Event is called during the key stroke
}
// KeyUp event of some control
private void SomeControl_KeyUp(object sender, KeyEventArgs e)
{
    // 3. Event is called after the key stroke 
}

String Comparision Performance Test

Comparasion done Replacing String.Compare with the below listed priorities.

we can priorities as follows:
  1. a == b - the most efficient and visual style
  2. String.Equals(a,b) - equally efficient but pain to read from the code
  3. a.Equals(b) - not fast but more sane than the Object one
  4. Object.Equals(a,b) - very obscure way to compare strings
  5. String.Compare(a,b)==0 - bad way to check equality
I have done a performance test below are the results.
 
Time Taken for comparing 100000000 Strings:

Time taken by == comparison 484 milliseconds
Time taken by CompareOrdinal method 537 milliseconds
Time taken by String.Compare method 18076 milliseconds
Time taken by String.Equals method 490 milliseconds

Enable mouse scroll-wheel in VB6


VB6 would let us use the mouse scroll-wheel like later versions of VS does. Here's a add-in for VB6 that I have used that does just that!

Download \Visual Basic 6\vb6mousewheel\VB6MOU~1 from Microsoft web site

·         Copy the VB6IDEMouseWheelAddin.dll to somewhere on your local machine where it won’t get deleted. I use “C:\Program Files\Microsoft Visual Studio 6”.

·         Click Start, click Run, type regsvr32 \VB6IDEMouseWheelAddin.dll, and then click OK.

·         Start Visual Basic 6.0.

·         Click Add-Ins, and then click Add-in Manager.

·         In the Add-in Manager list, click MouseWheel Fix.

·         Click to select the Loaded/Unloaded check box, and then click to select the Load on Startup check box.

·         Click OK.

Online C++ Compiler

Please find the Online Compiler for running C++ and other different programs: http://codepad.org. Below is the sample template code for C++:

#include
using namespace std;

int  main()
{

 char str[10];

 sprintf(str,"%3d%2d",311,12);

 cout<

 cout<

 return 0;

}

Optimal Enum to String Convertion

public static String ConvertToString(this Enum eff) {
     return Enum.GetName(eff.GetType(), eff);
}


Filling, Fetching and Removing HttpRuntime.Cache

public static void FillCache(string strCacheKey, object cacheObject)
{
    HttpRuntime.Cache.Insert(strCacheKey, cacheObject, null, DateTime.MaxValue, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, null);
}

public static object GetCache(string cacheKey)
{
    object cacheObject = null;
    if (HttpRuntime.Cache[cacheKey] != null)
    {
        cacheObject = HttpRuntime.Cache[cacheKey];
    }
    return cacheObject;
}

public static bool RemoveCache(string cacheKey)
{
    bool isRemoved = false;
    if (HttpRuntime.Cache[cacheKey] != null)
    {
        HttpRuntime.Cache.Remove(cacheKey);
        isRemoved = true;
    }
    return isRemoved;
}

Using StackFrame Class to get the stack information

using System.Diagnostics;
...

//Gets the file name that contains the code that is executing. This information is typically extracted from the debugging symbols for the executable.
public static int GetFileLineNumber()
{
    StackFrame s = new StackFrame(1, true);
    return s.GetFileLineNumber();
}


//Gets the method in which the frame is executing.
public static string GetMethod()
{
    StackFrame s = new StackFrame(1, true);
    return s.GetMethod().Name;
}


//Gets the file name that contains the code that is executing. This information is typically extracted from the debugging symbols for the executable.
public static string GetFileName()
{
    StackFrame s = new StackFrame(1, true);
    return s.GetFileName();
}


Read: http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.aspx

Serializing and Deserializing Object using XmlSerializer

public static string SerializeObject(T value)
{
    if (value == null)
    {
        return null;
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Encoding = new UnicodeEncoding(false, false);
    settings.Indent = false;
    settings.OmitXmlDeclaration = false;
    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, value);
        }
        return textWriter.ToString();
    }
}

public static T DeserializeObject(string xml)
{
    if (string.IsNullOrEmpty(xml))
    {
        return default(T);
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlReaderSettings settings = new XmlReaderSettings();
    using (StringReader textReader = new StringReader(xml))
    {
        using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }

Server.GetLastError that occurred

Exception ex= Server.GetLastError();
string error = ex.Message;

Regular expression to verify that a string contains between 1 and 40

Regex r = new Regex(@"^[\w]{1,40}$");
       
if (r.Match(strName).Success)
{
    // Valid
}
else
{
    // Not Valid
}

Give voice to your computer

Add a reference to the SAPI from COM tab, and select "Microsoft Speech Object Library"


using SpeechLib;
...
SpVoice voice = new SpVoice();
voice.Speak(rtbSpeachText.Text, SpeechVoiceSpeakFlags.SVSFDefault);

Using Clipboard

Clipboard.SetText(txtClipboard.Text);
txtClipboard.Text = Clipboard.GetText();
Clipboard.Clear();

//get the selected image into clipboard
OpenFileDialog selImage;

if (selImage.ShowDialog() == DialogResult.OK)
{
    Image myImage = Image.FromFile(selImage.FileName);
  Clipboard.SetImage(myImage);
}

clipBoardImage.Image = Clipboard.GetImage();

Lock, Stand By, Hibernate and Log Off your System

using System.Runtime.InteropServices;

//Locking the system
[DllImport("user32.dll")]
public static extern void LockWorkStation();


LockWorkStation();
Application.SetSuspendState(PowerState.Suspend, true, true);

//Making system stand by and hibernation

Application.SetSuspendState(PowerState.Suspend, true, true);
Application.SetSuspendState(PowerState.Hibernate, true, true);

//Log off the user

[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int uFlags, int dwReason);

ExitWindowsEx(0, 0);

Get the Cursor Position

using System.Runtime.InteropServices;

[DllImport("user32.dll")]
static extern bool GetCursorPos(ref Point lpPoint);

Point defPnt = new Point();
GetCursorPos(ref defPnt);

string CoordinatesXnY  = "X = " + defPnt.X.ToString() + "Y = " + defPnt.Y.ToString();

Using URI Class

using System.Net;
...
Uri uri = new Uri(txtURI.Text);
txtURI.AppendText("Absolute URI: " + uri.AbsoluteUri + "\r\n");
txtURI.AppendText("Absolute Path: " + uri.AbsolutePath + "\r\n");
txtURI.AppendText("Local path: " + uri.LocalPath + "\r\n");
txtURI.AppendText("Scheme: " + uri.Scheme + "\r\n");
txtURI.AppendText("Authority: " + uri.Authority + "\r\n");
txtURI.AppendText("Host: " + uri.Host + "\r\n");
txtURI.AppendText("Port: " + uri.Port + "\r\n");
txtURI.AppendText("Fragment: " + uri.Fragment + "\r\n");
txtURI.AppendText("Query: " + uri.Query + "\r\n");
//Get absolute URI from a base and relative URI
Uri uriBase = new Uri(“https://sites.google.com/site/BarqKadapavi”);
Uri absoluteUri = new Uri(uriBase, “Images/MyImages.htm”);
txtAbsolute.Text = absoluteUri.ToString();

Get a list of installed printers

using System.Drawing.Printing;
...
  
// Loop through the string collection of printers
foreach (string strPrinter in PrinterSettings.InstalledPrinters)
{
    // Show the name of the printer
    MessageBox.Show(strPrinter);
}

Get the list of thread of a process

using System.Diagnostics;
...
ProcessThreadCollection threadlist = theProcess.Threads;
foreach(ProcessThread theThread in threadlist)
{
   Console.WriteLine("Thread ID:{0} Priority: {1} Started: {2}",   theThread.Id, theThread.PriorityLevel, theThread.StartTime);
}

Get the running processes

using System.Diagnostics;
...
...
Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist)
{
 Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
//properties of the Process object
p.StartTime   (Shows the time the process started)
p.TotalProcessorTime  (Shows the amount of CPU time the process has taken)
p.Threads   (gives access to the collection of threads in the process)

Get the files of the users startup menu

        Dim theFiles As String()
        theFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "*", SearchOption.AllDirectories)
        Dim i As Integer
        For i = 0 To (theFiles.Length - 1)
            MsgBox(theFiles(i).ToString())
        Next

Using Environment.SpecialFolder to get the files of MyPictures folder

We can use the Environment.SpecialFolder enum in .NET to locate special folders like MyDocuments, MyPictures, MyMusic, MyComputer, Fonts, History, Desktop, Programs, StartMenu, Startup, and so on… We can see all of them in the Environment.SpecialFolder IntelliSense.

        Dim theFiles As String()
        theFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "*", SearchOption.AllDirectories)
        Dim i As Integer
        For i = 0 To (theFiles.Length - 1)
            Console.WriteLine(theFiles(i).ToString())
        Next

Get the Client-side/Browser Information

StringBuilder sbBrowserInfo = new StringBuilder();
sbBrowserInfo.Append("
Client Language Preferences");
string Lang = Request.UserLanguages[0];
int count;
String[] userLang = Request.UserLanguages;

for (count = 0; count < userLang.Length; count++)
{
    sbBrowserInfo.Append("
User Language " + Convert.ToInt32(count + 1) + ": " + userLang[count]);
}

sbBrowserInfo.Append("

General Browser Info
");
sbBrowserInfo.Append("RequestType=" + Request.RequestType.ToString() + "
");
sbBrowserInfo.Append("EcmaScriptVersion=" + Request.Browser.EcmaScriptVersion.ToString() + " *Major version greater than or equal to 1 implies JavaScript Support" + "
");
sbBrowserInfo.Append("Browser Type=" + Request.Browser.Type.ToString() + " Client=" + Request.UserAgent + "
");
sbBrowserInfo.Append("UserHostAddress=" + Server.HtmlEncode(Request.UserHostAddress) + "
");
sbBrowserInfo.Append("Table Support=" + Request.Browser.Tables.ToString() + "
");
sbBrowserInfo.Append("UserHostAddress=" + Server.HtmlEncode(Request.UserHostAddress) + "
");
sbBrowserInfo.Append("UserHostName=" + Server.HtmlEncode(Request.UserHostName) + "
");
sbBrowserInfo.Append("HttpMethod=" + Server.HtmlEncode(Request.HttpMethod) + "
");
sbBrowserInfo.Append("Support Java=" + Request.Browser.JavaApplets.ToString() + "
");
sbBrowserInfo.Append("Support HTML Frames=" + Request.Browser.Frames.ToString() + "
");
sbBrowserInfo.Append("Support Cookies=" + Request.Browser.Cookies.ToString() + "
");
sbBrowserInfo.Append(".Net Framework Version Installed=" + Request.Browser.ClrVersion.ToString() + "
");
sbBrowserInfo.Append("Support Channel Definition Format for webcasting=" + Request.Browser.CDF.ToString() + "
");
sbBrowserInfo.Append("Support ActiveXControls=" + Request.Browser.ActiveXControls.ToString() + "
");  //Support
sbBrowserInfo.Append("Support VBScript=" + Request.Browser.VBScript.ToString() + "
");
sbBrowserInfo.Append("Virtual Path of the request=" + Request.FilePath.ToString() + "
");
sbBrowserInfo.Append("Platform=" + Request.Browser.Platform + "
");
sbBrowserInfo.Append("Browser.Win16=" + Request.Browser.Win16 + "
");
sbBrowserInfo.Append("Browser.Win32=" + Request.Browser.Win32 + "
");
sbBrowserInfo.Append("ApplicationPath=" + Request.ApplicationPath + "
");

if (Request.UrlReferrer != null)
{
    sbBrowserInfo.Append("Referring URL Properties
");
    sbBrowserInfo.Append("AbsolutePath=" + Request.UrlReferrer.AbsolutePath + "
");
    sbBrowserInfo.Append("AbsoluteURI=" + Request.UrlReferrer.AbsoluteUri + "
");
    sbBrowserInfo.Append("Authority=" + Request.UrlReferrer.Authority + "
");
    sbBrowserInfo.Append("LocalPath=" + Request.UrlReferrer.LocalPath + "
");
    sbBrowserInfo.Append("Port=" + Request.UrlReferrer.Port + "
");
    sbBrowserInfo.Append("Scheme=" + Request.UrlReferrer.Scheme + "
");
    sbBrowserInfo.Append("UserInfo=" + Request.UrlReferrer.UserInfo + "
");
}

sbBrowserInfo.Append("
More Browser Information
");
foreach (String item in Request.ServerVariables)
    sbBrowserInfo.Append(item + "=" + Request.ServerVariables[item] + "
");

divGeneralInfo.InnerHtml = sbBrowserInfo.ToString();

Execute an .exe and get the output returned by an .exe

System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "C:\\MyExe.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = false;
myProcess.StartInfo.RedirectStandardInput = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.Start();

StreamReader sOut = myProcess.StandardOutput;
StreamReader sErr = myProcess.StandardError;

myProcess.WaitForExit();
string output = sOut.ReadToEnd();

textBox1.Text = output;

Using volatile Modifier

The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Marking a field as volatile would make sure that it is not cached dur¬ing the exe¬cu¬tion of a thread.

public volatile int i;

C# jump statements

break;
continue;
goto identifier;
goto case constant-expression;
goto default;
return [expression];
throw [ expressionopt];

Check your application’s running location and user rights

//Get the running drive of this application
Console.WriteLine(Directory.GetDirectoryRoot(Assembly.GetExecutingAssembly().Location));
String sddlAdmins = "S-1-5-32-544";  //Sid of administrators group
IdentityReference AdminsSid = new SecurityIdentifier(sddlAdmins);
if (WindowsIdentity.GetCurrent().Groups.Contains(AdminsSid))
    Console.WriteLine("Running with admin rights!");

C# code to Check IE Proxy Settings

private static void CheckIEProxySettings()
{
    string strFileURL = "http://programmersvision.blogspot.in";
    HttpWebRequest WebReqt = (HttpWebRequest)HttpWebRequest.Create(strFileURL);
    WebProxy WP = new WebProxy(WebReqt.Proxy.GetProxy(new Uri(strFileURL)));
    WP.Credentials = CredentialCache.DefaultCredentials;
    Console.WriteLine(WP.Address);
    // or use this method
    //CheckForProxy(new Uri("http://http://programmersvision.blogspot.in"));
}

private static void CheckForProxy(Uri resource)
{
    WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();
    Uri proxyUri = proxy.GetProxy(resource);
    if (proxyUri == resource)
    {
        Console.WriteLine("There is no proxy for {0}", resource);
    }
    else
    {
        Console.WriteLine("Proxy for {0} is {1}", resource, proxyUri.ToString());
    }
}

Getting the _EVENTTARGET hidden field

string controlName = Request.Params.Get("__EVENTTARGET");

Using SMO

Here is the useful code to get the list of servers available on my network using SMO.

        DataTable dtSQLServers = SmoApplication.EnumAvailableSqlServers(false);
        SQLServers.DataSource = dtSQLServers;
        SQLServers.DataBind();


        //Get the local server name
        Server LocalServer = new Server();
        String LocalServerName = LocalServer.Name;
        //Check if the server has any instance, concatinate if an instance exists
        if (LocalServer.InstanceName != null && LocalServer.InstanceName.Length > 0)
            LocalServerName = @"\" + LocalServer.InstanceName;
 

EventLog ModifyOverflowPolicy

   EventLog log = new EventLog(LogName);
   log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 7);
   log.MaximumKilobytes = 640000;

Read: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.modifyoverflowpolicy.aspx

Populating data in multiple columns using WinForms ListView

In this article, I would like to discuss a brief on how to bind data in multiple columns using ListView in WinForms.  It is preferable to go for a ListView rather than a ListBox in Winforms to bind multiple columns. Below is the little tricky code to do so:

// Adding ListView Columns
lstView.Columns.Add("Id", 245, HorizontalAlignment.Left);
lstView.Columns.Add("Name", 241, HorizontalAlignment.Left);
lstView.Columns.Add("Mobile Number", 245, HorizontalAlignment.Left);

// Getting the data to a datasource
DataTable dt = businessComponent.GetData(Id);

string[] Str = new string[3];
ListViewItem newItm;
foreach (DataRow dataRow in dt.Rows)
{
           Str[0] = dataRow["Id"].ToString();
           Str[1] = dataRow["Name"].ToString();
           Str[2] = dataRow["Mobile"].ToString();
           newItm = new ListViewItem(Str);
           lstView.Items.Add(newItm);
}

To show the data in Details form (tabular form) we need to set ‘View’ property of the ListView to Details. By default it is set to LargeIcon  out of the 5 values - LargeIcon, Details, SmallIcon, List, Tile.
We can do many more customizations for ListView, like setting the width of the columns, colors, fonts, etc  with ListView as it is designed to display the data.

Adding a Page break to the web page when we need to print to a different page.




C# Code to Generate Word Document from a Web Page

protected void Generate_Click(object sender, EventArgs e)
{
    string str = "
http://www.google.co.in/";
    HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(str);
    HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();

    // Make sure the response is valid
    byte[] MyBuffer = null;

    // Make sure the response is valid
    if (HttpStatusCode.OK == MyResponse.StatusCode)
    {
        // Open the response stream
        using (Stream MyResponseStream = MyResponse.GetResponseStream())
        {
            byte[] buffer = new byte[10000];

            using (MemoryStream memoryStream = new MemoryStream())
            {
                int
                count = 0;

                do
                {
                    count = MyResponseStream.Read(buffer, 0, buffer.Length);
                    memoryStream.Write(buffer, 0, count);
                }
                while (count != 0);
                MyBuffer = memoryStream.ToArray();
            }
        }
    }
    Response.ContentType = "application/ms-word";
    Response.AddHeader("content-Disposition", "attachment; filename=GhouseBarqSample.doc");
    Response.BinaryWrite(MyBuffer);
    Response.Flush();
    Response.Close();
    Response.ClearHeaders();
    Response.End();
}

Oracle vs SQL Server Datatype Mapping


SQL Server Data Type       Oracle Data Type

VARCHAR                    VARCHAR2

MONEY                      NUMBER(19,4)

BIT                        NUMBER(1,0)

IMAGE                      BLOB

SYSNAME                    VARCHAR2(128)

VARCHAR(MAX)               CLOB

DATETIME                   TIMESTAMP(3)

DECIMAL                    NUMBER

TINYINT                    NUMBER(3,0)

FLOAT                      NUMBER

CHAR                       CHAR

UNIQUEIDENTIFIER           CHAR(36)

BIGINT                     NUMBER(10,0)

INT                        NUMBER(10,0)

NUMBERIC                   NUMBER

NVARCHAR(MAX)              NCLOB

SMALLMONEY                 NUMBER(10,4)

NVARCHAR                   NVARCHAR2

TEXT                       CLOB
 

Error - DataContractAttribute could not be found

The type or namespace name 'DataContractAttribute' could not be found
(are you missing a using directive or an assembly reference?)
The type or namespace name 'DataContract' could not be found (are you
missing a using directive or an assembly reference?)
The type or namespace name 'DataMemberAttribute' could not be found
(are you missing a using directive or an assembly reference?)
The type or namespace name 'DataMember' could not be found (are you
missing a using directive or an assembly reference?)


Solution:

You're just missing a reference to "System.Runtime.Serialization". It's a built-in .NET library, so you can find it under the ".NET" tab of your add references dialog.


 

Convert XElement to DataTable

public DataTable XElementToDataTable(XElement x)
 {
   DataTable dt = new DataTable();

  XElement setup = (from p in x.Descendants() select p).First();
   foreach (XElement xe in setup.Descendants()) // build your DataTable
     dt.Columns.Add(new DataColumn(xe.Name.ToString(),typeof(string))); // add columns to your dt

  var all = from p in x.Descendants(setup.Name.ToString()) select p;
   foreach (XElement xe in all)
   {
     DataRow dr = dt.NewRow();
     foreach (XElement xe2 in xe.Descendants())
       dr[xe2.Name.ToString()] = xe2.Value; //add in the values
     dt.Rows.Add(dr);
   }
   return dt;
 }

Solution for the error in a multi threaded environment. Error: The process cannot access the file 'D:\[File].log' because it is being used by another process

In a multi threaded environment if you call a below WriteLog() function you will get the below error:
Error: "The process cannot access the file 'D:\Error.log' because it is being used by another process."
            public void WriteLog(string msg)
            {
                using (StreamWriter sw = File.AppendText("D:\\Error.log"))
                {
                    sw.Write(msg);
                    sw.Close();
                }
            }

To resolve this issue, It is recommended to lock on a separate simple object. This reduces the risk of anything else locking on the same object. Below is the example:
            static readonly object writerLock = new object();
            public void WriteLog(string msg)
            {
                lock (writerLock)
                {
                    using (StreamWriter sw = File.AppendText("D:\\Error.log"))
                    {
                        sw.Write(msg);
                        sw.Close();
                    }
                }
            }

Performance analysis of Enum.Parse vs Enum.TryParse

For the scenerio I am testing, for the below two approaches I found that approach I is better performing than the Approach II.

     //Approach I
            for (int i = 0; i < 100000; i++)
            {
                EnumRepository eRepository1 = (EnumRepository)Enum.Parse(typeof(ECCRepository), "GHOUSE");
            }
           
            //Approach II
            for (int i = 0; i < 100000; i++)
            {
                EnumRepository eRepository;
                Enum.TryParse("GHOUSE", out eRepository);
            }

            stopwatch.Stop();
            long timespan1 = stopwatch.ElapsedTicks;
            TimeSpan timespan2 = stopwatch.Elapsed;

            Console.WriteLine("Time taken:" + timespan1);

Performance of 'is' vs typeof (Reflection) in C#

Stopwatch s = new Stopwatch();
            s.Start();

            for (int i = 0; i < 100000000; i++)
            {
                CNDSegment segment = new CNDSegment();
                if (segment is CNDSegment == false)
                {

                }
            }
            s.Stop();

            Console.WriteLine(String.Format("Time taken by is {0} milliseconds", s.ElapsedMilliseconds));
            s.Reset();
            s.Start();

            for (int i = 0; i < 100000000; i++)
            {
                CNDSegment segment = new CNDSegment();
                if (segment.GetType() != typeof(CNDSegment))
                {

                }
            }

            s.Stop();
            Console.WriteLine(String.Format("Time taken by GetType and typeof method {0} milliseconds", s.ElapsedMilliseconds));

Performance results for 100000000 comparisions
Time taken by is 1338 milliseconds
Time taken by GetType and typeof method 5050 milliseconds

‘as’ versus type casting

Prefix casting vs as casting

Stopwatch s = new Stopwatch();
            s.Start();

            for (int i = 0; i < 100000000; i++)
            {
                object myClass = new CNDSegment();
                ((CNDSegment)myClass).Method1();
            }
            s.Stop();

            Console.WriteLine(String.Format("Time taken by prefix casting is {0} milliseconds", s.ElapsedMilliseconds));
            s.Reset();
            s.Start();

            for (int i = 0; i < 100000000; i++)
            {
                object myClass = new CNDSegment();
                (myClass as CNDSegment).Method1();
            }

            s.Stop();
            Console.WriteLine(String.Format("Time taken by as casting and typeof method {0} milliseconds", s.ElapsedMilliseconds));

            Console.ReadLine();

Time taken by prefix casting is 1406 milliseconds
Time taken by as casting and typeof method 1338 milliseconds

Read this:
http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in#_rating
http://gen5.info/q/2008/06/13/prefix-casting-versus-as-casting-in-c/

LINQ is for querying rather than updating..

LINQ is for querying rather than updating. However, that can be used to build a new list:

Stopwatch s = new Stopwatch();
            s.Start();

            cndSegmentList.FindAll(a => a is PublicRecord == false).ForEach(b => b.SegName = "Mohammed");
            s.Stop();
            Console.WriteLine(String.Format("Time taken by LINQ foreach is {0} milliseconds", s.Elapsed));
            Console.WriteLine(String.Format("Time taken by LINQ foreach is {0} milliseconds", s.ElapsedTicks));

            s.Reset();
            s.Start();

            foreach (CNDSegment segment in cndSegmentList)
            {
                if (segment is PublicRecord == false)
                    segment.SegName = "Mohammed";
            }

            s.Stop();
            Console.WriteLine(String.Format("Time taken by normal foreach is {0} milliseconds", s.Elapsed));
            Console.WriteLine(String.Format("Time taken by normal foreach is {0} milliseconds", s.ElapsedTicks));


Time taken by LINQ foreach is 00:00:00.0002578 milliseconds
Time taken by LINQ foreach is 603 ElapsedTicks
Time taken by normal foreach is 00:00:00.0000059 milliseconds
Time taken by normal foreach is 14 ElapsedTicks

Checking the Performance of GetNumericValue vs ConvertInt32Default

            Stopwatch w = new Stopwatch();
            w.Start();
            for (int i = 0; i < 10000000; i++)
            {
                if (Char.GetNumericValue('1') > 0)
                {
                }
            }

            w.Stop();
            Console.WriteLine("GetNumericValue Approach = " + w.ElapsedTicks);
            w.Reset();
            w.Start();
            for (int i = 0; i < 10000000; i++)
            {
                if (ConvertInt32Default('1') > 0)
                {

                }
            }
            w.Stop();
            Console.WriteLine("ConvertInt32Default Approach = " + w.ElapsedTicks);
           
            Console.ReadLine();


public static System.Int32 ConvertInt32Default(char input)
        {
            System.Int32 value;

            bool status = int.TryParse(input.ToString(), out value);
            if (status == true)
                return value;
            else
                return default(System.Int32);
        }


Output:
GetNumericValue Approach = 337396
ConvertInt32Default Approach = 3653561

Show all assemblies loaded by C# program

using System;
using System.Text;
using System.Reflection;


namespace AssemblyListing
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain MyDomain = AppDomain.CurrentDomain;
            Assembly[] AssembliesLoaded = MyDomain.GetAssemblies();

            foreach (Assembly MyAssembly in AssembliesLoaded)
            {
                Console.WriteLine("Loaded: {0}", MyAssembly.FullName);
            }
        }
    }
}

Checking the Performance of Enum.GetName vs ToString

            Stopwatch w = new Stopwatch();
            w.Start();
            for (int i = 0; i < 10000; i++)
            {
                string ghouse = Enum.GetName(tableName.GetType(), tableName);
            }

            w.Stop();
            Console.WriteLine("I time  = " + w.ElapsedTicks);
            w.Reset();
            w.Start();
            for (int i = 0; i < 10000; i++)
            {
                string ghouse = tableName.ToString();
            }
            w.Stop();
            Console.WriteLine("II time = " + w.ElapsedTicks);


Output
I time  = 24606
II time = 38881

How to get C# Enum description from value?

How to get C# Enum description from value?
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum in C# is an int, you can just cast it.
Read this: https://code.google.com/p/unconstrained-melody/

Changing the Geom value to text

declare @geom geometry
set @geom = Geometry::STGeomFromText('MULTIPOINT ((' + CAST(@lon AS varchar(20)) + ' ' + CAST(@lat AS varchar(20)) + '))',4326)

Table space used in sql server

CREATE TABLE dbo.Geo
(
    geo geography

)

GO

CREATE TABLE dbo.LatLon
(
    lat decimal(9, 6)
,   lon decimal(9, 6)

)

GO

INSERT dbo.Geo
SELECT geography::Point(36.204824, 138.252924, 4326) UNION ALL
SELECT geography::Point(51.5220066, -0.0717512, 4326) 

GO 10000

INSERT dbo.LatLon
SELECT  36.204824, 138.252924 UNION
SELECT 51.5220066, -0.0717512

GO 10000

EXEC sp_spaceused 'dbo.Geo'
EXEC sp_spaceused 'dbo.LatLon'

DataContract Serialization and Deserialization functions

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

Code snippet in VB.Net to split the Name eg. = "Mohammed Ghouse" to FirstName and LastName

If Not String.IsNullOrEmpty(element.Name) Then
    If element.Name.IndexOf(" ") = -1 Then
        eContact.FirstName = element.Name
    Else
        eContact.FirstName = element.Name.Substring(0, element.Name.IndexOf(" "))
        eContact.LastName = element.Name.Substring(element.Name.IndexOf(" ") + 1)
    End If
End If

Resolution for System.IO.FileNotFoundException: Could not find file 'C:\WINDOWS\TEMP\[SomeFileName].dll


I was getting the below errors randomly for each user make a first time call to the service. I tried recycling, restarting IIS, commented the newly added xmlserialization call to Log, but nothing worked. Then I looked further it’s the machine ran out of temp file storage space, so rebooting server and cleaning temp file solved the issue. 

*******************************************************************************************

[ERROR]  System.IO.FileNotFoundException: Could not find file 'C:\WINDOWS\TEMP\ekglwclt.dll'.  File name: 'C:\WINDOWS\TEMP\ekglwclt.dll'     at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)     at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)     at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)     at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)     at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)     at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)     at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)     at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)     at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)     at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)     at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)     at Credco.Business.Common.Serialize(Object obj)     at Credco.Business.Log.LogEvent(LogTypes LogType, IList obj)     at Credco.DataManagement.Server.BillingReport.GetFormatList(EnhancedBindingList`1& formatList)     at Credco.DataManagement.Server.Web.DataManagement.GetBillingReportFormatList(UserToken userToken, EnhancedBindingList`1& billingReportFormatList)

*******************************************************************************************
 
Hope that helps someone.