Pages

Wednesday 18 December 2013

Implement Search Engine in ASP.NET Web Site

This sample shows how to implement a search engine that can search contents (articles or posts...) in an ASP.NET website.

Download Sample Project

==============================================================================
ASP.NET APPLICATION : CSASPNETSearchEngine Project Overview
==============================================================================

//////////////////////////////////////////////////////////////////////////////
Summary:

This sample shows how to implement a simple search engine in an ASP.NET web site.

//////////////////////////////////////////////////////////////////////////////
Demo the Sample:

Open Default.aspx page, input one or more keywords into the text box. 
Click the submit button.

//////////////////////////////////////////////////////////////////////////////
Code Logical:

1. Create the database.
  a. Create a SQL Server database named "MyDatabase.mdf" within App_Data folder.
  b. Create a Table named "Articles" in the database.

     ID       bigint (Primary Key)
     Title    nvarchar(50)
     Content  varchar(MAX)

  c. Input some sample records to the Table.

2. Data Access.
  a. Create a class named "Article" represents a record.
  b. Create a class named "DataAccess" to access database. This class contains 
     public methods GetArticle(), GetAll() and Search(). Within Search() method,
     the key code is generating a complex Sql command which is used to search database.

       // Generate a complex Sql command.
       StringBuilder builder = new StringBuilder();
       builder.Append("select * from [Articles] where ");
       foreach (string item in keywords)
       {
           builder.AppendFormat("([Title] like '%{0}%' or [Content] like '%{0}%') and ", item);
       }

       // Remove unnecessary string " and " at the end of the command.
       string sql = builder.ToString(0, builder.Length - 5);
3. Search Page.
  The key controls of this page is TextBox control named "txtKeyWords" which 
  is used to input keywords, and Repeater control which is used to display
  result.
  And there is a JavaScript function which is used to hightlight keywords
  in the result.

       for (var i = 0; i < keywords.length; i++)
       {
           var a = new RegExp(keywords[i], "igm");
           container.innerHTML = container.innerHTML.replace(a, "$0");
       }
4. The Detail Page.
  This page receives a parameter from Query String named "id", and then call 
  DataAccess class to retrieve a individual record from database to show in the page.

You can VIEW in MSDN also..
By,
Akash Roy,
CEO, JPR Infoserve,
http://jprinfoserve.com

How to design a simple AJAX web chat (CSASPNETAJAXWebChat)


Download the sample project

Introduction

The project illustrates how to design a simple AJAX web chat application. We use jQuery, SP.NET AJAX at client side and LINQ to SQL at server side. In this sample, we could create a chat room and invite someone else to join in the room and start to chat.

Running the Sample

Step 1:               Open the CSASPNETAJAXWebChat.sln. Press F5 to open the default.aspx.
Step 2:               By default, we could see two chat rooms in the list, you can click the button, "Create chat room", to create your own chat room. Before that button, we could see a textbox, we can input our chatting alias before joining into the room.
Step 3:               Click any "Join" button at the end of each row. You will see a popup chat room window.
Step 4:               Open a new browser and make the same steps to impersonate another user to join in the same chat room.
Step 5:               When we input one message, we will see both of the chat room windows will show the messages.
Step 6:               Validation is finished.

Using the Code

Step 1:               Create an "ASP.NET Empty Web Application" in Visual Studio 2010/Visual Web Developer 2010. In this sample it is "WebChat".
Step 2:               Right-click the App_Data directory, and click Add -> New Item -> SQL Server DataBase. In this sample it is "SessionDB.mdf".
Step 3:               Open the database file and create four tables.
         * tblChatRoom: store chat room data.
         * tblMessagePool: store the chat message data temporarily.
         * tblSession: store the user session data.
         * tblTalker: store the user data who in the chat rooms.
         The details columns for these tables, please refer to the SessionDB.mdf in this sample.
Step 4:               Create a new directory, "Data". Right-click the directory and click Add -> New Item -> Linq to SQL classes.(If you could not find that template, please click the Data node of the tree view at the left hand.) In this sample, it is SessionDB.dbml.
Step 5:               Open the SessionDB.dbml and double-click the SessionDB.mdf, you will see the database in the Server Explorer. Expand the SessionDB.mdf, expand the Tables folder, and select the four tables, and drag them all to the stage of the SessionDB.dbml.
Step 6:               Create a new directory, "Logic". We need to create some class files.
         * ChatManager.cs: we have some static methods to control the data in the database by using Linq.
   * ChatRoom.cs: it is a DataContract used to send the chat room data                                   to the client side by WCF service.
     * Message.cs: it is a DataContract used to send the message data  to the client side by WCF service.
 * RoomTalker.cs: it is a DataContract used to send the talker data in one chat room to the client side by WCF service.
For the details of these classes, please refer to these four files in this sample.
Step 7:               Create a new directory, "Services". Right-click the directory and click
         Add -> New Item -> AJAX-enabled WCF service. In this sample, it is Transition.svc.
Add these two attributes for that class to make sure that the session is allowed.
C#
[ServiceContract(Namespace = "http://CSASPNETAJAXWebChat", SessionMode = SessionMode.Allowed)] 
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
 
In this file, we create some WCF service method which could be used by the client side to execute.
 For the details of these classes, please refer to the Transition.svc in this sample.                          
Step 8:               Create a new directory, "Scripts". Right-click the directory and click
  Add -> New Item -> Jscript File. We need to create some js files to call the WCF service from client side. And there are some page logic codes for this sample; they could be defined by user requirement.
 ASP.NET AJAX allows us to add some service references. So the ScriptManager will generate the client service contract scripts automatically. And what we need to do is just call the service method like we use them at server side. For example, we call the LeaveChatRoom method in the Transition.svc, we could write the JavaScript function like this:
C#
csaspnetajaxwebchat.transition.LeaveChatRoom(RoomID,SuccessCallBack,FailCallBack); 
 
 * csaspnetajaxwebchat is the namespace for this application.
* transition is the service name.
 * LeaveChatRoom is the method name.
 Because of this method has one parameter, the RoomID stands for that parameter, if we have two or more parameters for one methed, just write them before SuccessCallBack.
 * SuccessCallBack is a function used to be fired when the service called successfully.
* FailCallBack is a function used to be fired when the service called unsuccessfully.
For more details about these script functions, please refer to the files in this sample.(chatbox.js, chatMessage.js, chatRoom.js).
Step 9:               Open the Default.aspx,(If there is no Default.aspx, create one.) Create a ScriptManager control and add a service reference and a script reference like below.
HTML
<asp:ScriptManager ID="ScriptManager1" runat="server"           <Services               <asp:ServiceReference Path="~/Services/Transition.svc" /> 
           </Services> 
           <Scripts               <asp:ScriptReference Path="~/Scripts/chatbox.js" /> 
           </Scripts> 
        </asp:ScriptManager> 
 
Step 10:            In the Head block, add some js and css references from the CDN.
HTML
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script><script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.min.js"></script> 
        <script type="text/javascript" src="scripts/chatRoom.js"></script> 
        <link rel="Stylesheet" type="text/css" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/dark-hive/jquery-ui.css" /> 
 
We use these references to make this sample to write code easier and looks better.
There are some other UI markups, please refer to the Default.aspx in this sample.
 For more details about CDN, please view the links listed in the References part at the end of this ReadMe file.
Step 11:            Create a new web page. In this sample, it is "ChatBox.aspx".  In that page, we create some UI controls to send and receive messages. For more details, please refer to the ChatBox.aspx in this sample.
Step 12:            Build the application and you can debug it.

you can check the original artice from here

By,
Akash Roy,
CEO, JPR Infoserve,
http://jprinfoserve.com

Monday 16 December 2013

State Management In Asp.Net

In this article I'm going to discuss about various state management techniques used in Asp.Net.

Introduction

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help us to preserve data on both a per-page basis and an application-wide basis.


Types of State Management

We can categorize the state management techniques in following 2 types:

1. Client Side State management
2. Server Side State Management


Client Side State Management

Client side state management can be of following types:

1. Hidden Field: Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.


To declare a hidden field on aspx page we need to put the following asp.net control:
     <asp:HiddenField ID="HiddenField1" runat="server">

To Set the value of a hidden field from the code behind we need to put the following code:

 HiddenField1.Value="123";

2. ViewState: The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.

When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.

We can use ViewState in the following manner:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
 }   {
       if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            Label1.Text = ViewstateVal.ToString();
            ViewState["count"]=ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
       Label1.Text=ViewState["count"].ToString();
}

3. Control State: Control state is an object comprised of critical view state data that Web server controls need to function, and is contained in a separate object from normal view state information. Control state data is not affected when view state is disabled at the Page level, but requires extra implementation steps to use.
We can use control state in the following manner:
// Load ViewState and ControlState. 
// 
public override void Load()
{
    Stream stateStream = GetSecureStream();

    // Read the state string, using the StateFormatter.
    StreamReader reader = new StreamReader(stateStream);

    IStateFormatter formatter = this.StateFormatter;
    string fileContents = reader.ReadToEnd();

    // Deserilize returns the Pair object that is serialized in 
    // the Save method.
    Pair statePair = (Pair)formatter.Deserialize(fileContents);

    ViewState = statePair.First;
    ControlState = statePair.Second;
    reader.Close();
    stateStream.Close();
}
3. CookiesA cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
We can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data.
Cookie can be of 2 types:
 a. Persistent Cookies: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.
Example:
            Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";
       Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);
 b. Non-Persistent Cookies: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.
Example: Response.Cookies["nameWithPCookies"].Value = "This is A Non Persistance Cookie";
3. QueryStringQuery String is information that is appended to the end of a page URL. A typical query string might look like the following examples:
  http://www.contoso.com/listwidgets.aspx?category=basic&price=100
to get the query string values from code behind we can use the following code:
  String Category=Request.QueryString["category"].ToString();
 Int Price=Convert.ToInt32(Request.QueryString["category"]
.ToString());
Server Side State Management

Server side state management can be of following types:
1. Application StateASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.
Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.
Example:
Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The Application Object
Label1.Text = Application["Count"].ToString(); //Get Value from the Application Object     

Application events in ASP.NET

There are three types of events in ASP.NET. Application event is written in a special file called Global.asax. This file is not created by default, it is created explicitly by the developer in the root directory. An application can create more than one Global.asax file but only the root one is read by ASP.NET.
Application_start: The Application_Start event is raised when an app domain starts. When the first request is raised to an application then the Application_Start event is raised. Let's see the Global.asax file. 
Application_Error: It is raised when an unhandled exception occurs, and we can manage the exception in this event.
Application_End: The Application_End event is raised just before an application domain ends because of any reason, may IIS server restarting or making some changes in an application cycle. 
3. Session StateASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session.
Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
Example:
Session["Count"] = Convert.ToInt32(Session["Count"]) + 1;//Set Value to The Session
Label2.Text = Session["Count"].ToString(); //Get Value from the Sesion 

Session Events in ASP.NET  

To manage a session, ASP.NET provides two events: session_start and session_end that is written in a special file called Global.aspx in the root directory of the project. 
Session_Start: The Session_start event is raised every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.  
Session_End: The Session_End event is raised when session ends either because of a time out expiry or explicitly by using Session.Abandon(). The Session_End event is raised only in the case of In proc mode not in the state server and SQL Server modes. 
There are four session storage mechanisms provided by ASP.NET:
  • In Proc mode 
  • State Server mode  
  • SQL Server mode 
  • Custom mode 
In Process mode: In proc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server is restarted the session values will be lost. 
<configuration>
 <sessionstate mode="InProc" cookieless="false" timeout="10" 
    stateConnectionString="tcpip=127.0.0.1:80808" 

    sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration>
In State Server mode: This mode could store session in the web server but out of the application pool. But usually if this mode is used there will be a separate server for storing sessions, i.e., stateServer. The benefit is that when IIS restarts the session is available. It stores session in a separate Windows service. For State server session mode, we have to configure it explicitly in the web config file and start the aspnet_state service.
<configuration>
<sessionstate mode="stateserver" cookieless="false" 
   timeout="10"  stateConnectionString="tcpip=127.0.0.1:42424"  
   sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/> </configuration>
In SQL Server mode: Session is stored in a SQL Server database. This kind of session mode is also separate from IIS, i.e., session is available even after restarting the IIS server. This mode is highly secure and reliable but also has a disadvantage that there is overhead from serialization and deserialization of session data. This mode should be used when reliability is more important than performance.
<configuration>
    <sessionstate mode="sqlserver" cookieless="false" timeout="10" 
       stateConnectionString="tcpip=127.0.0.1:4  2424" 
       sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration>
Custom Session mode: Generally we should prefer in proc state server mode or SQL Server mode but if you need to store session data using other than these techniques then ASP.NET provides a custom session mode. This way we have to maintain everything customized even generating session ID, data store, and also security.
Following are the important attributes of session states:
Attributes  Description 
Cookieless true/false  Indicates that the session is used with or without cookie. cookieless set to true indicates sessions without cookies is used and cookieless set to false indicates sessions with cookies is used. cookieless set to false is the default set. 
timeout Indicates the session will abound if it is idle before session is abounded explicitly (the default time is 20 min).
StateConnectionStringIndicates the session state is stored on the remote computer (server). This attribute is required when session mode is StateServer
SqlConnectionStringIndicates the session state is stored in the database. This attribute is required when session mode is SqlServer
By,
Akash Roy,
CEO, JPR Infoserve,
http://jprinfoserve.com