Monday 27 February 2012

Singleton Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLayer
{
    public partial class Management
    {
        #region "Code to follow Singleton Design Pattern"

        /// <summary>
        /// Declare a private static variable
        /// </summary>
        private static Management _Instance;

        /// <summary>
        /// Return the instance of the application by initialising once only.
        /// </summary>
        public static Management GetInstance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new Management();
                }
                return _Instance;
            }
            set
            {
                _Instance = value;
            }
        }
        #endregion


        //public List<Company> GetChildCompany(int p)
        //{
        //    throw new NotImplementedException();
        //}

        public void InsertVoucher(Objects.PaymentReceipt newVoucher)
        {
            throw new NotImplementedException();
        }
    }
}

Friday 24 February 2012

Return value from storedprocedure

Stored Procedure:-


ALTER PROCEDURE TestInsert
(
@RollNo int,
@Name nvarchar(50),
@Gender varchar(10),
@Age int,
@DOB nvarchar(50),
@Address nvarchar(100),
@ContactNo nvarchar(15),
@Status int,
@Uimage nvarchar(100),
@Result int output
)
as
Begin
set @Result=0
if(exists(select RollNo from RegForm where RollNo=@RollNo))
Begin
update RegForm set Name=@Name,Gender=@Gender,Age=@Age,DOB=convert(datetime,@DOB,103),
Address=@Address,ContactNo=@ContactNo,Status=@Status,Uimage=@Uimage where RollNo=@RollNo
set @Result=1
end
else
Begin
  insert into RegForm (RollNo,Name,Gender,Age,DOB,Address,ContactNo,Status,Uimage)
values
(@RollNo,@Name,@Gender,@Age,convert(datetime,@DOB,103),@Address,@ContactNo,@Status,@Uimage)
set @Result=2
end
end

C# Code:-


public int InsertRecord(ObjectLayer.ObjectLayer objobject)
        {
            int result = 0;
            try
            {              
                SqlCommand com = new SqlCommand("TestInsert", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@RollNo", objobject.RollNo);
                com.Parameters.AddWithValue("@Name", objobject.Name);
                com.Parameters.AddWithValue("@Gender", objobject.Gender);
                com.Parameters.AddWithValue("@Age", objobject.Age);
                com.Parameters.AddWithValue("@DOB", objobject.DOB);
                com.Parameters.AddWithValue("@Address", objobject.Address);
                com.Parameters.AddWithValue("@ContactNo", objobject.ContactNo);
                com.Parameters.AddWithValue("@Status", objobject.Stat);
                com.Parameters.AddWithValue("@Uimage", objobject.Uimage);

                SqlParameter pa1 = new SqlParameter("@Result", SqlDbType.Int);
                pa1.Direction = ParameterDirection.Output;
                pa1.Size = 100;
                com.Parameters.Add(pa1);
                ExecuteStoredProcedure(com);
                result = Convert.ToInt32(com.Parameters["@Result"].Value.ToString());
            }
            catch (Exception ex)
            {
                string s = ex.Message.ToString();
            }
            return result;
        }

Dynamic Loading of ASP.NET User Controls


Introduction

In addition to using Web Server controls in your ASP.NET web pages, you can create your own custom, reusable controls using the same techniques you use for creating ASP.NET web pages. These controls are called User Controls. A User Control is a kind of composite control that works much like an ASP.NET web page - you can add existing web server controls and markup to a User Control, and define properties and methods for the control. You can then embed them in ASP.NET web pages, where they act as a unit.
User Controls are semi-autonomous pages of HTML and underlying ASP.NET code that can be inserted into ASP.NET pages. As such, they are useful for adding blocks of functionality to pages.
Typical uses of User Controls are for use as page headers and footers. Unlike ASP.NET pages that have the .aspx file extension, User Controls typically have the .ascx file extension. Once created, in Visual Studio .NET, they can be included in a specific page by simply dragging the User Control onto the Design view of that page. Alternatively, they can be added to a page at Design time by including the following in the page's HTML. For example, the following line includes a SimpleControl User Control from the SimpleControl.ascx file:
<%@ Register src="~/usercontrols/SimpleControl.ascx" 
    tagname="SimpleControl" tagprefix="SimpleControl" %>
The User Control is then positioned on the page using the following tag:
<SimpleControl:SimpleControl id="ucSimpleControl" 
         runat="server"></SimpleControl:SimpleControl>
Although this procedure is satisfactory for content like headers and footers that will always be required on specific pages, it would be useful if there was a way of dynamically loading specific User Controls at run time.
Fortunately, it is possible to load User Controls onto a page by making use of the LoadControl method. This function has a straightforward syntax - it takes a single argument - the virtual path to the User Control page. For example, to load the SimpleControl User Control, the following C# code would be used within the Page_Loadmethod, or you can use this on the Click event of the button:
usercontrols_SimpleControl ucSimpleControl = 
  LoadControl("~/usercontrols/SimpleControl.ascx") 
  as usercontrols_SimpleControl;
Once the User Control has been loaded, it can be added to the page by adding it to the Controls collection:
Placeholder1.Controls.Add(ucSimpleControl);

Using the Code

First, let's create a User Control and populate it with several controls. The User Control content looks like this:
<table>
    <tr>
        <td><asp:Label ID="label1" runat="server" 
            Text="First Name" ></asp:Label></td>
        <td> <asp:TextBox ID="txtFirstName" 
            runat="server"></asp:TextBox></td>
    </tr>
     <tr>
        <td><asp:Label ID="label2" runat="server" 
           Text="Last Name" ></asp:Label></td>
        <td> <asp:TextBox ID="txtLastName" 
           runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td><asp:Button ID="btnPost"  runat="server" 
            Text="Send Info" OnClick="btnPost_Click" />
        </td>
    </tr>
</table>
Create a delegate just under the namespaces to handle the Click event in the Default.aspx page. After declaring the delegate, create the delegate instance which will be called from the virtual method of the btnPost's click.
public delegate void btnPost_Click(object sender, System.EventArgs e);

public partial class usercontrols_SimpleControl : 
       System.Web.UI.UserControl
{
    #region Public Event

    public event btnPost_Click btnPostClk;

    #endregion

    #region Public Properties

    public TextBox FirstName
    {
        get
        {
            return txtFirstName;
        }
        set
        {
            txtFirstName = value;
        }
    }

    public TextBox LastName
    {
        get
        {
            return txtLastName;
        }
        set
        {
            txtLastName = value;
        }
    }
    #endregion

    #region Vitual Methods

    protected virtual void OnbtnDelQtnMrClk(EventArgs e)
    {
        // Call btnPost_Click event delegate instance
        btnPostClk(this, e);
    }

    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnPost_Click(object sender, EventArgs e)
    {
        //Call Virtual Method
        OnbtnDelQtnMrClk(e);
    }
}
Now, go to the ASPX page where you want to add the User Control and register the User Control by registering the tag in HTML view. The ASPX page content looks like this:
<%@ Register src="~/usercontrols/SimpleControl.ascx" 
    tagname="SimpleControl" tagprefix="SimpleControl" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>This is example of how to add usercontrol dynamically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <asp:Button ID="btnAddControl" runat="server" 
              Text="Click to add SimpleControl" 
              onclick="btnAddControl_Click" />
            <br />
            <asp:PlaceHolder runat="server" 
               ID="Placeholder1" ></asp:PlaceHolder>
            <br />
            <asp:Label ID="lblUser" 
              runat="server"></asp:Label>

    </div>
    </form>
</body>
</html>
To add the User Control on the Click event of "btnAddControl", add the following code to the code-behind:
protected void btnAddControl_Click(object sender, EventArgs e)
{
    // Create instance of the UserControl SimpleControl
    usercontrols_SimpleControl ucSimpleControl = 
      LoadControl("~/usercontrols/SimpleControl.ascx") 
      as usercontrols_SimpleControl;
    
    // Set the Public Properties
    ucSimpleControl.FirstName.Text = "Milind";
    ucSimpleControl.LastName.Text = "Chavan";

    //Create Event Handler for btnPost Click 
    ucSimpleControl.btnPostClk += 
            new btnPost_Click(ucSimpleControl_btnPostClk);

    //Add the SimpleControl to Placeholder
    Placeholder1.Controls.Add(ucSimpleControl);

    // Add the instance of the SimpleControl to Session Variable
    Session.Add((Session.Count + 1).ToString(), ucSimpleControl);

    // Set createAgain = true
    createAgain = true;
}

void ucSimpleControl_btnPostClk(object sender, EventArgs e)
{
   usercontrols_SimpleControl ucSimpleControl = 
               ((usercontrols_SimpleControl)(sender));
   lblUser.Text = "Welcome " + ucSimpleControl.FirstName.Text + 
                  " " + ucSimpleControl.LastName.Text;
}
The most important thing is, after the postback, the User Control vanishes from the page. So to maintain the User Control and its controls' properties as well as events, we need to add this instance of the User Control to the session variable shown above. To generate the User Control again on postback, we use the OnPreInit event:
// Declare 2 variable to handle user control after postback
const string controlID = "MyUserControl";
static bool createAgain = false;

protected Control GetPostBackControl(Page page)
{
    Control control = null;
    try
    {
        string ctrlName = page.Request.Params.Get("__EVENTTARGET");

        if (ctrlName != null && ctrlName != String.Empty)
        {
            control = page.FindControl(ctrlName);
        }
        else
        {
            ContentPlaceHolder cph = 
              (ContentPlaceHolder)page.FindControl("Main");
            for (int i = 0, len = page.Request.Form.Count; i < len; i++)
            {
                string[] ctl = page.Request.Form.AllKeys[i].Split('$');
                if (ctl.Length > 2)
                {
                    control = cph.FindControl(ctl[2]) 
                              as System.Web.UI.WebControls.Button;
                }

                if (control != null) break;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return control;
}

protected override void OnPreInit(EventArgs e)
{
    base.OnPreInit(e);

    Control control = GetPostBackControl(this.Page);

    // Check if the postback is caused by the button 
    // Titled "Click to Create a Dynamic Control"
    // OR
    // createAgain field is true 
    // which means a call is made to the server while the 
    // user control is active  

    if ((control != null && control.ClientID == 
                    btnAddControl.ClientID) || createAgain)
    {
        //should be set before the CreateUserControl method
        createAgain = true;

        CreateUserControl(controlID);
    }
}

protected void CreateUserControl(string controlID)
{
    // createAgain field is set to true in the OnPreInit method
    // when the 'Create User Control' button is clicked 

    // the createAgain field is used to check if the
    // user control is on the page before the call 
    // if so create the control again and add it to the
    // Control Hierarchy again
    try
    {
        if (createAgain && Placeholder1 != null)
        {
            if (Session.Count > 0)
            {
                Placeholder1.Controls.Clear();
                for (int i = 0; i < Session.Count; i++)
                {
                    switch (Session[i].ToString())
                    {
                        case "ASP.usercontrols_simplecontrol_ascx":
                        {
                            // Create instance of the UserControl SimpleControl
                            usercontrols_SimpleControl ucSimpleControl = 
                              LoadControl("~/usercontrols/SimpleControl.ascx") 
                              as usercontrols_SimpleControl;

                            // Set the Public Properties
                            ucSimpleControl.FirstName.Text = 
                              ((usercontrols_SimpleControl)(Session[i])).FirstName.Text;
                            ucSimpleControl.LastName.Text = 
                              ((usercontrols_SimpleControl)(Session[i])).LastName.Text;

                            //Create Event Handler for btnPost Click 
                            ucSimpleControl.btnPostClk += 
                              new btnPost_Click(ucSimpleControl_btnPostClk);

                            //Add the SimpleControl to Placeholder
                            Placeholder1.Controls.Add(ucSimpleControl);
                            break;
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
I know this is one of the known techniques, but I hope it has given you another way to think about dynamically adding controls.

Thursday 23 February 2012

10 tricks that will make your jQuery enabled site go faster

During the last few weeks, I've had the chance to go more in depth with jQyery and general site performance. I've found some techniques that makes my site go much faster. I don't know if they're all best practice, but this article is meant to at least give you some good ideas.


$(document).ready(e) vs $(window).load(e)


The .ready(e) function fires when a dom element is ready. That's why we use it on the document element. When the document element is ready, the page is also, sort of. Actually the page is not ready until the window is fully loaded with images and other resources, but we're allowed to start manipulating the DOM at an earlier stage. I recomend doing your DOM manipulation, resizing, setup menus etc first and then start your ajax calls once the page is fully rendered.

So put your design oriented code in the $(document).ready(e) function and your data oriented code in the $(window).load(e). That way, the page components come to place at an earlier stage and that creates the illusion of speed.


Load JSON from string

In order to avoid the extra cost of doing a page request you can actually include JSON in the page as a string. For instance, I use a jQuery framework to build my menu, but the page lags a bit while waiting for the external scripts that loads the menu elements. I found that the user experience is much faster if I include the menu items as a javascript string at the bottom of the page. The main page will take some milliseconds extra loading, but the menu lagging will dissapear. I then set up the menu in the $(document).ready(e) function and set up the menu before the page data loads.

?
1
2
3
4
5
var menuJSON = '[{....}]'
$(document).ready(function () {
 var menuObject = $.parseJSON(menuJSON);
}


Store repositories in memory

If you load JSON or XML from another script with ajax, keep the returned object in a variable in the window scope. That way, you can do live search and sort operations quickly without loading external resources again. I know some like to do sort in the database, but modern browsers can do it quite quick. It depends on the size of the dataset of course.

?
1
2
3
4
5
6
var userRepository;
$(window).load(function(){
 userRepository = $.ajax(....);
 doSomething(userRepository);
});


Setup events last

You can save a bit of loading time by adding events last. First layout, then data, and then events. Events aren't visible and we want the visible parts of your web site to load first, right? What you could do is to disable buttons until they're loaded with events. This example uses jQueryUI.


?
1
2
3
4
$(document).ready(function(){
 $(":button").button("disable");
});


and then, once an event has been added do all your button code:

?
1
2
3
4
5
6
(window).load(function(){
 $("#button").click(....);
 $("#button").button("enable");
 (...)
});


Unbind events

If you never unbind your events, you could potentially consume quite a lot of unnecessary memory. Even worse you could stack up double events and your click function or keypress trapper could be executed twice. In order to make sure that there's only one click funtion on a DOM element do the following:

?
1
2
3
$("#button").unbind("click");
$("#button").click(....);


.empty() vs html("")

This one is related to the one above. If you write .html("") when you want to empty a div or a list, then there's no guarantee that the events assigned to the child DOM elements are unbound. The jQuery manual states:

"To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves."

So, always use .empty() in stead of .html("")


Load your javascripts at bottom of the page

The new best practice is to load CSS in the head and javascripts at the end of the body. It actually works. If you do, then the page will have read the rest of the page before starting to manipulate it. Hence it appears much faster.

Since javascripts are getting quite heavy in size, it is actually better to let the page load divs and images before large chunks of javascripts. jQuery is just under 80 kb, jQueryUI another 200 kb and I bet you have a few other scripts as well. It all adds up and makes your site slower.

Also, rumors has it that some web search engines only reads a certain amout of text before leaving for another page, and therefore you will be able to present more of the important stuff first.


Don't use a content delivery system

Unless you run a site with tens of thousands of visitors daily or your bandwith costs are very hight, I see no reason to use a CDN. I think what they are trying to achieve is a caching effect. If your visitors allready have the recent jQuery framework cached from Google, they won't have to when they go to your site. But in my experience, CDNs are always a performance drag. They all tend to go slower than my on web hosting and that looses the whole meaning of using these services.


Download the custom version of jQueryUI

The full version of jQueryUi is just under 200kb in size. If you only use button functionallity, you only touch the tip of the iceberg. The custom version of jQueryUI which only holds the core funtionallity and the button package only takes about 13,9 kb. Do the maths, the custom version takes the jQueryUI from being the heaviest file you load on your page to being on of the smallest.

This also explains a problem with using a CDN, since they only have the large version on their site (probably).


RTFM

I mean it, are you familiar with the special selectors in jQuery? How about the .live(...) funtion? It's all in the jQuery documentation. Use it.