0 comments Tuesday, January 14, 2014

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,

0 comments Saturday, December 21, 2013

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

}

0 comments Thursday, September 5, 2013

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


0 comments Monday, July 29, 2013

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

0 comments Friday, July 12, 2013

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.

0 comments Thursday, June 27, 2013

Enumerations allows to add constants to be declare in the group. Main idea behind the enums are to make code more readable and maintainable. However these enum names are not suitable for display to the end user. This is most obvious when working with constants that combine two or more words, as no spaces, punctuation or other special characters are permitted.

Ex: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri},
      enum Mode {Create, Delete, Modify}


If we can add description to each enum value then we can display the particular description instead of enum value. This article will focus on adding descriptive attribute to enum using extension method.



Step 1:
Create sample enum like below which is use to store form name categories and add following directive 

using System.ComponentModel;
(To add the descriptive attribute for each enum we should use above directive)

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

namespace EnumExample
{
    public enum FormCategory
    {
        RegistrationForm,
        DisplayClient,
        DeleteClient,       
        EditClient,
        AddNewClient,
    }
}






Step 2 :
Then add the descriptive attribute to each enum which is going to display to end user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace EnumExample
{
    public enum FormCategory
    {
        [Description("Client Registration Form")]
        RegistrationForm,

        [Description("Display Client Information Form")]
        DisplayClient,

        [Description("Delete Client Form")]
        DeleteClient,

        [Description("Edit Existing Client Form")]
        EditClient,

        [Description("Add New Client Form")]
        AddNewClient,
    }
}




Step 3 :
Mechanism behind displaying enum description instead of enum value is .Net Reflection. The extension method will use reflection to examine the values in any enumeration and look for the Description attribute. Where present, the description will be returned. If the description is absent, the constant name will be returned instead.

Create static  class called EnumExampleExtensions.cs and add following directives,
using System.Reflection;
using System.ComponentModel;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace EnumExample
{
    public static class EnumExampleExtensions
    {
    }
}





Step 4:
Create static extension method Description which takes enum as parameter  like below.

public static string Description(this Enum enumValue)
{
            var enumType = enumValue.GetType();
            var field = enumType.GetField(enumValue.ToString());
            var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length == 0
                ? enumValue.ToString()
                : ((DescriptionAttribute)attributes[0]).Description;
}

In above code take the enum value and then resolve its description. GetField method is called, passing the name of the enumeration value provided in the method's parameter. This obtains the field information for the value. Finally check the description attribute and if attribute contains description return the description if not return the enum constant name.

Step 5:
Now it's time to test the code. I'm using console application for test the code.

Code :
Console.WriteLine(string.Format("Enum Value{0}", 
FormCategory.RegistrationForm.ToString()));

Console.WriteLine( 
string.Format("Enum Description{0}", 
FormCategory.RegistrationForm.Description()));
Console.ReadKey();

Output: