ListView with ObjectDataSource with Support for ResourceFile in .NET C#

I believe that you have already read y previous article that is N-Tier Architecture with Entity Framework and enjoyed the Entity Framework as well.

Now I will going to show you that how to use ListView with ObjectDataSource and Support Resource File. This is the best way when you are maintaining the Admin side.(As per my experience)

This Tutorial will show you all the things SQL Query, Sorting, Filtering, Paging, ResourceFile etc.

First you need to create a Generic  Query for getting the Employee Detail Pagewise with Sorting functionality implemented. I have written the Query like this you can use your own standards.

CREATE PROCEDURE GetEmployee

                @PageIndex INT = 0,

                @PageSize INT = 10,

                @SortBy NVARCHAR(50) = ”,

                @SortOrder NVARCHAR(50) = ‘ASC’,

                @SearchOn NVARCHAR(MAX) = ”,

                @SearchText NVARCHAR(MAX) = ”,

                @TotalRecCount INT OUT           

AS

BEGIN

                DECLARE @RangeFrom INT =(@PageIndex * @PageSize) + 1

                DECLARE @RangeTo INT =(@PageIndex + 1) * @PageSize

               

                SELECT ID, EmployeeName, Designation FROM

                (SELECT ROW_NUMBER() OVER

                                ( 

                                                ORDER BY           

                                                                CASE WHEN @SortBy=’Employee’ AND @SortOrder = ‘DESC’ THEN e.Name END DESC,

                                                                CASE WHEN @SortBy=’Employee’ AND @SortOrder = ‘ASC’ THEN e.Name END ASC,

                                                                CASE WHEN @SortBy=’Designation’ AND @SortOrder = ‘DESC’ THEN d.Name END DESC,

                                                                CASE WHEN @SortBy=’Designation’ AND @SortOrder = ‘ASC’ THEN d.Name END ASC

                                ) AS RowNumber,

                                e.ID ,e.Name AS EmployeeName ,d.Name AS Designation

                                FROM Employee e INNER JOIN Designation d ON e.ID = d.ID

                                WHERE @SearchOn like ‘%’ + @SearchText + ‘%’

                )temp

                WHERE RowNumber between CONVERT(VARCHAR(10), @RangeFrom) AND CONVERT(VARCHAR(10), @RangeTo)

               

                SELECT @TotalRecCount = COUNT(e.ID) FROM Employee e INNER JOIN Designation d ON e.ID = d.ID

                                WHERE @SearchOn like ‘%’ + @SearchText + ‘%’

END

GO

 

Now next thing is to import this Stored Procedure in edmx and create complex type for this.

For that go to DAL Project and open edmx file and then right click and select “Update Model From Database”  Import the Stored Procedure and then Create function for that. You can create Complex Type or you can use Entity as well. Here We are creating new Complex Type named “EmployeeDetail

Now Build the DAL Project only.

Now Move back to the BAL Project. And Add reference Systes.Data.Entity and Add namespace System.Data.Objects (for ObjectParameter) . Here is the Code that you need to write into your BAL Project in Employee Entity.(In Main Project you need to create object of that entity and Call this method to get the result)

publicList<EmployeeDetail> GetEmpForList(string sortField, string sortDirection, int pageSize, int pageIndex, string searchText, string searchOn, outint totalRecords)

        {

            ObjectParameter TotalRecords = newObjectParameter(“TotalRecCount”, Type.GetType(“System.Int32”));

            List<EmployeeDetail> lstQACategory = db.fnGetEmployee(pageIndex, pageSize, sortField, sortDirection, searchOn, searchText, TotalRecords).ToList();

            totalRecords = Convert.IsDBNull(TotalRecords.Value) ? 0 : (int)TotalRecords.Value;

            return lstQACategory;

        }

All the Parameters used in the SQL Query needs to be passed from here.

Now That’s it done with the BAL and DAL. Now focus on the UI Side and code behind methods.

Now this is the Code that need to be there in aspx page.

<%@PageLanguage=”C#”AutoEventWireup=”true”CodeBehind=”EmpDesignation.aspx.cs”Inherits=”ArchDesign.UI.EmpDesignation”%>

 

<!DOCTYPEhtml>

 

<htmlxmlns=”http://www.w3.org/1999/xhtml”&gt;

<headrunat=”server”>

    <title></title>

</head>

<body>

    <formid=”form1″runat=”server”>

        <div>

            <table>

                <tr>

                    <td>

                        Search On:

                        <asp:DropDownListID=”ddlSearchOn”runat=”server”AppendDataBoundItems=”true”>

                            <asp:ListItemValue=”0″Text=”Select”></asp:ListItem>

                            <asp:ListItemValue=”1″Text=”Employee”></asp:ListItem>

                            <asp:ListItemValue=”2″Text=”Designation”></asp:ListItem>

                        </asp:DropDownList>

                        <asp:TextBoxID=”txtSearchValue”runat=”server”></asp:TextBox>

                        <asp:ButtonID=”btnSearch”runat=”server”Text=”Search”OnClick=”btnSearch_Click”/>

                        <asp:ButtonID=”btnReset”runat=”server”Text=”Reset”OnClick=”btnReset_Click”/>

                    </td>

                </tr>

                <tr>

                    <td>

                        <asp:ListViewID=”lvEmpDesignation”runat=”server”DataKeyNames=”ID”DataSourceID=”odsEmpDesignation”OnPreRender=”lvEmpDesignation_PreRender”>

                            <LayoutTemplate>

                                <tablewidth=”100%”border=”1″cellspacing=”0″cellpadding=”0″>

                                    <tr>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LinkButtonID=”lnkEmployeeName”runat=”server”CommandName=”CustomSort”

                                                CommandArgument=”Employee”OnCommand=”Custom_Command”meta:resourcekey=”lnkEmployeeNameResource”></asp:LinkButton>

                                        </td>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LinkButtonID=”lnkDesignation”runat=”server”CommandName=”CustomSort”

                                                CommandArgument=”Designation”OnCommand=”Custom_Command”meta:resourcekey=”lnkDesignationResource”></asp:LinkButton>

                                        </td>

                                        <tdalign=”left”width=”10%”>

                                            <asp:LabelID=”lblAction”runat=”server”meta:resourcekey=”lblActionResource”></asp:Label>

                                        </td>

                                    </tr>

                                    <asp:PlaceHolderID=”itemPlaceHolder”runat=”server”></asp:PlaceHolder>

                                    <tr>

                                        <tdalign=”right”colspan=”3″>

                                            <asp:DataPagerID=”dpEmpDesignation”runat=”server”PagedControlID=”lvEmpDesignation”PageSize=”10″>

                                                <Fields>

                                                    <asp:NumericPagerField/>

                                                </Fields>

                                            </asp:DataPager>

                                        </td>

                                    </tr>

                                </table>

                            </LayoutTemplate>

                            <ItemTemplate>

                                <tr>

                                    <tdalign=”left”width=”45%”>

                                        <%# Eval(“EmployeeName”) %>

                                    </td>

                                    <tdalign=”left”width=”45%”>

                                        <%# Eval(“Designation”) %>

                                    </td>

                                    <tdalign=”center”width=”10%”>

                                        <asp:ImageButtonID=”hypEdit”runat=”server”CommandName=”CustomEdit”CommandArgument='<%# Eval(“ID”) %>’

                                            OnCommand=”Custom_Command”ImageUrl=”~/Images/edit.png”/>

                                    </td>

                                </tr>

                            </ItemTemplate>

                            <EmptyDataTemplate>

                                <tablewidth=”100%”border=”0″cellspacing=”0″cellpadding=”0″>

                                    <tr>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LabelID=”lblEmpName”runat=”server”meta:resourcekey=”lnkEmployeeNameResource”></asp:Label>

                                        </td>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LabelID=”lblDesignation”runat=”server”meta:resourcekey=”lnkDesignationResource”></asp:Label>

                                        </td>

                                        <tdalign=”center”width=”10%”>

                                            <asp:LabelID=”lblAction”runat=”server”meta:resourcekey=”lblActionResource”></asp:Label>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdalign=”center”colspan=”3″>

                                            <asp:LabelID=”lblNoRecord”runat=”server”meta:resourcekey=”lblActionResource”></asp:Label>

                                        </td>

                                    </tr>

                                </table>

                            </EmptyDataTemplate>

                        </asp:ListView>

                        <asp:ObjectDataSourceID=”odsEmpDesignation”runat=”server”SelectMethod=”GetEmpDesignation”

                            SelectCountMethod=”GetTotalRowCount”EnablePaging=”true”

                            MaximumRowsParameterName=”pageSize”TypeName=”ArchDesign.UI.EmpDesignation”OnSelecting=”odsEmpDesignation_Selecting”>

                            <SelectParameters>

                                <asp:ParameterName=”sortField”Type=”String”/>

                                <asp:ParameterName=”sortDirection”Type=”String”/>

                            </SelectParameters>

                        </asp:ObjectDataSource>

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

 

Note: Method Name you need to remember because this is mandatory for this.

ListView : OnPreRender, OnCommand(Linkbutton in ItemTemplate)

ObjectDataSource : SelectMethod, SelectCountMethod

Here is the code for that

using ArchDesign.BAL;

using ArchDesign.DAL;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace ArchDesign.UI

{

    publicpartialclassEmpDesignation : System.Web.UI.Page

    {

        int totalRecordCount;

        staticstring searchText = “”;

        staticstring searchOn = “”;

 

        ///<summary>

        /// Page Load Event

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                ViewState[“SortBy”] = “Employee”;

                ViewState[“AscDesc”] = “ASC”;

            }

        }

 

        ///<summary>

        /// OnSelect Command whenver you cal DataBind of List this method calls

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid odsEmpDesignation_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)

        {

            e.InputParameters[“sortField”] = ViewState[“SortBy”].ToString();

            e.InputParameters[“sortDirection”] = ViewState[“AscDesc”].ToString();

            e.InputParameters[“searchText”] = searchText;

            e.InputParameters[“searchOn”] = searchOn;

        }

 

        ///<summary>

        /// ListView PreRender Event (Used for set the sortig Image)

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid lvEmpDesignation_PreRender(object sender, EventArgs e)

        {

            if (lvEmpDesignation.Items.Count > 0)

            {

                SetSortImage();

            }

        }

 

        ///<summary>

        /// Handle Click Event of the button used inside the listview

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid Custom_Command(object sender, CommandEventArgs e)

        {

            if (e.CommandName.ToLower() == “customsort”)

            {

                if (ViewState[“AscDesc”] == null || ViewState[“AscDesc”].ToString() == “”)

                    ViewState[“AscDesc”] = “ASC”;

                else

                {

                    if (ViewState[“AscDesc”].ToString() == “ASC”)

                        ViewState[“AscDesc”] = “DESC”;

                    else

                        ViewState[“AscDesc”] = “ASC”;

                }

                ViewState[“SortBy”] = e.CommandArgument;

 

                lvEmpDesignation.DataBind();

            }

            elseif (e.CommandName.ToLower() == “customedit”)

            {

 

            }

        }

 

        ///<summary>

        /// This function is used to show the Sorting is implemented on which column

        ///</summary>

        privatevoid SetSortImage()

        {

            (lvEmpDesignation.FindControl(“lnkEmployeeName”) asLinkButton).Attributes.Add(“class”, “”);

            (lvEmpDesignation.FindControl(“lnkDesignation”) asLinkButton).Attributes.Add(“class”, “”);

 

            LinkButton lnkSortedColumn = null;

            if (ViewState[“SortBy”] != null)

            {

                switch (ViewState[“SortBy”].ToString().ToLower())

                {

                    case”employee”:

                        lnkSortedColumn = lvEmpDesignation.FindControl(“lnkEmployeeName”) asLinkButton;

                        break;

                    case”designation”:

                        lnkSortedColumn = lvEmpDesignation.FindControl(“lnkDesignation”) asLinkButton;

                        break;

                }

            }

            if (lnkSortedColumn != null)

            {

                if (ViewState[“AscDesc”].ToString().ToLower() == “asc”)

                {

                    lnkSortedColumn.Attributes.Add(“class”, “ascending”);

                }

                else

                {

                    lnkSortedColumn.Attributes.Add(“class”, “descending”);

                }

            }

        }

 

        ///<summary>

        /// Get total no of rows in the database

        ///</summary>

        ///<param name=”sortField”></param>

        ///<param name=”sortDirection”></param>

        ///<param name=”searchText”></param>

        ///<param name=”searchOn”></param>

        ///<returns></returns>

        publicint GetTotalRowCount(string sortField, string sortDirection, string searchText, string searchOn)

        {

            return totalRecordCount;

        }

       

        ///<summary>

        /// Get the Employee Detail

        ///</summary>

        ///<param name=”sortField”></param>

        ///<param name=”sortDirection”></param>

        ///<param name=”pageSize”></param>

        ///<param name=”startRowIndex”></param>

        ///<param name=”searchText”></param>

        ///<param name=”searchOn”></param>

        ///<returns></returns>

        publicList<EmployeeDetail> GetEmpDesignation(string sortField, string sortDirection, int pageSize, int startRowIndex, string searchText, string searchOn)

        {

            int pageIndex = startRowIndex / pageSize;

            int totalRecords;

            EmployeeEntity empEntity = newEmployeeEntity();

            List<EmployeeDetail> lstEmpDetail = empEntity.GetEmpForList(sortField, sortDirection, pageSize, pageIndex, searchText, searchOn, out totalRecords);

            totalRecordCount = totalRecords;

            return lstEmpDetail;

        }

 

        ///<summary>

        /// Searching for any Employee/Department

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid btnSearch_Click(object sender, EventArgs e)

        {

            int selectedValue = Convert.ToInt32(ddlSearchOn.SelectedValue);

            if (selectedValue > 0)

            {

                switch (selectedValue)

                {

                    case 1:

                        searchOn = “Employee”;

                        break;

                    case 2:

                        searchOn = “Department”;

                        break;

                }

            }

            searchText = txtSearchValue.Text;

 

            lvEmpDesignation.DataBind();

        }

 

        ///<summary>

        /// Reset the Filter applied on the ListView.

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid btnReset_Click(object sender, EventArgs e)

        {

            searchText = “”;

            searchOn = “”;

            txtSearchValue.Text = “”;

            lvEmpDesignation.DataBind();

        }

    }

}

You just need to remember the parameters that are called in the select method of the objectDataSource. All the InputParameters that are assigning to the ObjectDataSource must be passed and for addition you can use the PageSize and PageIndex(StartRowindex).

 

Now you need to create one Resourcefile for handle multi language data. For that Right click on the UI Project and Add Folder named “App_LocalResources” in this folder you need to create the Resource File with the same name as page here My Page Name is “EmpDesignation.aspx” so my resource file name will be “EmpDesignation.aspx.resx”. This is for English Now if you want to make it for Saudi Arabia then the resultand file name will be “EmpDesignation.aspx.ar-SA.resx”. Create this file and the open this file it will display 3 columns named “Name”, “Value”, “Comment”. Name Is the unique Identifier, Value is the text to display and Comment is just for description.

In this code I have label that having meta:resourcekeyvalue as “lnkEmployeeNameResource” In resource file you need to write following

 

Name

Value

Comment

lnkEmployeeNameResource.Text

Employee

 

addValue

Add Value

 

 

Here resource file will replace the lnkEmployeeNameResource.Text value with “Employee” and addValue with the “Add Value”. You can get the local resource object at javascript or codebehind using following method.

this.GetLocalResourceObject(“addValue “).ToString();

 

General Mistakes :

  • TypeName of ObjectDataSource will be the same as Inherits Property value of the Project.
  • Parameters are not same in the select method. (Use all the parameter name that are preset in the select method.)
  • Add PlaceHolder in the ListView
  • Add DataPager and add the value PageSize.
  • DataSourceID(id of the ObjectDatasource) and DataKeyNames(Unique Identifier) value must be there in the ListView.

 

Enjoy… have a nice Day J

N-Tier Architecture with Entity Framework

Hi,

Today i will show you that how to create N-Tier Architecture with Entity Framework

Hope you know about the N-Tier Architecture so I am starting with creating the Project.

First You need to understand the Naming Convention

1) UI – Presentation Layer

2) BAL – Business Access Layer

3) DAL – Data Access Layer

—————————————————————————————————————————————————————

Now I am starting for creating the Project.

I am selecting “ASP.NET Empty Web Application” and name it as “ArchDesign.UI“. It contains all the aspx, JS, CSS, Images etc.

Now creating another Project, I am selecting “Class Library” and name it as “ArchDesign.BAL“. It contains all the Entity File and major two files BaseEntity and ObjectContextFactory file. I will discuss later about this. So You need to create Entity for every table.

Now creating another Project, I am selecting “Class Library” and name it as “ArchDesign.DAL“. It contains the Entity Framework(edmx).

—————————————————————————————————————————————————————

Now next step is to create Entity Framework. Right Click on the “ArchDesign.DAL” and click on Add new Item then select “ADO.NET entity Data model” name it as “ArchDesign.edmx” > Now select “Generate from Database” and click on Next > Choose your database by clicking on the New Connection button and check the Checkbox which says “Save entity connection settings in App.config as” and name that “ArchDesignEntities” and click on Next > Check all the tables, Views and SP and Functions and Type Proper Model Namespace: Here i am using “ArchDesignModel” and Click on Finish. That’s it completed with Entity Framework. Now Save and Build the DAL Project only.

—————————————————————————————————————————————————————

Now move Back to the BAL Project

Add Reference of the DAL Project and EntityFramework

Add following references into the project. System.Web, System.Web.Entity, System.Web.Entity.Design

Create one “Class file” into it and name it “BaseEntity.cs” and add namespace of DAL.

Add another “Class file” into it and name it “ObjectContextFactory.cs

You will get both of the file on the following URL. Just copy and Paste the required things into it. (Copy all the things and change namespace)

https://drive.google.com/folderview?id=0B0Dm4JdbKHbjMjRRa2NJejNRU0U&usp=sharing

Now open the Base Entity file and you will find the line written as “publicArchDesignEntities db = null;

Change “public” to “Internal” and “ArchDesignEntities” to the name of connectionString written in App.config of DAL Project.

Now you need to create entity of the Tables. Use specific naming convention

I have 2 tables named “Employee”and “Desgination” so my Entity name will be as follows “EmployeeEntity” and “DesignationEntity”. Both the entity will be class file. Access modifier is public and implements the Base Entity. Also add DAL namespace in both the files.

Now implement the Insert, Update, Delete and select operation in the BAL Entity

Reference Code for Designation:

publicclassDesignationEntity : BaseEntity

{

    publicDesignation CurrentRecord { get; set; }

    publicList<Designation> CurrentList { get; set; }

 

    public DesignationEntity()

    {

    }

 

    public DesignationEntity(Designation designation)

    {

        CurrentRecord = designation;

    }

 

    public DesignationEntity(int dID)

    {

        CurrentRecord = GetByID(dID);

    }

 

    privateDesignation GetByID(int id)

    {

        return db.Designations.Where(x => x.ID == id).FirstOrDefault();

    }

 

    publicvoid Create()

    {

        CurrentRecord = db.Designations.Create();

    }

 

    publicvoid Save()

    {

        if (CurrentRecord.ID == 0)

        {

            db.Designations.Add(CurrentRecord);

        }

        else

        {

 

        }

        db.SaveChanges();

    }

 

    publicvoid Delete()

    {

        if (CurrentRecord != null)

        {

            db.Designations.Remove(CurrentRecord);

            db.SaveChanges();

        }

    }

 

    publicList<Designation> getallDesignation()

    {

        return db.Designations.ToList();

    }

}

Implement same for the Employee.

—————————————————————————————————————————————————————

Now Move to the UI section and create one webform that list all the designation in grid.

Give BAL and DAL reference and Add namespace of BAL and DAL

Now Add Connection String into the Web.Config of the UI Project. Just Copy Paste the connectionStrings tag from the App.config of the DAL Project.

Now in the aspx.cs file of the DesignationList just add the following code in Page_Load method  to get the list of all the designaton.

//for listing

DesignationEntity designationEntity = newDesignationEntity();

List<Designation> lstDestignation = newList<Designation>();

 

lstDestignation = designationEntity.getallDesignation();

 

gvDesignation.DataSource = lstDestignation;

gvDesignation.DataBind();

 —————————————————————————————————————————————————————

Now if you want to Add/Update the Record, you just need to code as listed below.

//for adding or Updating

protectedvoid btnSave_Click(object sender, EventArgs e)

{

    int dID = 0;

    DesignationEntity designation = newDesignationEntity(dID);

 

    if (designation != null)

    {

        designation.Create();

    }

 

    //If for adding and else for Updating

    if (dID == 0)

    {

        designation.CurrentRecord.Name = txtDesignation.Text;

    }

 

    designation.Save();

 

    if (dID == 0)

    {

        //Added Successfully.

        dID = designation.CurrentRecord.ID;

    }

    else

    {

        //Updated Successfully.

    }

}

That’s it its al completed and enjoy the Entity framework with N-Tier Architecture

For Common Functions you can add the New Project as “Class Library”. Have a great day….

Contact me if you have any Query.