Limiting TextArea Characters In Internet Explorer

In my last project I ran into an annoying nuance of IE9 but turned out to be IE (Internet Explorer) in general.  IE does not like to acknowledge the maxLength property that you can set on a <textarea> tag.  In FireFox as well as in Chrome you could set this property to the desired length and the browser would acknowledge this and stop user input at the desired length.  Take a look at the following snippet.

<textarea id="limitChars" rows="5" cols="86" maxlength="1000">

In this snippet, the attribute to look at is maxlength=”1000″.  Make sure you have this set as it works well in FireFox and in Chrome.  Now, let’s talk about Internet Explorer.  From my project it looks like IE7, IE8, IE9, and IE10 don’t care about the maxlength attribute and will let the user keep typing long beyond what you desire.  So there are two pieces to this puzzle that I found fit my likings best.  The first is we bind the <textarea> to the keyup event like so.

$('# limitChars').keyup(function () {
     //Code
});

In binding the textarea to this keyup event it will be fired on every keystroke.  So inside of this event we now just have to check the length of characters in the texarea and either do nothing or we will cut it down.  So let’s add the code in the middle.

$('#limitChars').keyup(function () {
     //Get the value of the textarea.
     var valueOfInput = $("#limitChars").val();

     //Check and see if its over our desired limit.

     if (valueOfInput.length > 1000) {
          //We reset the characters they have typed and cut it off to 1000.

          $("#limitChars").html(valueOfInput.substr(0, 1000));
     }
});

It causes a bit of weird behavior when they get to the limit but up until that limit it works quite well.


Create Local Business Rich Snippet

I thought it would be nice to right out a little how to on a recent task I did for a site I manage (www.mrdscarpetcleaning.com).  Rich Snippets are a bit of a new thing when it comes to SEO and running a small business.  There are tons of different snippets and snippet variations that can be found on http://schema.org/.  For right now I am only going to show a local business.

The first part that will be looked for by the search engine is the itemscope and itemtype attributes.  This is going to basically tell the search engine this is a snippet and also what kind.  For a local business it is as follows.

<div itemscope itemtype="http://schema.org/LocalBusiness">

From here on out we build out the snippet with the name address.  Take note that there is actually a second snippet in here that is denoted by the itemtype=”http://schema.org/PostalAddress” attribute.

<span itemprop="name">Mr. D's Carpet Cleaning</span>
<div itemprop="address" itemscope temtype="http://schema.org/PostalAddress">
     <span itemprop="streetAddress">731 N 25th St.</span>
     <span itemprop="addressLocality">Mesa</span>,
     <span itemprop="addressRegion">AZ</span>
     <span itemprop="postalCode">85213</span>
</div>

The last part for this snippet will be including the contact information.  You can add the phone number and the website for your small business.

Phone: <span itemprop="telephone">(480) 628-3788</span><br />
Website: <a style="color: black;" itemprop="URL">http://www.mrdscarpetcleaning.com/</a>

Now, if we put this all together you will get a full rich snippet for your local business.  Take a look at the following.

<div itemscope itemtype="http://schema.org/LocalBusiness">
     <span itemprop="name">Mr. D's Carpet Cleaning</span>
     <div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
          <span itemprop="streetAddress">731 N 25th St.</span>
          <span itemprop="addressLocality">Mesa</span>,
          <span itemprop="addressRegion">AZ</span>
          <span itemprop="postalCode">85213</span>
     </div>
     Phone: <span itemprop="telephone">(480) 628-3788</span><br />     
     Website: <a style="color: black;" itemprop="URL">http://www.mrdscarpetcleaning.com/</a>
</div>

One side note to keep in mind.  If you run your site through html validators make sure that it handles HTML5 tags.  As you can see in the example the itemscope attribute doesn’t have a value after it as it’s a Boolean value it does not need anything after it in HTML5.  If you can’t change the version and your validator is saying this is invalid you can update your attribute to:

<div itemscope="itemscope" itemtype="http://schema.org/LocalBusiness">

By setting it to itself you are in a sense tricking the validator to say that this value is true.


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


AJAX Post Using Serialize Data

AJAX posts are great for calling controller methods.  However, if you have a lot of parameters or if your method only takes a model there is a nice and simple answer to sending all of the data in a quick and efficient matter.  The AJAX call allows you to .serialize() the form that the data is coming from.  It can select on individual elements like <input> or <textarea> but it is typically easier to select the surrounding form. Let’s look at how this call is constructed.

$.ajax({
    type: 'POST',
    url: '/Controller/EmailAction',
    data: $('#form-content').serialize(),
    dataType: "json",
    success: function (data) {
        //show a success message
    },
    error: function () {
        //log failure/show message
    }
});

As you can see it is pretty straight forward.  Data gets set to the form, which in this case is $(‘#form-content’).  From there you call a .serialize() on the form as show above. So if we look at the controller method this is all you need for your method declaration.

public JsonResult EmailAction(MyModel model)
{
       try
       {
              //Processing here.
       }
       catch (Exception ex)
       {
              //log
       }

       return Json(result);
}

It is obviously not a complete method by any means but as you can see it only takes a model.  The magic that happens is when you name the input elements the same as in the model, when you serialize and make the request they are automatically mapped over because it generates a query string of the input elements and they are mapped over to the model.  This makes something like a registration form that has numerous fields it becomes very simple to create a model and just call .serialize() and it’s all done for you.  I found this way a lot easier and more organized then creating methods with tons of parameters and helps to minimize error if you change the names of fields as there are less places to make changes.


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.


StackOverflow Profile