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

Codeigniter Shield Authorization

Codeigniter Shield Authorization CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provide...