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

            //Activates knockoutjs so the browser knows what to do with data-bind in markup html.
            ko.applyBindings(viewModel); 
        });
    };
};

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.

<div id="table_words" class="someStyles" data-bind="koGrid: { 'data': ConfigurationsMin }">
</div>

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.


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
logThread.Start(logParams);

//Add thread to thread list
_threadList.Add(checkThread);

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){
     thread.Join();
}

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:ListItem>Adam</asp:ListItem>
        <asp:ListItem>Anthony</asp:ListItem>
    <asp:ListItem>Ryan</asp:ListItem>
    </asp:DropDownList>
    <asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
    <p>
        Selected Name: <asp:label text='<%# List.SelectedItem.Text %>' runat="server"/>
    </p>
</form>

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.

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

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>
<div id="NewdWay">
    <%: Model.Content %>
</div>

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()
{
    try
    {
        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.


Ensure Threads Have Finished Before Method Continues

**Update – Please see here for a better way of doing this.  It’s a better solution that came around after writing this post.

This post is part extension off of my Multithreading with Parameters.  I came into a spot where I am building a monitoring page that on page load, spins off about 20-30, and then displays the outcome of those threads.  However, if you spin off a bunch of threads and don’t do anything else, the page load method finishes and you’re left with little to no content on the page because it finished before your threads.  So I implemented a thread counter.  It was a simple solution and makes the method wait until all threads have completed before it can move on.
We need a few things; a counter object, a lock object, an increment method, and a decrement method.  These are pretty straight forward and are as follows.


protected static int threadCounter = 0;
protected static object lockObject = new object();

protected void IncrememntCounter()
{
    lock (lockObject)
    {
        threadCounter++; //Increment Thread Count By 1
    }
}

protected void DecrementCounter()
{
    lock (lockObject)
    {
        threadCounter--; //Decrement Thread Count By 1
    }
}

Now let’s look how this gets applied.  [more]In our method where we spin off the threads, we simply call the increment method.


//Create new thread
Thread logThread = new Thread(LogServiceCall); 
//Start new threadlog
Thread.Start(logParams);
//Increment our thread 
counterIncrementCounter();

As I am sure you have figured out, the method that gets spun off in the thread, we need to call the decrement counter upon completion of that method.


private void LogServiceCall(object parameterObject)
{
    LogginParams pLoggingParams = (LogginParams)parameterObject;
    lock (lockObject)
    {
        LogServiceCall(pLoggingParams.Log, pLoggingParams.Info, pLoggingParams.Number);
    }

    DecrementCounter();
}

Now we have our counter set up.  When we spin off a new thread we are adding one to the counter, and then when our thread finishes we are decrementing the counter by one. Now the last piece of the puzzle is in the method that you are wanting to wait for the threads to complete, we simply check our thread counter for number remaining.


while (threadCounter > 0)
{
    Thread.Sleep(500); //Make it pause for half second so that we don’t spin the cpu out of control.
}

This was a nice way to ensure threads have finished and that the method would not continue until everything was done.  My threads were small and often times finish quickly.  I added asynchronous threads and chopped the page loading speed over half.  If you have another way of going about doing this please share, I would love to hear to if there are better and different ways of doing this.


StackOverflow Profile