Wednesday, August 21, 2013

Three simple tricks for better C# code

Here are 3 tricks that once you start using them can save you a lot of typing when dealing with C#.


1. The Null Coalescing Operator (??) This is a short-cut for the ternary operator (?:) checking against a null:
string name = value;  
      
   if (value == null)  
   {  
     name = string.Empty;  
   }  
Can now be condensed into one line:
 string name = value ?? string.Empty;  
2. Auto properties There is no need to define a variable for simple backing fields for most properties in C#. In fact most things like int, strings, double i just let the compiler handle it.
 public class MyPoint  
   {  
    public int X { get; set; }  
    public int Y { get; set; }  
  }  
3. Is vs As You should try and avoid the is operator when you can do an as cast. The is requires two casts where the as does just one. Even with the added null check it's always going to be faster to do an as vs is.
 var sq = Square as Shape;  
   if ( sq != null )  
   {  
     volume = sq.CalculateVolume();  
     // ...  
  }  

Thursday, March 28, 2013

ASP.NET User Control with Template Content

Asp.net user controls are great.  I use them all the time when working on .net websites.  I was working on a site using the asp.net ajax extender toolkit.  I created a panel that could be expanded collapsed with a button click.  I inserted a few into the site and liked them so much I made some more.  Well after the 7th panel it started getting tedious.  What a perfect place for a user control.  The problem was I needed to be able to place whatever custom content I wanted inside the panel.  After much searching around I wasn't finding what I wanted.  The answer it turns out is an asp.net user control with custom templates.

Create a new user control for your asp.net site.  Mine is called CollapsiblePanel.  In the code behind for the page you need to add a new class MessageContainer that inherits from Control and implements the INamingContainer Interface.   Then in the user controls OnInit method you need to check for content and add it to your user control.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test.UserControls
{
    // this is a message container, it contins the data we want to display
    // as well as the index of the container
    public class MessageContainer : Control, INamingContainer
    {
        private int index;
        internal MessageContainer(int index) { this.index = index; }
        public int Index { get { return index; } }
    }

   // this is the user control I have created
   //its an ajax extended collapsible panel with some custom content
    public partial class CollapsiblePanel : System.Web.UI.UserControl, INamingContainer
    {
        private ITemplate _contentTemplate = null;

        [TemplateContainer(typeof(MessageContainer))]
        public ITemplate Content
        {
            get { return _contentTemplate; }
            set { _contentTemplate = value; }
        }
     
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // if we have a content template in the markup then add it to our container
            if (_contentTemplate != null)
            {
                MessageContainer container = new MessageContainer(0);
                _contentTemplate.InstantiateIn(container);
                this.ContentHolder.Controls.Add(container);
            }
        }
    }
}

Now to use our new user control in an aspx page with some content.


<uc:CollapsiblePanel runat="server" ID="CollapsiblePanel1">
        <content>
          CONTENT GOES HERE,You can drop anything, asp.net controls, etc.            
        </content>
    </uc:CollapsiblePanel>

C++ convert char * to to wide string wstring

Often times when working with older code you find yourself staring at some old char* variables. I often find myself having to convert them to wide strings for unicode support (wstring). I created a handy function that makes this simple.
wstring charToWideString( const char* src )
{
    return std::wstring( src, src + strlen(src) );
}
Now simply call thus:
wstring thus = charToWideString( "thus" );
Drop this function in a static class or header file and use it anywhere.

Thursday, March 14, 2013

ASP.NET Create Javascript Alert on Server Side

Many times in ASP.net you find yourself needing to create an alert on the client side but you're processing on the server side. The trick is to register a Javascript to the client from the server. I have found a nifty way of creating a class that will allow you to do this.

public static class ClientMessageBox
{

    public static void Show(string message, Control owner)
    {
        Page page = (owner as Page) ?? owner.Page;

        if (page == null)
        {
          return;
        }

        page.ClientScript.RegisterStartupScript(owner.GetType(),
            "ShowMessage", string.Format("<script type="text/javascript">;alert('{0}')</script>",
            message));

    }

}

// Example of using class and method
protected void Page_Load(object sender, EventArgs e)
{
    ClientMessageBox.Show("Hello World", this);
}

You can now call ClientMessageBox.Show('text', this ); anywhere server side and get a nice javascript alert. Now of course there are AJAX control toolkits and other things that do this for you but this is a bare bones pure C# solution.

Friday, January 25, 2013

C# Numeric Only TextBox

Once in a while you find yourself needing to stop certain keypresses in a C# desktop application.  I've found the best way is to handle this in the keypress event of a text box.  This is some very small code that shows how to only allow numeric digits to be pressed.

private void textBox_KeyPress( object sender, KeyPressEventArgs e )
{
     e.Handled = !char.IsDigit( e.KeyChar );
}


Now if you want to allow other characters, like the decimal, etc you need to get a bit fancier.


private void textBox_KeyPress( object sender, KeyPressEventArgs e )
{
       if( char.IsDigit( e.KeyChar ) || 
           e.KeyChar == '.' )
       {
          e.Handled = false;
      }
      else
      {
          e.Handled = true;
      }
}

To allow more characters you just need to modify that first if parameter to your needs.

Friday, November 30, 2012

C# Form Application in Kiosk Mode/Fullscreen

Sometimes you need to have a C# windows form application run in full screen mode.  Like you see on a kiosk at a mall or some stand alone machine.  It's fairly easy you just need to set some of the properties on the Form either in it's OnLoad method or directly in the designer.

In the OnLoad method of the main Form set these values, or again set them directly in the designer.

this.MaximizeBox = false;
this.TopMost = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

Wednesday, November 14, 2012

C# String Performance

In C# I have read a lot of debate over which way is the best way to do String Concatenation.  I have often read never ever use String1 + String2 due to the memory allocations and time constraints.  I decided to run some tests on the various way of doing String manipulation.  The table below shows the iterations, total times, and average times for some common way of doing string addition.  This was just a test of time, there was no memory consumption test.  All tests were doing adding 7 strings together that were stored in variable names.  There was no string a = "a" + "b";  It was all string a  = var1 + var2;  These were creating a single string for the listed iterations using the method(s) below.

I was surprised to see the + method came out ahead in all the tests.  String builder came in a close second.  String.Format was extremely slow but allows for localization which is another story.

iterations String + average String.Concat average String.Format average StringBuilder average
100 0 0 0 0 0 0 0 0
1000 0 0 0 0 1 0.001 0 0
10000 4 0.0004 7 0.0007 21 0.0021 4 0.0004
100000 38 0.00038 82 0.00082 69 0.00069 44 0.00044
1000000 272 0.000272 525 0.000525 784 0.000784 306 0.0003067
10000000 2569 0.0002569 5133 0.0005133 6245 0.0006245 2917 0.0002917

Sunday, July 29, 2012

C# Use a stored procedure to fill a dataset/table

When you fill a DataSet/Table in C# you use a SQL Data Adapter. The code for this is geared towards a SQL SELECT statement. However I'm not a big fan of raw SQL in my code so I found a way to use a stored procedure instead.

 public static DataTable GetTable()  
     {  
       DataTable dt = null;  
       try  
       {  
         using( SqlConnection connection = new SqlConnection( "your connection string" ) )  
         {  
           using( SqlDataAdapter sda = new SqlDataAdapter() )  
           {  
             using( SqlCommand command = new SqlCommand( "your stored procedure", connection ) )  
             {  
               command.CommandType = CommandType.StoredProcedure;
               
               // this line needs to be added for every parameter the SP expects
               command.Parameters.AddWithValue( "parametere value", paramValue ); 
               
               sda.SelectCommand = command;  
               dt = new DataTable();  
               connection.Open();  
               sda.Fill( dt );  
             }  
           }  
         }  
       }  
       catch( Exception ex )  
       {  
         Debug.WriteLine( ex.ToString() );  
       }  
       return dt;  
     }  

C# execute a stored procedure using SQL Server

Below we have some code that opens a connection to a database using a connection string then executes a stored procedure. This obviously needs to be placed in some method or class. You will need to add your own connection string and parameter values.
 
       try  
       {  
         using( SqlConnection connection = new SqlConnection("some connection string" ) )  
         {  
           using( SqlCommand command = new SqlCommand( "stored procedure name", connection ) )  
           {  
             command.CommandType = CommandType.StoredProcedure;  
             // this line needs to be added for every parameter the SP expects
             command.Parameters.AddWithValue( "parametere value", paramValue );    
             connection.Open();

             // based on the what the SP does, call the execute non query, execute scalar, or execute reader method

             command.ExecuteNonQuery();  
           }  
         }    
       }  
       catch( Exception ex )  
       {  
         Debug.WriteLine( ex.ToString() ); 
       } 

Tuesday, November 22, 2011

C# convert string array to integer (or something other kind of data type) array

Many times in coding you are dealing with transforming data from one type to another.  I often find myself creating integers, longs, etc from strings.  Especially in .net for some reason.  I got tired of writing tons of code to handle this.  .Net gives you a great way to convert an array from one type to another.

Currently I would always end up writing a for loop iterating through the array and doing a manual copy.  It would look something like this:

string[] someStringValues;

int[] someIntValues = new int[someStringValues.Length];

for( int i = 0; i < someStringValues.Length; i++ )
{
   someIntValues[i] = int.Parse( someIntValues[i] );
}

Not horrible code, but there is a more succinct way of doing it!

string[] someStringValues;

int[] someIntValues = Array.ConvertAll<string, int>( someStringValues, int.Parse );


We have now moved all that code into 1 line.  With some more magic we can also move this into a generic templated solution and you could theoretically change any array type into another type with the appropriate converter.  This could apply not only to basic data types but complex classes with an associated converter.

Friday, November 18, 2011

C# Simple Binary Tree

Today I'm getting a bit into data structures. Recently I've found a need to store a large amount of records (16 million) in memory as a sort of cache. I tried using databases, etc, but it was all too slow. I needed super fast access times, well under a millisecond to speed up a large application with many data look ups. I tried a linked list but while the insert times were great the look ups again were too slow. I finally settled on a binary tree. Building the tree is slow, several minutes, but this data doesn't change and gives me super fast look up times, around .005 ms. To achieve this I wrote a very simple binary tree class.

It uses a node that is fit for my purposes. To make this class even better I would implement in generics with a node class that has to implement IComparable. This way you can make a binary tree for any type of class that can be compared. For now I'm hard coding the key/values for my specific needs. See the rather large code block below. I will add a zip file with the code as well.

using System;
using System.Collections;

namespace BinaryTree
{
   
    /// <summary>
    /// A very basic Binary Search Tree. Not generalized, stores
    /// name/value pairs in the tree nodes. name is the node key.
    /// The advantage of a binary tree is its fast insert and lookup
    /// characteristics. This version does not deal with tree balancing.
    /// </summary>
    public class TreeNode
    {
        #region Fields

        private string _name;
        
        private int[] _codes;
        
        public TreeNode Left, Right;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>
        /// The name.
        /// </value>
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// Gets or sets the codes.
        /// </summary>
        /// <value>
        /// The codes.
        /// </value>
        public int[] Codes
        {
            get { return _codes; }
            set { _codes = value; }
        }
        
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="TreeNode"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="_codes">The _codes.</param>
        public TreeNode( string name, int[] codes )
        {
            _name = name;
            _codes = codes;
            Left = null;
            Right = null;
        }
    }

    /// <summary>
    /// A basic binary tree with a string, int[] node.  string is the key, int[] is the value
    /// </summary>
    public class BinaryTree
    {
        #region Fields

        // Points to the _root of the tree
        private TreeNode _root;

        // a count of nodes in the tree, duh!
        private int _count = 0;

        #endregion

        #region Properties

        /// <summary>
        /// Returns the number of nodes in the tree
        /// </summary>
        /// <returns>Number of nodes in the tree</returns>
        public int Count
        {
            get { return _count; }
        }

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="BinaryTree"/> class.
        /// </summary>
        public BinaryTree()
        {
            _root = null;
            _count = 0;
        }

        #region Public Methods

        /// <summary>
        /// Clear the binary tree.
        /// </summary>
        public void Clear()
        {
            this.KillTree( ref _root );
            _count = 0;
        }       

        /// <summary>
        /// Find name in tree. Return a reference to the node
        /// if symbol found else return null to indicate failure.
        /// </summary>
        /// <param name="name">Name of node to locate</param>
        /// <returns>Returns null if it fails to find the node, else returns reference to node</returns>
        public TreeNode FindSymbol( string name )
        {
            TreeNode np = _root;

            int cmp;
            
            while( np != null )
            {
                cmp = String.CompareOrdinal( name, np.Name );

                if( cmp == 0 )   // found !
                {
                    return np;
                }

                if( cmp < 0 )
                {
                    np = np.Left;
                }
                else
                {
                    np = np.Right;
                }
            }
            return null;  // Return null to indicate failure to find name
        }

        /// <summary>
        /// Recursively locates an empty slot in the binary tree and inserts the node
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="tree">The tree.</param>
        private void Add( TreeNode node, ref TreeNode tree )
        {
            if( tree == null )
            {
                tree = node;
            }
            else
            {
                // If we find a node with the same name then it's 
                // a duplicate and we can't continue
                int comparison = String.CompareOrdinal( node.Name, tree.Name );

                if( comparison == 0 )
                {
                    throw new Exception();
                }

                if( comparison < 0 )
                {
                    Add( node, ref tree.Left );
                }
                else
                {
                    Add( node, ref tree.Right );
                }
            }
        }

        /// <summary>
        /// Add a symbol to the tree if it's a new one. Returns reference to the new
        /// node if a new node inserted, else returns null to indicate node already present.
        /// </summary>
        /// <param name="name">Name of node to add to tree</param>
        /// <param name="d">Value of node</param>
        /// <returns> Returns reference to the new node is the node was inserted.
        /// If a duplicate node (same name was located then returns null</returns>
        public TreeNode Insert( string name, int[] codes )
        {
            TreeNode node = new TreeNode( name, codes );
            try
            {
                if( _root == null )
                {
                    _root = node;
                }
                else
                {
                    Add( node, ref _root );
                }
                
                _count++;
                
                return node;

            }
            catch( Exception )
            {
                return null;
            }
        }

        // Searches for a node with name key, name. If found it returns a reference
        // to the node and to thenodes parent. Else returns null.
        private TreeNode FindParent( string name, ref TreeNode parent )
        {
            TreeNode np = _root;
            
            parent = null;
            
            int cmp;

            while( np != null )
            {
                cmp = String.Compare( name, np.Name );
                if( cmp == 0 )   // found !
                    return np;

                if( cmp < 0 )
                {
                    parent = np;
                    np = np.Left;
                }
                else
                {
                    parent = np;
                    np = np.Right;
                }
            }

            return null;  // Return null to indicate failure to find name

        }

        /// <summary>
        /// Find the next ordinal node starting at node startNode.
        /// Due to the structure of a binary search tree, the
        /// successor node is simply the left most node on the right branch.
        /// </summary>
        /// <param name="startNode">Name key to use for searching</param>
        /// <param name="parent">Returns the parent node if search successful</param>
        /// <returns>Returns a reference to the node if successful, else null</returns>
        public TreeNode FindSuccessor( TreeNode startNode, ref TreeNode parent )
        {
            parent = startNode;
            
            // Look for the left-most node on the right side
            startNode = startNode.Right;
            
            while( startNode.Left != null )
            {
                parent = startNode;
                startNode = startNode.Left;
            }

            return startNode;
        }

        /// <summary>
        /// Delete a given node. This is the more complex method in the binary search
        /// class. The method considers three senarios, 1) the deleted node has no
        /// children; 2) the deleted node as one child; 3) the deleted node has two
        /// children. Case one and two are relatively simple to handle, the only
        /// unusual considerations are when the node is the _root node. Case 3) is
        /// much more complicated. It requires the location of the successor node.
        /// The node to be deleted is then replaced by the sucessor node and the
        /// successor node itself deleted. Throws an exception if the method fails
        /// to locate the node for deletion.
        /// </summary>
        /// <param name="key">Name key of node to delete</param>
        public void Delete( string key )
        {
            TreeNode parent = null;

            // First find the node to delete and its parent
            TreeNode nodeToDelete = FindParent( key, ref parent );
            
            if( nodeToDelete == null )
            {
                throw new Exception( "Unable to delete node: " + key.ToString() );  // can't find node, then say so 
            }

            // Three cases to consider, leaf, one child, two children

            // If it is a simple leaf then just null what the parent is pointing to
            if( ( nodeToDelete.Left == null ) && ( nodeToDelete.Right == null ) )
            {
                if( parent == null )
                {
                    _root = null;
                    return;
                }

                // find out whether left or right is associated 
                // with the parent and null as appropriate
                if( parent.Left == nodeToDelete )
                {
                    parent.Left = null;
                }
                else
                {
                    parent.Right = null;
                }

                _count--;
                return;
            }

            // One of the children is null, in this case
            // delete the node and move child up
            if( nodeToDelete.Left == null )
            {
                // Special case if we're at the _root
                if( parent == null )
                {
                    _root = nodeToDelete.Right;
                    return;
                }

                // Identify the child and point the parent at the child
                if( parent.Left == nodeToDelete )
                {
                    parent.Right = nodeToDelete.Right;
                }
                else
                {
                    parent.Left = nodeToDelete.Right;
                }

                // Clean up the deleted node
                nodeToDelete = null; 
                _count--;
                return;

            }

            // One of the children is null, in this case
            // delete the node and move child up
            if( nodeToDelete.Right == null )
            {
                // Special case if we're at the _root            
                if( parent == null )
                {
                    _root = nodeToDelete.Left;
                    return;
                }

                // Identify the child and point the parent at the child
                if( parent.Left == nodeToDelete )
                {
                    parent.Left = nodeToDelete.Left;
                }
                else
                {
                    parent.Right = nodeToDelete.Left;
                }

                // Clean up the deleted node
                nodeToDelete = null; 
                _count--;
                return;

            }

            // Both children have nodes, therefore find the successor, 
            // replace deleted node with successor and remove successor
            // The parent argument becomes the parent of the successor
            TreeNode successor = FindSuccessor( nodeToDelete, ref parent );

            // Make a copy of the successor node
            TreeNode tmp = new TreeNode( successor.Name, successor.Codes );

            // Find out which side the successor parent is pointing to the
            // successor and remove the successor
            if( parent.Left == successor )
            {
                parent.Left = null;
            }
            else
            {
                parent.Right = null;
            }

            // Copy over the successor values to the deleted node position
            nodeToDelete.Name = tmp.Name;
            nodeToDelete.Codes = tmp.Codes;
            _count--;
        }

        /// <summary>
        /// Return the tree depicted as a simple string, useful for debugging, eg
        /// 50(40(30(20, 35), 45(44, 46)), 60)
        /// </summary>
        /// <returns>Returns the tree</returns>
        public string DrawTree()
        {
            return DrawNode( _root );
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return this.DrawTree();
        }

        #endregion

        #region Private Methods

        // Recursive destruction of binary search tree, called by method clear
        // and destroy. Can be used to kill a sub-tree of a larger tree.
        // This is a hanger on from its Delphi origins, it might be dispensable
        // given the garbage collection abilities of .NET
        private void KillTree( ref TreeNode p )
        {
            if( p != null )
            {
                KillTree( ref p.Left );

                KillTree( ref p.Right );

                p = null;

            }
        }

        /// <summary>
        /// Draws the node.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns></returns>
        private string DrawNode( TreeNode node )
        {
            if( node == null )
            {
                return "empty";
            }

            if( node.Left == null &&
                node.Right == null )
            {
                return node.Name;
            }
            if( node.Left != null &&
                node.Right == null )
            {
                return String.Format( "{0}({1}, )", node.Name, DrawNode( node.Left ) );
            }
            if( node.Right != null &&
                node.Left == null )
            {
                return String.Format( "{0}(_,{1})", node.Name, DrawNode( node.Right ) );

            }

            return String.Format( "{0}({1},{2})", node.Name, DrawNode( node.Left ), DrawNode( node.Right ) );

        }

        #endregion

    }
}

Friday, September 30, 2011

C# create a new process

Once in a while I find myself needing to spawn a process in C#.  The .net framework has some built in functionality to do this.  It's fairly trivial to just spawn a process and let it run.  .NET however allows us many options to customize the look and feel as well as the error output of the spawned process.  The example below simply fires up notepad with a default document.  You can customize this heavily as mentioned and not show windows, etc.

You can read all about is on MSDN.

// create and setup the process object
chartProcess = new Process();
chartProcess.StartInfo.FileName = "notepad.exe";

// this is all optional setup

// pass in any command line arguments if desired
chartProcess.StartInfo.Arguments = "test.txt";

//
chartProcess.StartInfo.UseShellExecute = false;

// this determines if we show the actual command or form window
chartProcess.StartInfo.CreateNoWindow = false;

// this lets us handle an event when the process we start stops
chartProcess.EnableRaisingEvents = true;
chartProcess.Exited += new EventHandler( chartProcess_Exited );

// start the process
chartProcess.Start();

Tuesday, August 30, 2011

C# Parallel.For

With the advent of C# 4.0 you can now write code to more efficiently use multiple core machines. I will show a trivial example on how to do this. This code reads through a directory and lists all the files. Now while the example itself isn't that complicated I will show some timings and benefits on my Intel duo core 2 machine. Running on even more cores would show an even bigger result. This kind of computing really shines when you're dealing with large amounts of data or very intensive computations. This test sums up 10 million random integers.



using System.Threading.Tasks;

static void Main( string[] args )
{
      int[] values = new int[10000000];

      Random r = new Random( DateTime.Now.Millisecond );

      double sum = 0;

      for( int i = 0; i < values.Length; i++ )
      {
          values[i] = r.Next( 0, 10 );
      }

      DateTime start = DateTime.Now;
      DateTime end;

      // run the test in parallel
      Parallel.For( 0, values.Length, delegate( int i )
      {
          sum += values[i];
      } );

      end = DateTime.Now;

      TimeSpan t = end - start;

      Console.WriteLine( "Parrallel For time is: " + t.TotalMilliseconds + ", sum is: " + sum );

      start = DateTime.Now;

      // run the test in sequential
      for( int i = 0; i < values.Length; i++ )
      {
          values[i] = r.Next( 0, 10 );
      }

      end = DateTime.Now;

      t = end - start;

      Console.WriteLine();
      Console.WriteLine( "Regular For time is: " + t.TotalMilliseconds + ", sum is: " + sum );

      Console.ReadKey();
}

The Parallel.For looks almost exactly like the regular for. The main difference is you have to add in the delegate(int) at the end. This is used when the compiler creates the different threads to use on the various CPUs. A more detailed explanation can be found here:

MSDN Link

Now onto the results!

After many runs the parallel code ran anywhere from almost twice as fast to 100 ms faster. Now this is just a random summation of integers. Even more computationally complex tasks should see even more benefit

Some results:

Tuesday, August 23, 2011

C# create MD5 hash from a string

A common task when dealing with sensitive data is to create a hash of it. MD5 is used quite often especially when dealing with password, etc. I will leave the discussion of collisions, etc to others and just show a function that will return an array of bytes that is the result of hashing the input string. This function calls for an Encoding object to be passed in since you never know what encoding you will be using. But you could easily hard code the encoding if you know that will never change.

using System.Security.Cryptography;

/// <summary>
/// Hashes the string.
/// </summary>
/// <param name="valueToHash">The value to hash.</param>
/// <param name="textEncoding">The text encoding.</param>
/// <returns></returns>
private byte[] HashString( String valueToHash, Encoding textEncoding )
{
   byte[] result;

   using( MD5 md5 = MD5.Create() )
   {
      byte[] inputBytes = textEncoding.GetBytes( valueToHash );
      result = md5.ComputeHash( inputBytes );
   }

   return result;

}

Thursday, August 18, 2011

C# get the number of days in a month

Ok this isn't the longest blog post, but it contains a handy little code snippet. Sometimes you find yourself needing to know the number of days in any given month. The code below will get you the last day of the month. I'm using the current month but you could use any month. You just need to know the month and year you're looking for. The magic lies in the DateTime.DaysInMonth method. You pass in the year and month and it returns the number of days in that month. The code below is pretty self explanatory.

static void Main( string[] args )
{
   DateTime now = DateTime.Now;

   int daysInMonth = DateTime.DaysInMonth( now.Year, now.Month );

   String dateFormat = String.Format( "Last day of the month is - {0}/{1}/{2}", now.Month, daysInMonth, now.Year);

   Console.WriteLine( dateFormat);

   Console.ReadKey();

}

And a brief picture showing the output, obviously I ran this is October 2011.

Monday, August 15, 2011

C# Get the ip address of a host name

Often times you want to find the ip address of a host name. This function will do this for you. It returns the first address.

using System.Net;

public string GetIPAddress(string sHostName)
{
   IPHostEntry ipEntry = Dns.GetHostByName(sHostName);
   IPAddress [] addr = ipEntry.AddressList;
   string sIPAddress = addr[0].ToString();

   return sIPAddress;

}