Tuesday, June 19, 2012

Serialize JSON string using asp.net and Jquery

As web applications are highly responsive, with asynchronous request to the sever and back to the client. In order to achieve flicker-free effect on web pages the request made to the server is asynchronous. Therefore the data sent to the browser should be in certain format (in our case JSON). Serialize the JSON string before being sent to the web browser.

App_Data/Persons.xml
<?xml version="1.0" encoding="utf-8" ?>
<persons>
    <person id="p101">
        <name>Aisha, Kumari</name>
        <age>28</age>
        <sex>female</sex>
        <nationality>India</nationality>
        <date_of_birth>2000-10-01</date_of_birth>
        <description> Sales manager </description>
    </person>
    <person id="p102">
        <name>Jonathan, Trott</name>
        <age>41</age>
        <sex>male</sex>
        <nationality>United states</nationality>
        <date_of_birth>2000-12-16</date_of_birth>
        <description> A former architect. </description>
    </person>
    <person id="p103">
        <name>Angelina, Jolie</name>
        <age>32</age>
        <sex>female</sex>
        <nationality>United states</nationality>
        <date_of_birth>2000-11-17</date_of_birth>
        <description> Technical operator. </description>
    </person>
    <person id="p104">
        <name>Jagatheesh, Pandian</name>
        <age>35</age>
        <sex>male</sex>
        <nationality>India</nationality>
        <date_of_birth>2001-03-10</date_of_birth>
        <description> Software Engineer. </description>
    </person>
    <person id="p105">
        <name>Jacob,John</name>
        <age>25</age>
        <sex>male</sex>
        <nationality>England</nationality>
        <date_of_birth>2001-09-10</date_of_birth>
        <description> Cheif Executive. </description>
    </person>
    <person id="p106">
        <name>Cynthia, Myriam</name>
        <age>29</age>
        <sex>female</sex>
        <nationality>China</nationality>
        <date_of_birth>2000-09-02</date_of_birth>
        <description> Operations manager. </description>
    </person>
    <person id="p107">
        <name>Nixon, Paul</name>
        <age>45</age>
        <sex>male</sex>
        <nationality>England</nationality>
        <date_of_birth>2000-11-02</date_of_birth>
        <description> A deep sea diver. </description>
    </person>
    <person id="p108">
        <name>Knorr, Stefan</name>
        <age>54</age>
        <sex>male</sex>
        <nationality>United states</nationality>
        <date_of_birth>2000-12-06</date_of_birth>
        <description> Technical Mentor. </description>
    </person>
    <person id="p109">
        <name>Kress, Peter</name>
        <age>43</age>
        <sex>male</sex>
        <nationality>India</nationality>
        <date_of_birth>2000-11-02</date_of_birth>
        <description> Artist. </description>
    </person>

    <person id="p110">
        <name>O'Brien, Tim</name>
        <age>33</age>
        <sex>male</sex>
        <nationality>Ireland</nationality>
        <date_of_birth>2000-12-09</date_of_birth>
        <description> Programmer. </description>
    </person>
</persons>

App_Code/Person.cs
public class Book
{

    /// <summary>
    /// do not change or remove "id", "value" and the "label" variables as atuocomplete need them to be sent    ///back
    /// </summary>
    public string id { get; set; }
    public string label { get; set; }
    public string value { get; set; }
 
    public string Name{get;set;}
    public string Age{ get; set; }
    public string Sex{ get; set; }
    public string Nationality{ get; set; }
    public string Date_of_birth{ get; set; }
    public string Description { get; set; }
}

PersonAutocomplete.ashx
<%@ WebHandler Language="C#" Class="AutoComplete" %>
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Web;
using System.Web.Script.Serialization;

public class AutoComplete : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //  Query string 'term' is for autocomplete. By default, it sends the variable
        //  "term" with the search word to the backend page.
        string searchText = context.Request.QueryString["term"];

        Collection<Person> persons= new Collection<Person>();

        DataSet ds = new DataSet();
        ds.ReadXml(HttpContext.Current.Server.MapPath("App_Data/Persons.xml"));
        DataView dv = ds.Tables[0].DefaultView;
        dv.RowFilter = String.Format("title like '{0}*'", searchText.Replace("'", "''"));

        Person person;
        foreach (DataRowView myDataRow in dv)
        {
            person= new Person();
            person.id = myDataRow["id"].ToString();
            person.value = person.label = person.Name = myDataRow["name"].ToString();
            person.Age= myDataRow["age"].ToString();
            person.Sex= myDataRow["sex"].ToString();
            person.Nationality= myDataRow["nationality"].ToString();
            person.Date_of_birth = myDataRow["date_of_birth"].ToString();
            person.Description = myDataRow["description"].ToString();
            persons.Add(person);
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        string jsonString = serializer.Serialize(persons);

        context.Response.Write(jsonString);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Initially, reference the required Jquery library, Jquery UI library and the CSS in the head section as shown below.

Default.aspx
<link rel="stylesheet" href="Styles/jquery-ui.css" type="text/css" media="all" />
<link rel="stylesheet" href="Styles/site.css" type="text/css" />
<script type="text/javascript" src="Scripts/jquery.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui.min.js"></script>
   
<script type="text/javascript">
        $(function () {
            $('#<%= tbBookName.ClientID %>').autocomplete({
                source: "PersonAutoComplete.ashx",
                select: function (event, ui) {
                    $(".name").text(ui.item.Name);
                    $(".age").text(ui.item.Age);
                    $(".sex").text(ui.item.Sex);
                    $(".date_of_birth").text(ui.item.Date_of_birth);
                    $(".description").text(ui.item.Description);
                }
            });
        });
    </script>

And, put the markup below in the body,

<form id="form1" runat="server">
    <h3>
        AutoComplete Example -- serialize JSON string and return search result
    </h3>
    <div class="search_bar">
        select book:
        <asp:TextBox ID="tbPersonName" runat="server" />
        (try a few examples like: 'Cynthia, Myriam', ' Kress, Peter')</div>
    <div class="search_response">
        <p>
            name: <span class="name"></span>
        </p>
        <p>
            age: <span class="age"></span>
        </p>
        <p>
            sex: <span class="sex"></span>
        </p>
        <p>
            date of birth: <span class="date_of_birth"></span>
        </p>
        <p>
            description: <span class="description"></span>
        </p>
    </div>
    </form>

Get online users list in asp.net

In this post I will explain how to get the list of online users in asp.net.

OnlineUserList.aspx
<asp:GridView ID="gvOnlineUserList" runat="server" Font-Bold="True" AutoGenerateColumns="False">
        <Columns>      
            <asp:BoundField DataField="UserName" HeaderText="User Name" />
            <asp:CheckBoxField DataField="IsOnline" HeaderText="Is Online" />    
            <asp:BoundField DataField="IsApproved" HeaderText="Is Approved" />
            <asp:BoundField DataField="Email" HeaderText="Email" />
            <asp:BoundField DataField="CreationDate" HeaderText="Creation Date" />
            <asp:BoundField DataField="LastActivityDate" HeaderText="Last Activity Time" />
            <asp:BoundField DataField="LastLockoutDate" HeaderText="Last Lockout Date" />
        </Columns>
        <RowStyle BackColor="#EFF3FB" />
        <EditRowStyle BackColor="#2461BF" />        
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <EmptyDataTemplate>          
            No User Online      
        </EmptyDataTemplate>
    </asp:GridView>

OnlineUserList.aspx.cs
public MembershipUserCollection OnlineUsers = new MembershipUserCollection();
public MembershipUserCollection AllUsers = new MembershipUserCollection();
     
protected void Page_Load(object sender, EventArgs e)
{
            if (!Page.IsPostBack)
            {
                this.BindOnlineUsers();
            }
}


private void BindOnlineUsers()
{
            AllUsers = Membership.GetAllUsers();
            foreach (MembershipUser user in AllUsers)
            {
                if (user.IsOnline)
                {
                    OnlineUsers.Add(user);
                }
            }
             gvOnlineUserList.DataSource = OnlineUsers;
             gvOnlineUserList.DataBind();
}

Friday, June 15, 2012

Passing data between asp.net pages

There are so many ways in which you can pass data between asp.net web pages. Data can be passed from one page to other using Querystring, HTTP Post, Public properties, Sessionstate and Controlinfo. Below all approaches were given with an example.

1.Querystring:

Default.aspx
Data : <asp:TextBox ID="DataTextBox" runat="server" Text="Hello World!"></asp:TextBox><br />
<asp:Button ID="btnSend" runat="server" Text="Send" onclick=" btnSend_Click"/>

Default.aspx.cs
protected void  btnSend_Click(object sender, EventArgs e)
{
       Response.Redirect("QueryStringPage.aspx?Data="+Server.UrlEncode(DataTextBox.Text));
 }

TargetPage.aspx
The data received is: <%=Server.UrlDecode(Request.QueryString["Data"]) %>

2. HttpPost:

Default.aspx

Data : <asp:TextBox ID="DataTextBox" runat="server" Text="Hello World!"></asp:TextBox><br />
<asp:Button ID="btnHttpPost" runat="server" Text="Use HttpPost" PostBackUrl="~/TargetPage.aspx"/>

TargetPage.aspx

The data received is: <%=Request.Form["DataTextBox"] %><br />
<fieldset>
        <legend>Data from the source page</legend>
        <asp:Label ID="lblData" runat="server" Text="Label"></asp:Label>
</fieldset>

TargetPage.aspx.cs

using System.Text;

protected void Page_Load(object sender, EventArgs e)
{
            StringBuilder displayValues = new StringBuilder();
            System.Collections.Specialized.NameValueCollection postedValues = Request.Form;
            String nextKey;
            for (int i = 0; i < postedValues.AllKeys.Length; i++)
            {
                nextKey = postedValues.AllKeys[i];
                if (nextKey.Substring(0, 2) != "__")
                {
                    displayValues.Append("<br>");
                    displayValues.Append(nextKey);
                    displayValues.Append(" = ");
                    displayValues.Append(postedValues[i]);
                }
            }
            lblData.Text = displayValues.ToString();
}

3. Public properties

Default.aspx.cs

public string DataToSend
{
       get
       {
             return DataTextBox.Text;
        }
}


protected void btnSend_Click(object sender, EventArgs e)
{
       Server.Transfer("TargetPage.aspx");
}

TargetPage.aspx

<%@ PreviousPageType VirtualPath="~/Default.aspx" %>


The data received is: <%=PreviousPage.DataToSend %>

4. Sessionstate:

Default.aspx.cs

protected void btnSend_Click(object sender, EventArgs e)
{
       Session["Data"] = DataTextBox.Text;
       Response.Redirect("TargetPage.aspx");
}

TargetPage.aspx

The data received is: <%=Session["Data"] %>

5. Control Info
Default.aspx.cs

protected void btnSend_Click(object sender, EventArgs e)
{
       Server.Transfer("TargetPage.aspx");
}

TargetPage.aspx

<%@ PreviousPageType VirtualPath="~/Default.aspx" %>


The data received is: <asp:Label ID="lblData" runat="server" Text="Label"></asp:Label>

TargetPage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
        var textbox = PreviousPage.FindControl("DataTextbox") as TextBox;
        if (textbox != null)
        {
             lblData.Text = textbox.Text;
         }
}

Monday, March 5, 2012

Setting the selected value of dropdownlist in gridview on databind

Write this code in the RowDataBound event of the gridview,
if (sender is GridView)
{
      GridView grid = (GridView)sender;
      grid.SelectedIndex = e.Row.RowIndex;

       if (!string.IsNullOrEmpty(grid.SelectedDataKey["db_field"].ToString()))
       {
             DropDownList ddl = (DropDownList)e.Row.Cells[0].FindControl("controlname");
             ddl.SelectedValue = grid.SelectedDataKey["db_field"].ToString();
        }
        grid.SelectedIndex = -1;
}

Alternatively,

DropDownList ddl = (DropDownList)e.Row.Cells[0].FindControl("controlname");
ddl.SelectedValue = DataBinder.Eval(e.Row.DataItem, "db_field").ToString();

Friday, February 3, 2012

Get Month and Year between two dates in C#.NET

This snippet of code shows how to get Month and Year between two dates. The code below return an array of ListItems.

public ArrayList GetMonthYear(DateTime dtStart, DateTime dtEnd)
{

ArrayList monthList = new ArrayList();
for (DateTime dt = dtStart; dt <= dtEnd; dt = dt.AddMonths(1))
{
monthList.Add(
new ListItem(dt.ToString("MMMM yyyy"), dt.ToString("yyyy")));
}

return monthList;
}

Sample Output:

June 2010
July 2010
August 2010
September 2010
October 2010
November 2010
December 2010
January 2011
February 2011

Friday, December 16, 2011

Get weeks in a month with start and end date of each week using C#.NET

This article explains how to get all weeks in a month with start and end date.

public ArrayList GetWeeks(int _year, int _month)
{
int countDays = DateTime.DaysInMonth(_year, _month);
ArrayList _weeksList = new ArrayList();

for (int i = 1; i <= countDays; i = i + 7)
{
DateTime _startDate = new DateTime(_year, _month, i);
DateTime _finishDate = _startDate.AddDays(6);
string sReturn = _startDate.ToShortDateString()
+ " - " + _finishDate.ToShortDateString();
_weeksList.Add(sReturn);
}

//zero-based array
return _weeksList;
}

Output Sample:

If _year = 2012 and _month = 04, the output would be

01-04-2012 - 07-04-2012
08-04-2012 - 14-04-2012
15-04-2012 - 21-04-2012
22-04-2012 - 28-04-2012
29-04-2012 - 05-05-2012

Get Month Names using C#.NET

This article explains how to get all month names of the year using C#.NET. First create an instance of the class DateTimeFormatInfo and get its CurrentInfo. There is property called MonthNames in the DateTimeFormatInfo which returs an array of month names.

using System.Globalization;
using System.Collections.Generic;

public
ListItem[] GetMonthNamesList()
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
string[] _months = dfi.MonthNames;
List<ListItem> _monthNamesList = new List<ListItem>();
for (int i = 0; i <= 11; i++)
{
_monthNamesList.Add(
new ListItem(_months[i], (i + 1).ToString()));
}
return _monthNamesList.ToArray();
}

Output sample:

January
February
March
April
May
June
July
August
September
October
November
December

Sending email from website using Microsoft Office 365 OAuth2

Step 1: Register an Application in Microsoft Entra ID Sign in to the Microsoft Azure portal: Microsoft Azure Portal Navigate to: Microsoft E...