September 2008 - Posts

Below are slides + demos of the presentation I've given on 26-Sept-2008. Feel free to re-use and take advantage of them however you want.


Download the Demo Project from

http://weblogs.asp.net/blogs/brijmohan/DemoPresentation/PhoneBook.zip



Download the Sample project from

http://weblogs.asp.net/blogs/brijmohan/DemoPresentation/A%20Brief%20overview%20of%20ASP.NET%20MVC.zip


Thanks
Brij Mohan

This function calculates the difference between the two Date, and Validate it,

I used this function to validate the difference between the From Date and To Datefor not more then 366 days(to cover the leap year also) or less then 0,

This function is called through the CustomValidator of ASP.NET, but you can also use this without the CustomValidator.

 

To execute the Custom JavaScript from your Validation Control you have to add CustomValidator, the code of which is given belo

<asp:CustomValidator runat="server" ID="custDateValidator"
ClientValidationFunction="CompareDates" Display="Dynamic"
ErrorMessage="The number of date to be included in report must be between 1 and 366">
</asp:CustomValidator>

This following piece of code also shows you how to convert the String to DateTime,because in my Form I am taking the Dates from two HTML TextBoxes, which by default is String, so I had to write seperate piece of code which will convert String to DateTime.

<script language="JavaScript" type="text/javascript">
function CompareDates(source, args) 
{
    var fromDate = new Date();
    var txtFromDate = document.getElementById("txtDateFrom").value;
    var aFromDate = txtFromDate.split("/");
    
    /*Start 'Date to String' conversion block, this block is required because javascript do not provide any direct function to convert 'String to Date' */
    var fdd = aFromDate[0]; //get the day part
    var fmm = aFromDate[1]; //get the month part
    var fyyyy = aFromDate[2]; //get the year part
    
    fromDate.setUTCDate(fdd);
    fromDate.setUTCMonth(fmm-1);
    fromDate.setUTCFullYear(fyyyy);
    
    var toDate = new Date();
    var txtToDate = document.getElementById("txtDateTo").value;
    var aToDate = txtToDate.split("/");
    var tdd = aToDate[0]; //get the day part
    var tmm = aToDate[1]; //get the month part
    var tyyyy = aToDate[2]; //get the year part
    
    toDate.setUTCDate(tdd);
    toDate.setUTCMonth(tmm-1);
    toDate.setUTCFullYear(tyyyy);
    //end of 'String to Date' conversion block
    
    var difference = toDate.getTime() - fromDate.getTime();
    var daysDifference = Math.floor(difference/1000/60/60/24);
    
    difference -= daysDifference*1000*60*60*24;
    
    //if diffrence is greater then 366 then invalidate, else form is valid
    if(daysDifference > 366 daysDifference < 0)
        args.IsValid = false;
    else
        args.IsValid = true;
}
</script>

I know there can be lots of better way to do this, please post as comments if you have some good ideas and example to do the same.

 

Thanks

~Brij

Using Back Button in ASP.NET 2.0 and AJAX

This post will show you how to use ASP.NET 3.5 Ajax COntrolToolKit History control with ASP.NET 2.0,

As you might be aware of that microsoft has included AJAX with Framework 3.0, and from version 3.5 microsoft has also included History control in his AJAX Control toolkit,

Using history control we can use browser back button to navigate backwards in the pages containing AJAX Controls, which was normally not possible till Framework 2.0.

But if you are still using ASP.NET 2.0, then don't get disappointed you can use the same control in ASP.NET 2.0, remember to use this you don't need to install Framework 3.0, or 3.5.

You just need to do the steps given below:

1. Download the DLL, Microsoft.Web.Preview.dll, version 1.1.61025.0 or alrernatively download the source code from here and copy the DLL from bin folder.

2. From the Toolbox of you project, right click and Select Choose Items...

3. Locate the Microsoft.Web.Preview.dll and select OK.

4. You can find see the following tiems in the screenshot below, are added in your toolbox.

 
 
 

 

5. Now add the code below in your web.config

<sectionGroup name="microsoft.web.preview" type ="Microsoft.Web.Preview.Configuration.PreviewSectionGroup, Microsoft.Web.Preview">

<section name="search" type ="Microsoft.Web.Preview.Configuration.SearchSection, Microsoft.Web.Preview" requirePermission ="false" allowDefinition="MachineToApplication"/>

<section name="searchSiteMap" type ="Microsoft.Web.Preview.Configuration.SearchSiteMapSection, Microsoft.Web.Preview"

requirePermission ="false" allowDefinition="MachineToApplication"/>

<section name="diagnostics" type="Microsoft.Web.Preview.Configuration.DiagnosticsSection, Microsoft.Web.Preview"

requirePermission ="false" allowDefinition="MachineToApplication"/>

</sectionGroup>

6. Once you are done with this, open the webpage where you want to use the history control, and add the code below.

<asp:History ID="History1" runat="server" OnNavigate="History1_Navigate">

</asp:History>

 

7. Open the codebehind and add the following piece of code

protected void History1_Navigate(object sender, Microsoft.Web.Preview.UI.Controls.HistoryEventArgs args)

{

int startPage = 0;

if (args.State.ContainsKey("StartPage"))

{

startPage = (int)args.State["StartPage"];

}

GridView1.PageIndex = startPage;

}

protected void GridView1_PageIndexChanged(object sender, EventArgs e)

{

History1.AddHistoryPoint("StartPage, ((GridView)sender).PageIndex);

}

And thats it!!! You are ready to go...

 

This code uses GridView Paging, to demonstrate the HistoryControl

 

You can download the running sample from the here,

C# Code, VB.NET Code

 

You can also refer my post

Using ASP.NET 3.5 Extensions History Control for complete Samples and Videos.

 

This post will provide useful links on how the ASP.NET Extensions Preview allows control over the Browser back button in Ajax. Normally this is not possible using AJAX Controls in WebBrowsers, because AJAX Control's partial postback is not added to the history of Web Browser.

Note : ASP.NET AJAX Extensions are available in the ASP.NET 3.5 Extensions SP1

Watch the video   |   Download the video   |   Get VB code  or  C# code

Important Links :

http://www.asp.net/AJAX/downloads/

http://weblogs.asp.net/davidbarkol/archive/2007/12/28/asp-net-3-5-extensions-history-control-tip.aspx

http://www.bestechvideos.com/2008/06/10/introduction-to-asp-net-ajax-history

http://www.asp.net/learn/ajax-videos/video-149.aspx

 

 

Paging is perhaps one of the most required in data presentation, specially when it comes to huge amount of data, normal paging becomes nightmare. If you are developing your application using ASP.NET 2.0, then you can make use of ObjectDataSource in a very efficient manner to achieve paging.

 

 

The code which I am providing below will give you a complete understanding of how you can do this, this technique will fetch one the number of data which you set in PageSIze of GridView from the DataBase, instead of fetching entire data and on every PageIndexChanged event repeating the full cycle again,

 

 

First you need to either modify or write your procedure the input and output parameters which will fit into your .NET code to get the paging.

 

 

create procedure proc_EmployeeDetails
    @empId int,
    @empStatus varchar(10),
    @pagestart int = null,
    @pagesize int = null,
    @numresults int output
as

create table #empresults
(
    [rowid] [int] IDENTITY (1, 1) NOT NULL,
    [empID] [nchar] (5) ,
    [EmpName] [nvarchar] (30),
    [Address] [varchar] (200),
    [DOB] [datetime],
    [Age] [int],
)


insert into #empresults (empid, empname, address, DOB, Age) 
select empID, EmpName, Address, DOB, Age
where
    empid = @empId    AND empStatus = @empStatus
order by EmpName

set @numresults = @@rowcount 

if @pagesize is null
    set @pagesize = @numresults

if @pagestart is null
    set @pagestart = 1

set rowcount @pagesize

select * 
from #empresults
where rowid >= @pagestart

drop table #tempresults

 

Next I create a Employee class which will hold the results from the database.

 

public class EmployeeCollection : IList<Employee> { }

public class Employee
{
    private int _empId;
    private string _empName;
    private DateTime? _DOB;
    private int _age;
    private string _address;

    public Employee() { }

    public int EmployeeId
    {
        get { return _empId; }
        set { _empId = value; }
    }

    public string EmployeeName
    {
        get { return _empName; }
        set { _empName = value; }
    }

    public DateTime? DOB
    {
        get { return _DOB; }
        set { _DOB = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public string Address
    {
        get { return _address; }
        set { _address = value; }
    }
   
}

 

 

Now as we have got the BusinessObjects, it time to create a class specifically designed to handle request from ObjectDataSource. This class you can keep in your app_code directory of web project and is used like facade layer between UI layer and Business Layer.

 

 

public class EmployeeDataSource
{
    public EmployeeDataSource() { }

    public int SelectCount(int empId, string employeeStatus, ObjectDataSourceSelectingEventArgs e)
    {
        return e.Arguments.TotalRowCount;
    }

    public EmployeeCollection Select(int empId, string employeeStatus, int maximumRows, int startRowIndex, 
    ObjectDataSourceSelectingEventArgs e)
    {
        using (SqlConnection connection = new 
		SqlConnection("Initial Catalog=Employee;Integrated Security=SSPI;Data Source=."))
        using (SqlCommand command = new SqlCommand("proc_EmployeeDetails", connection))
        {
            connection.Open();
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@empId", empId);
            command.Parameters.AddWithValue("@empStatus", employeeStatus);
            command.Parameters.AddWithValue("@pagestart", startRowIndex);
            command.Parameters.AddWithValue("@pagesize", maximumRows);
            command.Parameters.Add(new SqlParameter("@numresults", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, null, 
            DataRowVersion.Default, 0));
            EmployeeCollection employees = new EmployeeCollection();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Employee emp = new Employee();
                    emp.EmployeeId = reader.GetInt32("empId");
                    emp.EmployeeName = reader.GetString("empname");
                    emp.DOB = reader.GetDateTime("DOB");
                    emp.Age = reader.GetInt32("Age");
                    emp.Address = reader.GetString("Address");
                    employees.Add(emp);
                }
            }
            e.Arguments.TotalRowCount = (int)command.Parameters["@numresults"].Value;
            return employees;
        }
    }

 

 

Now I am adding code to the code behind of the EmployeeDetails.aspx page.

protected void objectDataSourceOrders_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
   {
       if (!e.ExecutingSelectCount)
       {
           e.Arguments.MaximumRows = this.gridViewEmployees.PageSize;
           e.InputParameters.Add("e", e);
       }
   }
Here is the ASPX page code that goes along with the rest of this example

 

 

<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="ddlEmpStatus" runat="server">
    <asp:ListItem Text="Active" Value="Active" Selected="True"></asp:ListItem>
    <asp:ListItem Text="Disabled" Value="Disabled"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <div>
        <asp:GridView ID="gridViewEmployees" runat="server" AllowPaging="True" 
            AutoGenerateColumns="False"
            CellPadding="2" DataSourceID="objectDataSourceEmployee" 
            ForeColor="Black" GridLines="None" 
            BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px">
            <FooterStyle BackColor="Tan" />
            <Columns>
                <asp:BoundField DataField="EmployeeId" HeaderText="ProductId" 
                  SortExpression="ProductId" />

                <asp:BoundField DataField="EmployeeName" HeaderText="ProductName" 
                  SortExpression="ProductName" />

                <asp:BoundField DataField="DOB" HeaderText="UnitPrice" 
                  SortExpression="UnitPrice" />
                
                <asp:BoundField DataField="Age" HeaderText="CustomerId" 
                  SortExpression="CustomerId" />

                <asp:BoundField DataField="Address" HeaderText="OrderId" 
                  SortExpression="OrderId" />
            </Columns>
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" 
              HorizontalAlign="Center" />

            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
        </asp:GridView>
        <asp:ObjectDataSource ID="objectDataSourceEmployee" runat="server" EnablePaging="True"
            SelectMethod="Select" TypeName="EmployeeDataSource" 
              OnSelecting="objectDataSourceOrders_Selecting" SelectCountMethod="SelectCount">

            <SelectParameters >
            <asp:QueryStringParameter QueryStringField="empid" DefaultValue="0" Name="empId" />
            <asp:ControlParameter ControlID="ddlEmpStatus" DefaultValue="Active" 
              Name="employeeStatus" PropertyName="Value" />
            </SelectParameters>
            </asp:ObjectDataSource></div>
    </form>
</body>

In the aspx page I am passing the Query string and dropdown control value as a parameter, and Binding the result to the GridView.

 

The code above worked for me, I hope you too find this code useful.

 

Thanks

~Brij
More Posts