Tuesday, January 14, 2014

Lazy Initialization in .NET

Lazy Initialization in .NET

This is the amazing feature that introduced with the .NET 4.0. This is mainly focuses following objectives.

1. Improve performance.
2. Avoid unnecessary computations.
3. Reduce unnecessary memory allocations.
4. Create objects when they are actually need.
5. Provide thread safe facility by framework.

This is very useful when you need create very expensive object when only you need to access members of these objects.

In here I will describe this Lazy initialization with following sample code.

I have created following class for the demonstration and created Order object as two types as lazy object and normal object.

public class Customer
{
        private readonly Lazy<Order> lazyOrder;
        private readonly Order order;

        public int Id { get; set; }
        public string Name { get; set; }

        public Order LazyOrder
        {
            get { return this.lazyOrder.Value; }
        }

        public Order Order
        {
            get { return this.order; }
        }

        public Customer()
        {
            lazyOrder = new Lazy<Order>();
            order = new Order();
        }
}

Following is the testing code for above code,

static void Main(string[] args)
{
    //Create customer object as lasy initialization
    Lazy<Customer> customerObject = new Lazy<Customer>(true);
    //Check whether customer object is actually created or not
    bool isCustomerCreated = customerObject.IsValueCreated;
    //Get the id of the customer
    int id= customerObject.Value.Id;
    //Check whether customer object is actually created after getting the customer Id
    bool isCustomerCreatedFinish = customerObject.IsValueCreated;
          
}

I’m going to initialize the Customer object as Lazy initialization. When you debug the code isCustomerCreated is always false until you need something from the Customer object.

isCustomerCreatedFinish is getting true after you actually access member within Customer object. (get the customer Id)

Also debug the Customer class constructor and there you can also notice until you call method/property inside the Order object it is not getting constructed but normal object will construct even you not call method/property inside order object.

Following is lazy Order object,

Following is normal Order object,

Saturday, December 21, 2013

ASP.NET GridView sorting

Here will explains how to enable sorting on ASP.NET Grid View control. Following are key things that you have to remember when you are enabling sorting in Grid View control.

Here is the Demo Solution
  • Give SortExpression to the columns that you need to sort in grid view.
  • AllowSorting="true" in grid view markup.
  • Create event for "OnSorting" in gridview.
Here is the markup of the GridView.



Code Behind

This is where you convert you data to DataView and assign sorting expression to the DataView and bind the data to the GridView.

As an example sortExpression is like "Id ASC";

private void BindStudents(string sortExpression)
{
            //Get student data as list and convert it to the datatable
            DataTable studentsDt = GetStudents().ToDataTable();
            DataView studentDataView = new DataView(studentsDt);
            studentDataView.Sort = sortExpression;
            StudentGridView.DataSource = studentDataView;
            StudentGridView.DataBind();
}

Then each time you need to keep the track of the current sorting direction("ASC or DESC"). Therefore I have used ViewState to keep track of it.

public string SortingDirection
{
            get { return ViewState[expressionViewStateKey] as string ?? asendingOrder; }
            set { ViewState[expressionViewStateKey] = value; }
}

Then implement the OnSorting event to generate new sorting expression and rebind the data to the gridview.

protected void StudentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
            //Toggle sorting directions according to the current sorting direction
            if (SortingDirection == "ASC")
                SortingDirection = "DESC";
            else
                SortingDirection = "ASC";

            string sortExpression = string.Format(CultureInfo.InvariantCulture, "{0} {1}",
                                                                    e.SortExpression, SortingDirection);
             //Rebind data to the gridview with new soring expression
             BindStudents(sortExpression);

}

Thursday, September 5, 2013

Create Filter Tool using ASP.NET GridView Control

Create Filter Tool using ASP.NET  GridView Control

This post will cover how to implement custom filer tool using ASP.NET GridView Control. Below figure shows the overview of the filter control.

Sample Solution
  1. We need to define <ItemTemplate> and the  <FooterTemplate> for each and every column of the GridView.
  2. Then define   <EmptyDataTemplate> for GridView.
  3. Then you need to maintain GridView information in ViewState, because each time we click the "Add" button we need to bind the changed data again to the GridView. 
  4. "RowCommand" and "RowDataBound" events of the GridView is used for bind the data with the help of ViewState.
Please refer below code,

Define GridView Markup

 <asp:GridView ID="FilterGridView" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" OnRowCommand="FilterGridView_RowCommand" OnRowDataBound="FilterGridView_RowDataBound" ShowFooter="True" ShowHeader="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ColumnDropDownList" runat="server">
<asp:ListItem Text="First Name" Value="FirstName"></asp:ListItem>
<asp:ListItem Text="Last Name" Value="LastName"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ColumnDropDownList" runat="server">
<asp:ListItem Text="First Name" Value="FirstName"></asp:ListItem>
<asp:ListItem Text="Last Name" Value="LastName"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="CriteriaDropDownList" runat="server">
<asp:ListItem Text="Conatins" Value="Contains"></asp:ListItem>
<asp:ListItem Text="Equals" Value="Equals"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="CriteriaDropDownList" runat="server">
<asp:ListItem Text="Conatins" Value="Contains"></asp:ListItem>
<asp:ListItem Text="Equals" Value="Equals"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="FieldValueTextBox" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="FieldValueTextBox" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="OperatorDropDownList" runat="server">
<asp:ListItem Text="And" Value="And"></asp:ListItem>
<asp:ListItem Text="Or" Value="Or"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="OperatorDropDownList" runat="server">
<asp:ListItem Text="And" Value="And"></asp:ListItem>
<asp:ListItem Text="Or" Value="Or"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField>
<FooterTemplate>
<asp:Button ID="btnInsert" runat="Server" Text="Add" CommandName="Insert" UseSubmitBehavior="False" />
</FooterTemplate>
</asp:TemplateField>

</Columns>

<EmptyDataTemplate>
<asp:DropDownList ID="ColumnDropDownList" runat="server">
<asp:ListItem Text="First Name" Value="FirstName"></asp:ListItem>
<asp:ListItem Text="Last Name" Value="LastName"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="CriteriaDropDownList" runat="server">
<asp:ListItem Text="Conatins" Value="Contains"></asp:ListItem>
<asp:ListItem Text="Equals" Value="Equals"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="FieldValueTextBox" runat="server"></asp:TextBox>
<asp:DropDownList ID="OperatorDropDownList" runat="server">
<asp:ListItem Text="And" Value="And"></asp:ListItem>
<asp:ListItem Text="Or" Value="Or"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnInsert" runat="Server" Text="Add" CommandName="EmptyInsert" UseSubmitBehavior="False" />
</EmptyDataTemplate>
</asp:GridView>


RowCommand

if (e.CommandName.Equals("Insert"))
{
DropDownList ColumnsDropDownList = (DropDownList)FilterGridView.FooterRow.FindControl("ColumnDropDownList");
DropDownList CriteriaDropDownList = (DropDownList)FilterGridView.FooterRow.FindControl("CriteriaDropDownList");
DropDownList OperatorDropDownList = (DropDownList)FilterGridView.FooterRow.FindControl("OperatorDropDownList");
TextBox FieldValueTextBox = (TextBox)FilterGridView.FooterRow.FindControl("FieldValueTextBox");

DataTable existingData = (DataTable)ViewState["GridViewData"];
DataRow newData = existingData.NewRow();
newData["FieldName"] = ColumnsDropDownList.SelectedValue;
newData["Criteria"] = CriteriaDropDownList.SelectedValue;
newData["FieldValue"] = FieldValueTextBox.Text;
newData["Operator"] = OperatorDropDownList.SelectedValue;
existingData.Rows.Add(newData);
existingData.AcceptChanges();

ViewState["GridViewData"] = existingData;
}
if (e.CommandName.Equals("EmptyInsert"))
{

DropDownList ColumnsDropDownList = (DropDownList)FilterGridView.Controls[0].Controls[0].FindControl("ColumnDropDownList");
DropDownList CriteriaDropDownList = (DropDownList)FilterGridView.Controls[0].Controls[0].FindControl("CriteriaDropDownList");
DropDownList OperatorDropDownList = (DropDownList)FilterGridView.Controls[0].Controls[0].FindControl("OperatorDropDownList");
TextBox FieldValueTextBox = (TextBox)FilterGridView.Controls[0].Controls[0].FindControl("FieldValueTextBox");

DataTable existingData = (DataTable)ViewState["GridViewData"];
DataRow newData = existingData.NewRow();
newData["FieldName"] = ColumnsDropDownList.SelectedValue;
newData["Criteria"] = CriteriaDropDownList.SelectedValue;
newData["FieldValue"] = FieldValueTextBox.Text;
newData["Operator"] = OperatorDropDownList.SelectedValue;
existingData.Rows.Add(newData);
existingData.AcceptChanges();

ViewState["GridViewData"] = existingData;

}
BindDataToGridView(); 


RowDataBound

DataTable data = (DataTable)ViewState["GridViewData"];
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ColumnsDropDownList = (DropDownList)e.Row.FindControl("ColumnDropDownList");
DropDownList CriteriaDropDownList = (DropDownList)e.Row.FindControl("CriteriaDropDownList");
DropDownList OperatorDropDownList = (DropDownList)e.Row.FindControl("OperatorDropDownList");
TextBox FieldValueTextBox = (TextBox)e.Row.FindControl("FieldValueTextBox");

ColumnsDropDownList.SelectedValue = data.Rows[e.Row.RowIndex]["FieldName"].ToString();
CriteriaDropDownList.SelectedValue = data.Rows[e.Row.RowIndex]["Criteria"].ToString();
OperatorDropDownList.SelectedValue = data.Rows[e.Row.RowIndex]["Operator"].ToString();
FieldValueTextBox.Text = data.Rows[e.Row.RowIndex]["FieldValue"].ToString();
} 

DataBind Method

private void BindDataToGridView()
{
DataTable data = (DataTable)ViewState["GridViewData"];

FilterGridView.DataSource = data;
FilterGridView.DataBind();
}


Monday, July 29, 2013

How to determine SharePoint 2007 versions installed in server

This is quick guide to determine MOSS 2007 versions. I'm writing this post share knowledge because it took while to find out Service Pack versions which are installed on MOSS 2007 servers.

1. Go to Central Admin.
2. Then go to "Operations".
3. Select "Servers in farm" under Topology and Services category.
4. You can see the version of the SharePoint.


5. Follow below table to find out which version of SharePoint/Service pack installed on the server.

Version NameVersion NumberKB
First Release Version (RTM) 12.0.0.4518 N/A
Service Pack 1 12.0.0.6219 KB936988
Service Pack 2 12.0.0.6421 953338
Service Pack 3 12.0.0.6606 2526305

Friday, July 12, 2013

Cannot connect SPD 2013 to SharePoint 2013 online public site

We cannot connect to the SharePoint online 2013 public site using SharePoint Designer 2013. Hovever we can connect to the private silte collections via SPD2013.

Try below steps to connect to the private site collections.

  • Open the SPD 2013
  • Click open site in SharePoint desinger and give the private site collection address.(Make sure to add https instead of http)
  • Then give the online account credentials to login in to the site.