How to Use Git and Simple Git Commands

This is a very vast concept and way too much for one post so I will start off basic and add subsequent posts as I go deeper. The first step is to obviously install Git. At the time of writing this I am using Git 1.8.1.2. Since this lends itself to personal preference and team preference I will not cover the install.
Once you have Git installed, let’s open a command prompt. The very first command I want you to run is simply: Git. This will ensure that you installed Git and we are ready to go. You should see a screen as such below.

Simple Git Commands 1

If you see this output from your command line then you are set up and we are ready to get started. The next step we need to do is create a local folder that we will use as our Git Repository.

-Create a folder at C:\GitRepo
-Use your command line and change directories to new created directory.
-Run Git Command: Git init
-Verify you have the results below.

Simple Git Commands 2

The top being the command prompt and the bottom showing the folder you created and now a .git file. The .git file is a Git repository and will host all the files that we add and commit to it throughout this tutorial. The next thing we need to do is set some global config settings so that we have a username and email associated with our commits.

-Run Git Command: Git config --global user.name "Adam Drummond"
-Run Git Command: Git config --global user.email "adam@adamthings.com"

Now let’s make our first commit. In the directory we created C:\GitRepo lets create a text file and add a line of content to it. We will then add this to our repository and then commit it.

-Create text file name MyFirstCommit.txt
-Add some content to text file.
-Run Git Command: Git add MyFirstCommit.txt

At this point in time, our file is in what would be considered a staging area. It’s been adding to the repository but it has not been ‘checked in’ or ‘committed’ to the repository.

-Run Git Command: Git commit --m "This is my first commit."

This should be what your current state looks like.

Simple Git Commands 3

The last piece we will cover in this blog post is seeing the history of what has happened. For this we will use the following command.

-Run Git Command: Git log --oneline --graph --decorate –all

Since we have only made one commit, our graph is only one line.

Simple Git Commands 4

This graph will continue to grow in the next blog post as we add some branching in Git. Stay Tuned.


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.

 


How to Create a Rich Snippet for a Local Business

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.


The difference between a Generic Dictionary and a 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 and When to use 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.


Div Border With Rounded Corners And Gradient Background

Getting a div to have rounded corners with CSS is not too difficult of a task.  I came across a solution I would like to share quickly and briefly. Please note I found it only works in IE9, Firefox and Chrome.  It’s really only a couple lines of CSS so lets’ take a look.

.roundedCorners {
   -webkit-border-radius:10px;
    -moz-border-radius:10px;
    border-radius: 10px;
}

By setting these 3 values, you get a pretty nice rounded edge.  Now here is a weird edge case I came across.  I used a gradient background through CSS in a div and in IE9 the gradient was not rounded off.  So the fix for that was to surround it with a div and use an overflow: hidden to mask the colors.

<div class=" roundedCorners mask">
    <div class=" roundedCorners gradientBackground">
    </div
</div>

//CSS
.gradientBackground {
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e9ecf9', endColorstr='#ffffff'); /* for IE */
    background: -webkit-gradient(linear, left top, left bottom, from(#e9ecf9), to(#fff)); /* for webkit browsers */
    background: -moz-linear-gradient(top,  #e9ecf9,  #fff); /* for firefox 3.6+ */
}
 
.mask {
     overflow: hidden;
}

The above code properly rounded the corners of my div and provided a gradient with rounded corners as well in IE9, Firefox, and Chrome.  The rounded corners don’t work in older versions of IE.


Renstalling and Moving a Windows Service to a new location using a .bat file

Today I had an instance where I needed to move a currently running service to a new folder in a directory. I found that an easy way to do this was to just uninstall and reinstall the service itself. For this I used a .bat file that includes a couple commands. First, we have to stop the running service.

net stop “Adam’s Windows Service”

The next command is using InstallUtil.exe to uninstall the current service. This is the full line for uninstalling.

c:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u "D:\Adams\AdamsWindowsService.exe"

As you can see, the ‘-u’ signifies uninstall.  Now that we have the service uninstalled we want to reinstall it using the new directory location.  This line looks almost exactly the same as above, however, there is no ‘-u’.  Have a look at the following to install.

c:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "D:\AdamsNewDirectory\AdamsWindowsService.exe"

My service is now running from a new directory at D:\AdamsNewDriectory. The last thing to do is to restart the service.  This is almost the exact same as the first line except it includes a start.

net start “Adam’s Windows Service”

Now that we have an AdamsServiceMove.bat (naming doesn’t matter) we can easily modify it for any service to and from any location as well.  Have a look at the full file below.

net stop “Adam’s Windows Service” 

c:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u "D:\Adams\AdamsWindowsService.exe"

echo.
echo Please verify uninstallation ...
pause

c:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "D:\AdamsNewDirectory\AdamsWindowsService.exe"

echo.
echo Starting Adam’s Windows Service...
pause

net start "Adam’s Windows Service"

pause


Targeting IE6 and IE7 in CSS

So, as many of you know, supporting these old browsers can be a huge pain.  Some CSS hacks have made it a lot easier to handle the little quirks and override the main CSS to target a specific version.  There are two characters, one for IE6 and one for IE7.  Here is how it looks.

#divName
{
     padding: 5px;  /* shows in all browsers */
     *padding: 5px; /* shows in IE7 and earlier */
      _padding: 5px; /* shows in IE6 and earlier */
}

Really simple; by adding the preceding characters, it can change your CSS world.  I try at all costs to avoid doing such things because I don’t like how it clutters up my CSS page.  However, sometimes it’s just the easiest/quickest way to get the desired result you need when you have a deadline to meet.

Personally I wish that all old browsers would be deprecated. :)


KoGrid with KnockoutJS Simple Grid Set Up

Recently we took a look at implementing KoGrid which utilizes KnockoutJS.  This is a brief set up that I go going by pulling a data set from our controller.  First let’s look into the JavaScript and how all this happens.  Let’s look at the document initialization method first.

$(function () {    var $scvm = new ConfigsViewModel();  //Create New Instance of our ViewModel    $scvm.LoadConfigurations();  //Calls the load function in our ViewModel});

This is all pretty straight forward.  So let’s take a bit deeper look into the ConfigsViewModel().  In here we will create our observableArray() and load our data.

var ConfigsViewModel = function () {var self = this;    //#region Observables    self.ConfigurationsMin = ko.observableArray();    //#endregion    self.LoadConfigurations = function () {        $.post("/Config/Search", function (data) {            var viewModel = {                ConfigurationsMin: ko.observableArray(JSON.parse(data))            };            ko.applyBindings(viewModel); //Activates knockoutjs so the browser knows what to do with data-bind in markup html.        });    };};

[more]Here you can see the LoadConfigurations function that gets call when the dom loads.  Within this function it’s doing an Ajax post which returns a serialized result.

JavaScriptSerializer s = new JavaScriptSerializer();string json = s.Serialize(results);return json;

Since we are serializing the results we do a quick JSON.parse which will split the data out into a JSON object that the grid will recognize.  This is all relatively simple and gets a start to pull data back.  Now let’s look at the mark up of the grid. 

Here is the whole mark up and we will dig into it. 

There are a few key points for this intro into KoGrid.  First, you can see using the data-bind element we are signaling koGrid which has an element called data.  Here we assign data with the observableArray of ConfigurationsMin.  If you remember, we created and applied our data to this object. ConfigurationsMin: ko.observableArray(data).  This is the bare bones of KoGrid and knockout; but it gets a grid up and running with doing an Ajax call to get some data to populate the grid with.