Tuesday, January 15, 2013

Extending the default Command Timeout in Nhibernate



There was a Nhibernate query that is taking more than 30 sec , 34 seconds to be exact. The query involves a view that joins so many views and tables. It started taking more than 30 seconds last week. Reviewing the execution plan and throwing indexes here and there didn't help. The next immediate solution was to extend the Nhibernate default timeout time (i.e.30 seconds).

I believe extending the timeout should be a last resort approach , should be used as immediate fix until you come up with a long term solution - like redesigning your data architecture , optimizing your queries and others.

Nhibernate allows you set the command timeout for query. This timeout is the length of time the query will be allowed to execute and finish. If  the query takes more than this time,the query will be aborted and SQL timeout exception will be thrown.

Currently you can set the timeout on query if you are using ICriteria. The Nhibernate team is working to make this method (setting the timeout) available on  QueryOver  on the next release (3.3.x). 

I was using Nhibernate QueryOver for my query, thus I had to rewrite it using ICriteria , I know it is a bummer :(  . Assuming you are using a unit of work pattern  the code will be along the line of the following 


var query = _unitOfWork.currentSession.CreateCriteria<MyView>().          setTimeout(TIMEOUT_IN_MILLISECONDS);


I will leave it like that until we completely remove that view and replace it with a roll up table in our next release.


Friday, December 28, 2012

SignalR and Interval Polling for Dashboard Update

Have you ever wondered how some dashboard update their content with new data without the users intervention? If you check out the google finance stock dashboard you see the stock data is updated every few seconds. Google finance can be found here http://www.google.com/finance
I can think of two ways of achieving this objective,
   A.    Interval polling
This approach involves the client polling the server for new data in preconfigured time interval.
The client displays the new data and waits for the specified time and repeats the request again.
The drawback of this alternative is the unnecessary requests that is wasted to continually check for new data- even if the new data is available or not.

The conversation between the client (browser) and the server goes along the line of
Client: “Do you have new Data?”
Server: “No”
Client waits for 5 seconds and tries again
Client: “Do you have new Data?”
Server: “yes”
Client will update the dashboard

However, instead of the client continually checking the server for new data, Is there a way where the server can notify the client when the new data is ready. Luckily yes. Here SignalR comes to the rescue.

 B.     SignalR
This library allows us to write an application in which there is a bi-directional communication between the server and the client. In the newest version of browsers that support the new HTML5 API web sockets are used for communication. In browser where web sockets are not supported it will fallback to other legacy options to achieve the same objective. The list of fallback options include long polling ,interval polling etc.
At the core of this implementation we have the  Connection Hubs . Hubs provide a high level RPC framework over PersistentConnection. All the notification from the server to the client and vice versa is done through the hub. When the application is run, SignalR will emit the javascript equivalent of the Hub you defined in your C# assembly. So that you can start a connection from the client and then call methods defined in the hub(Server Calls). Moreover you can add client call in your javascript file that can be called by the server methods for server to client communication.
The SignalR documentation can be found here
The SignalR Nuget package installation procedure can be found here 

Lets see some code …
1.       Install Nuget package . In this example I am hosting the hub inside asp.net mvc app.
2.       Register the routing for signalr hub to be accessed through URL . Note: the signalr route registration should come before the asp.net mvc route registration.
If you don’t specify an alternative path name. The default /signalr/hubs will be used
        protected void Application_Start()
        {
            RouteTable.Routes.MapHubs();
            RegisterRoutes(RouteTable.Routes);
           
        }



3.       Server Code : I created a hub class called ReportHub. All Hub classes should inherit from the base Hub Class.
The ReportHub class now will have access to the public properties defined in the HubClass
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalRDemo
{
    public class ReportHub : Hub
    {
         public void NotifyClients()
        {
            //notify all other clients to update their data
            Clients.Others.updateReport1();
            Clients.Others.updateReport2();
        }
       
      
        public void BroadCastData1Available()
        {
            Clients.Others.updateReport1();
        }

        public void BroadCastData2Available()
        {
            Clients.Others.updateReport2();
        }

    }
}

The ReportHub has three server calls that can be invoked by clients.
Looking NotifyClients() in detail

      In this line of code Clients.Others.updateReport1();
      updateReport1 is a method defined in the client.

I am sending out the notification to all clients except for the one who made the server call. If you           want the notifier  itself to be notified too, You can use Clients.All instead of Clients.Others. Note updateReport1() is a method defined in the client. Upon notification the client will execute the updateReport1() method in the javascript.

Some notable properties of Hub.
a.       Clients -  list of clients connected to the hub. This property will give you access to
Clients.All – all clients
Clients.Others – all clients except the one calling the hub’s method
Clients.Caller – the called calling hub method.
b.      Context
c.       Groups

4.       Client Code :
Register the following scripts on your client/view
<script src="/Scripts/jquery.signalR-1.0.0-rc1.min.js" type="text/javascript"></script>
   <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
               
 "~/signalr/hubs” – this is the path defined on your route. When the application is run, the signalR assemblies will use reflection to emit the javascript equivalent of the ReportHub class defined in the assembly.
The hub can be accessed from the client as show below. The connections can be started and an optional call back can be invoked when the connection is started or done.
You can also define methods on the clients to be invoked by the server. The updateReport() method discussed in the above section (Server Code) is define as follows.
        // Declare a function on the myHub hub so the server can invoke it         
        rptHub.client.updateReport1 = function () {
            // do something
        };

       

The whole script of the client is shown below.
$(function () {
        // Proxy created on the fly         
        var rptHub = $.connection.reportHub;

        // Declare a function on the rptHub hub so the server can invoke it         
        rptHub.client.updateReport1 = function () {
            RefreshData('map_canvas');
        };

        rptHub.client.updateReport2 = function () {
            RefreshData('map_canvas2');
        };

        // Start the connection
        $.connection.hub.start().done(function () {
          
        });
     
    });
How can we call the server from the client?You will call the server property of the hub and then you will have access to all the public methods in the hub.
E.g. If you want to invoke the notifyClients() method defined in the server/hub.
    // Call the notifyClients method on the server
       rptHub.server.notifyClients();

 Putting it all together
I have included a demo asp.net mvc application hosting a signalR hub. The application has a dashboard page which has two geomap charts  and there is an admin page with three buttons. Clicking the buttons on the admin page will notify the charts on the dashboard to update their content with a new data. The demo shows the bi-directional communication from the client to the server and vice versa.
 Admin page to Server Hub => client to server
Server Hub to Dashboard page => server to client
The full demo can be downloaded from here


        




Wednesday, September 5, 2012

Ghostery - Tracking the Trackers

Ever wondered who is tracking you? Well apparently you can know that.

Ghostery claims to work with more than a 1000 ad networks, behavioral data providers, web publishers, and other companies interested in your browser activity.

This browser plugin allows you to see what companies are tracking you (i.e. reading or writing tracking cookie) in your browser. This trackers are basically interested in your age,sex,shopping pattern, hobbies and interests so that they share that information to advertisers who want to run targeted ads.

Ghostery shows you the list of trackers with the information they track. You can only see the description of the company , what they do and links to their site etc. It also gives you the option to block advertisers, analytics and widgets etc. Thus putting you on the control of which companies you share your information with.
But beware that  blocking trackers might produce an unexpected experience while browsing sites which rely on information availed through trackers to tailor your browsing experience.

You can install this plugin on the browser you are using . I tried it with  Firefox and Google Chrome.

Click here  to go to Ghostery site.

Tuesday, July 12, 2011

My experience with SmartGit

I was looking for a repository client for a Git repository. The first client I experimented with was TortoiseGit. I love tortoise products. I specifically used tortoiseHg in my last project. However, my experience with tortoiseGit was disastrous. I couldnot make it use the ignore patterns defined in .ignore or in the exclude file. Thus, after messing up with it for a while, I looked for other clients which are free for personal use and I stumpled upon on SmartGit, as you guessed it; It was love at first sight!

SmartGit is lovely, easy to use and has elegant user interface. I was able to install it and started using it in a heart beat.It reads and applies the ignore patterns listed in the .ignore file. However, it doesnot have the contextual menu to access repository commands by right clicking in a folder structure. You have to start the client in order to open the local repository to do your staging, commiting and other related stuff.

You can download and evaluate SmartGit here

Cheers!

Thursday, March 31, 2011

Cross domain page request using jquery

Have you ever wanted to display content from another domain into you site using client side scripts? At this moment you may already know it is not possible make ajax request to a different domain or subdomain using javascript, since it violates the same origin policy

Luckily, there is a work around to it.

You can achieve this by including a proxy page that is dedicated to making a server side request to the intended page in the other domain and return the contents retrieved as its own content. How cool is that? J

Then you can make ajax request to the proxy page using jquery and further filter the content using selectors and integrate it into your Page.

The code below demonstrates how to load content from www.example.com .

Proxy page: uses System.Net classes to make http request and receive the response .If the request is successful, i.e. Status Code is 200, and it will read the response stream from the cross domain request and return the content read in its response.

Proxy.aspx.cs:

using System;

using System.IO;

using System.Net;

namespace CrossDomainPageRequestSample

{

public partial class Proxy : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

// ‘loadUrl‘ is the address to the page in the other domain

var url = Request.QueryString["loadurl"];

// create a request

HttpWebRequest request = (HttpWebRequest)

WebRequest.Create(url);

// make the request

var response = (HttpWebResponse)request.GetResponse();

// we will read data via the response stream

if (response.StatusCode == HttpStatusCode.OK)

{

var contentReader = new StreamReader(response.GetResponseStream());

Response.ContentType = response.ContentType;

Response.Write(contentReader.ReadToEnd());

}

}

}

}

Proxy.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Proxy.aspx.cs" Inherits="CrossDomainPageRequestSample.Proxy" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>title>

head>

<body>

<form id="form1" runat="server">

<div>

div>

form>

body>

html>

DefaultPage:

This page makes Ajax request to the Proxy page and filters the content returned and appends to the div with id ‘otherSiteContent’.

$('#otherSiteContent').load('proxy.aspx?loadurl=http://www.example.com/ #header', function () { });

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

CodeBehind="Default.aspx.cs" Inherits="CrossDomainPageRequestSample._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js">

script>

<script type="text/javascript">

$(document).ready(function () {

// the script below loads the proxy page and further applies id selector #header and appends the content to

// the div #otherSiteContent

$('#otherSiteContent').load('proxy.aspx?loadurl=http://www.example.com/ #header', function () {

});

});

script>

asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<div>

div>

Page Content from the other site goes below

<div id="otherSiteContent">

div>

asp:Content>

DefaultPage.aspx.cs

using System;

namespace CrossDomainPageRequestSample

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

}

}

Wednesday, March 30, 2011

Controlling the Serialization process by implementing ISerializable

In my current project we keep items in the cache to share them among multiple requests. When items are added to the cache they are serialized by the runtime. However, the default serialization process makes use of reflection to determine the object structure, its contents and relationship with other objects and serializes all public and protected fields. Thus the cached items size tends to be large and the process is a bit slower.

Thus to alleviate the problems described above, I wanted to have a fine grained control on the serialization process and explicitly state which fields are to be serialized and avoid using reflection to determine the object properties.

Fortunately .Net allows you to control the serialization process in many ways. However, this topic demonstrates how to achieve this result by extending the ISerializable class.

Steps to follow

1. The class to be serialized should to be decorated by [Serializable] attributes.

2. The class needs to extend ISerializable in System.Runtime.Serialization. In doing so you will implement GetObjectData(SerializationInfo info, StreamingContext context). Inside this method you will access the serialization info and provide alternate values for the fields to be serialized as namevalue pairs. Later the serializer will make use of the new values.

3. Provide a second constructor like

Employee (SerializationInfo info, StreamingContext context).

In this constructor, access the serialization info to reconstruct the serialized fields.

Note: a derived class needs to call the base class’s new constructor (i.e. the base class should also implement Iserializable) to recover the serialized fields. Or alternatively, the derived class needs to serialize/deserialize the fields of the parent class.

The following code puts all the pieces together. Besides it shows you how to serialize a collection property.

[Serializable]

public class Employee : ISerializable

{

public string Name { get; set; }

public int Id { get; set; }

public IEnumerable&lt;Address> Addresses { get; set; }

public Employee()

{

}

public Employee(SerializationInfo info, StreamingContext context)

{

Name = info.GetString("N");

Id = info.GetInt32("Id");

Addresses = (List&lt;Address>) info.GetValue("Addresses", typeof (List&lt;Address>));

}

public void GetObjectData(SerializationInfo info, StreamingContext context)

{

info.AddValue("N",Name);

info.AddValue("Id",Id);

info.AddValue("Addresses",Addresses);

}

}

[Serializable]

public class Address:ISerializable

{

public string Street { get; set; }

public Address()

{

}

public Address(SerializationInfo info, StreamingContext context)

{

Street = info.GetString("St");

}

public void GetObjectData(SerializationInfo info, StreamingContext context)

{

info.AddValue("St",Street);

}

}