Difference Between Dictionary and Hashtable

A guy asked me the other day, what is the difference between a Dictionary and a Hashtable?  I found myself stumbling a bit so I thought it would a good topic for me to write about and help me understand further.  A Dictionary is a generic type Dictionary<TKey, TValue> that allows static type which gets verified at compile-time as well as you can use a Dictionary without boxing.  I am finding that using a Dictionary in .Net 2.0 and above is the preferred way to go.

A Hashtable is not a generic type and requires boxing when you are dealing with value types.  A nice perk to using a Hashtable is that it allows multiple reader threads with one reader thread making a Hashtable thread safe where a Dictionary does not offer thread safety.  Another difference is that in a Dictionary when you request a non-existing key an exception will be thrown.  However, when you request a non-existing key in a Hashtable; a null is returned.

There is an alternative in .Net 4.0 for a Dictionary that is called ConcurrentDictionary<TKey, TValue>.

Here is an example of a simple ConcurrentDictionary from MSDN http://msdn.microsoft.com/en-us/library/dd287191.aspx.

class CD_Ctor
        // Demonstrates: 
        //      ConcurrentDictionary<TKey, TValue> ctor(concurrencyLevel, initialCapacity) 
        //      ConcurrentDictionary<TKey, TValue>[TKey] 
        static void Main()
            // We know how many items we want to insert into the ConcurrentDictionary. 
            // So set the initial capacity to some prime number above that, to ensure that 
            // the ConcurrentDictionary does not need to be resized while initializing it. 
            int NUMITEMS = 64;
            int initialCapacity = 101;

            // The higher the concurrencyLevel, the higher the theoretical number of operations 
            // that could be performed concurrently on the ConcurrentDictionary.  However, global 
            // operations like resizing the dictionary take longer as the concurrencyLevel rises.  
            // For the purposes of this example, we'll compromise at numCores * 2. 
            int numProcs = Environment.ProcessorCount;
            int concurrencyLevel = numProcs * 2;

            // Construct the dictionary with the desired concurrencyLevel and initialCapacity
            ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(concurrencyLevel, initialCapacity);

            // Initialize the dictionary 
            for (int i = 0; i < NUMITEMS; i++) cd[i] = i * i;

            Console.WriteLine("The square of 23 is {0} (should be {1})", cd[23], 23 * 23);

Differences Between DataReader and DataAdapter

In doing some research about common interview questions for .Net developers I came across the question of what are the difference between DataReader and DataAdapter; as well as when would each be used.  As it turns out, they are quite easy to figure out which one does what with some distinct difference.

DataReader is a forward only read stream that is useful when you are just selecting data from the database.  DataReader is great for when you are just grabbing information to fill out a DataGrid or WebControls in your page.  However, do note that DataReader requires an open connection to the database until the entire select process is complete.  DataReader is good to use when you only need to grab data once and in a read only context as it offers no way to insert/update/delete data in the database.  With DataReader you also need to make sure that you explicitly open and close the database connection.

DataAdapter is similar in that it can be used to select data but it also allows the other data actions of insert/update/delete.  DataAdapter uses a DataSet to handle all of the data and the manipulations to the data.  This is a nice feature in the respect that it uses a disconnected architecture that allows the database connection to remain close until it is absolutely needed.  A nice difference between DataAdapter and DataReader is that DataAdapter handles the opening and closing of the database connection automatically so there is no manual labor to remember.

Some good points to remember not only for using in your applications but also good to remember going into discussion and interview type of scenes.

Ensure Threads Finish Before Method Continues Thread Join

So I wrote a post a few weeks back using a different method for the same thing.  I used a counter to count how many threads I started, and then decremented them as they finished.  Once the counter was equal to zero, I let the method continue and finish.  However, I realized since then that using Thread.Join() (Thread Join) was a lot easier to use and manage to handle the same task.

So the set up is that we are spinning off a handful of threads, but we don’t want the method, such as Main() to continue until all threads are finished. So we start off by needing a list to add all the threads to once we start them.

protected List _threadList = new List();

Then in our methods where we create and start the threads we will add them to this list we just created.

//Create new thread
Thread logThread = new Thread(LogServiceCall);

//Start new thread

//Add thread to thread list

So after we have spun off all our threads; the next call in the method basically calls Thread.Join() on all threads within that list.  What Thread.Join() does is block the calling thread from terminating before all the other threads do.  So by doing this we can ensure that the main method won’t be able to finish until all the threads have since we cause the calling thread to hang.
This is the little snippet to call Thread.Join() on the thread list.

foreach (Thread thread in _threadList){

Once this completes, all the threads we started have to finish before the main calling thread can continue and terminate allowing the method to continue.  I find this to be a more compact and less heavy way to complete this task instead of using a counter.

ASP.Net Page Syntax Code Blocks

ASP.Net Page Syntax Code Blocks

The <%# %> is used for data binding. This data binding expression creates a binding between a property on an ASP.NET page and a data source when the DataBind method is called. Data binding expressions can be included on the value side of an attribute/value pair in a server control or anywhere on the page. All data binding expressions on a page must be put between the <%# and %> characters. Here would be an example of using a data binding expression to bind to a server control.

<form runat="server">
    <asp:DropDownList id="List" runat="server">
    <asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
        Selected Name: <asp:label text='<%# List.SelectedItem.Text %>' runat="server"/>

The <%= %> symbols are used to display information. The value that gets entered in between the symbols will be written out to the current page. These symbols will be executed and displayed when they appear on the page. So a quick example would be having a variable named Transportation. Let’s say the value of that variable is equal to Truck. With that in mind, let’s look at how this would be used in the mark up.

I drive a <%= Transportation %>! //Code
I drive a Truck! //Output

The <% %> symbols are used for Embedded code blocks. The embedded code block is server code and is executed during the pages render. The block can be used to execute programming statements or call functions in the current page class. Here is a simple example from msdn. You’ll see how it uses the <% %> to encase the for loop that will then execute when the page renders.

    <form id="form1" runat="server">
        <% for(int i = 0; i < 6; i++) %>
        <% { Response.Write("<br>" + i.ToString()); }%>

The <%– –%> is simply used to indicate a server side comment. These can be used anywhere within the page but cannot be used within the <script> tag. You also may not used a server side comment within an embedded code block. So if you have a <%– –%> inside of a <% %> it will result in a compilation error.

    <asp:button runat="server" id="MyButton"
    OnClick="MyButton_Click" />

The <%@ %> is used to used to signify a page directive. ASP.Net includes many different directives which are as follows. Taken right from msdn.

@ Page Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .aspx files.
@ Control Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files (user controls).
@ Import Explicitly imports a namespace into a page or user control.
@ Implements Declaratively indicates that a page or user control implements a specified .NET Framework interface.
@ Register Associates aliases with namespaces and class names, thereby allowing user controls and custom server controls to be rendered when included in a requested page or user control.
@ Assembly Links an assembly to the current page during compilation, making all the assembly's classes and interfaces available for use on the page.
@ Master Identifies an ASP.NET master page.
@ WebHandler Identifies an ASP.NET IHttpHandler page.
@ PreviousPageType Provides the means to get strong typing against the previous page as accessed through the PreviousPage property.
@ MasterType Assigns a class name to the Master property of an ASP.NET page, so that the page can get strongly typed references to members of the master page.
@ OutputCache Declaratively controls the output caching policies of a page or user control.
@ Reference Declaratively links a page or user control to the current page or user control.

It is important to note that if you do not specify one, the default then becomes the @ Page directive.

The <%: %> symbols were introduced in ASP.NET 4 and it works much like the <%= %> but it will also automatically HTML encode the output. In the example below, you will notice that the second one does the encoding for you and helps save some space.

<div id="OldWay">
    <%= Server.HtmlEncode(Model.Content) %>
<div id="NewdWay">
    <%: Model.Content %>

I got tired of trying to look them up every time so I decided to consolidate them into one place for quick reference.

Check Database Connectivity Using Stored Procedure

This may not be the best way to go about checking database connectivity from within your app, but it is a method that works for me.  If you have a different way, please comment.  The point of this is to make a dummy call out to the database and if the call succeeds, then we have access to the database.  If the call fails or fails to connect, we then know something is wrong and it can trigger an alert.

It’s relatively simple and rather I am thinking about renaming the post to calling a stored procedure through C# but never the less let’s look.

protected void CheckDBHealthStatus()
        using (SqlConnection conn = new SqlConnection(ConnectionString)) //Create new SqlConnection with ConnectionString to DB
            using (SqlCommand sqlCommand = new SqlCommand())//Create a new SqlCommand to call stored proc
                sqlCommand.Connection = conn; //Add the Connection
                sqlCommand.CommandTimeout = 60; //Timeout After 1 mins
                sqlCommand.CommandText = "dummyProc_HealthCheck"; //Name Of Stored Procedure
                sqlCommand.CommandType = CommandType.StoredProcedure; //Type obviously Stored Procedure

                //add the parameters
                SqlParameter newParam = new SqlParameter("@ID", SqlDbType.VarChar, 10) { SqlValue = "Adam" }; //Create New Parameter
                sqlCommand.Parameters.Add(newParam); //Add to the SqlCommand we created above.

                conn.Open();//Open Our Connection to the DB
                sqlCommand.ExecuteNonQuery();//Execute the query.
    catch (Exception ex)
        string errorMessage = "Critical - Error when connecting to Database." + ex.Message;

All the comments are inline.  Obviously there is not really a need to have a parameter but I think it could come in useful for a person looking for how to add one.  Overall, fairly simple and a quick and dirty way of reaching out to the database, making some dummy call, and reporting if it succeeded or if it failed.  You can then take this farther and capture the error message and exception and have a service report to you when this goes wrong.