Friday, 30 January 2015

Response.IsClientConnected example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class response : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Response.IsClientConnected)
        {
            Response.Redirect("stringlen.aspx", false);
        }
    }
}

Repeter Control in Asp.net with example

A Repeater is a Data-bound control. Data-bound controls are container controls. It creates a link between the Data Source and the presentation UI to display the data. The repeater control is used to display a repeated list of items.

A Repeater has five inline templates to format it:

<HeaderTemplate>

<AlternatingItemTemplate>

<Itemtemplate>

<SeperatorTemplate>

<FooterTemplate>

<HeaderTemplate>

Displays Header text for a Data Source collection and applies a different style for the Header text.

<AlternatingItemTemplate>

Changes the background color or style of alternating items in a Data Source collection.

<Itemtemplate>

It defines how the each item is rendered from the Data Source collection.

<SeperatorTemplate>

It will determine the separator element that separates each item in the item collection. It will be a <br> or <Hr> HTML element.

<FooterTemplate>

Displays a footer element for the Data Source collection.

Now, in this article I am describing the Repeater control in ASP.NET and how to create a comment page in ASP.NET


Repeter_Control_Example.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Repeter_Control_Example.aspx.cs" Inherits="Repeter_Control_Example" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>Repeter Control in ASP.NET</h3>
    <div">
    <table>
    <tr>
    <td>Enter Name:</td>
    <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
      <tr>
    <td>Enter Subject:</td>
    <td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
    </tr>
      <tr>
    <td valign="top">Enter Comments:</td>
    <td><asp:TextBox ID="txtComment" runat="server" Rows="5" Columns="20" TextMode="MultiLine"></asp:TextBox></td>
    </tr>
      <tr>
    <td></td>
    <td><asp:Button ID="btnSubmit" runat="server" Text="Summit" OnClick="btnSubmit_click" /></td>
    </tr>
    </table>
    </div>
    <div>
    <asp:Repeater ID="RepterDetails" runat="server">
    <HeaderTemplate>
    <table style="border:1px solid #0000FF; width:500px" cellpadding="0">
    <tr style="background-color:#FF6600; color:#000000; font-size: large; font-weight: bold;">
    <td colspan="2">
    <b>Comments</b>
    </td>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
    <tr style="background-color:#EBEFF0">
    <td>
    <table style="background-color:#EBEFF0;border-top:1px dotted #df5015; width:500px" >
    <tr>
    <td >
    Subject:
    <asp:Label ID="lblSubject" runat="server" Text='<%#Eval("Subject") %>' Font-Bold="true"/>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Label ID="lblComment" runat="server" Text='<%#Eval("CommentOn") %>'/>
    </td>
    </tr>
    <tr>
    <td>
    <table style="background-color:#EBEFF0;border-top:1px dotted #df5015;border-bottom:1px solid #df5015; width:500px" >
    <tr>
    <td >Post By: <asp:Label ID="lblUser" runat="server" Font-Bold="true" Text='<%#Eval("UserName") %>'/></td>
    <td >Created Date:<asp:Label ID="lblDate" runat="server" Font-Bold="true" Text='<%#Eval("Post_Date") %>'/></td>
    </tr>
    </table>
    </td>
    </tr>
    <tr>
    <td colspan="2">&nbsp;</td>
    </tr>
    </ItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
    </asp:Repeater>
    </div>
    </form>
</body>
</html>

Table Query

CREATE TABLE [dbo].[Comment](
       [UserName] [nvarchar](50) NULL,
       [Subject] [nvarchar](max) NULL,
       [CommentOn] [nvarchar](max) NULL,
       [Post_Date] [datetime] NULL
) ON [PRIMARY]


Complete Program

Repeter_Control_Example.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class Repeter_Control_Example : System.Web.UI.Page
{
 
    SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds;

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=****");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            RepeterData();
        }
    }
    protected void btnSubmit_click(object sender, EventArgs e)
    {
        try
        {
            con.Open();
             cmd = new SqlCommand("insert into Comment (UserName,Subject,CommentOn,Post_Date) values(@userName,@subject,@comment,@date)", con);
            cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = txtName.Text.ToString();
            cmd.Parameters.Add("@subject", SqlDbType.NVarChar).Value = txtSubject.Text.ToString();
            cmd.Parameters.Add("@comment", SqlDbType.NVarChar).Value = txtComment.Text.ToString();
            cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Now.Date;
            cmd.ExecuteNonQuery();
            con.Close();
            txtName.Text = string.Empty;
            txtSubject.Text = string.Empty;
            txtComment.Text = string.Empty;
            RepeterData();

        }
        catch(Exception ex)
            {
               txtComment.Text= ex.Message;
            }

    }
    public void RepeterData()
    {
        con.Open();
        cmd = new SqlCommand("Select * from Comment Order By Post_Date desc", con);
        DataSet ds = new DataSet();
        da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        RepterDetails.DataSource = ds;
        RepterDetails.DataBind();

    }
}

Thursday, 15 January 2015

Events in the Global.asax file

Events in the Global.asax file
The following are important events catered for in the Global.asax file:

Application_Init: Fires when the application initializes for the first time.
Application_Start: Fires the first time an application starts.
Session_Start: Fires the first time when a user’s session is started.
Application_BeginRequest: Fires each time a new request comes in.
Application_EndRequest: Fires when the request ends.
Application_AuthenticateRequest: Indicates that a request is ready to be authenticated.
Application_Error: Fires when an unhandled error occurs within the application.
Session_End: Fires whenever a single user Session ends or times out.
Application_End: Fires when the application ends or times out (Typically used for application cleanup logic).

Wednesday, 14 January 2015

Insert data in table using Ajax



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title>jQuery Submit a form without postback</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="txtname" /></td>
</tr>
<tr>
<td>Subject:</td>
<td> <input type="text" id="txtsubject" /></td>
</tr>
<tr>
<td>Body:</td>
<td> <textarea id="txtbody"></textarea></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
<label id="lblmsg" style="font-weight:bold; color:Red"/>
</form>
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#txtname').val();
var subject = $('#txtsubject').val();
var body = $('#txtbody').val();
if (name != '' && subject != '' && body) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/InsertData",
data: "{'username':'" + name + "','subj':'" + subject + "','desc':'" + body + "'}",
dataType: "json",
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#txtname').val('');
$('#txtsubject').val('');
$('#txtbody').val('');
$('#lblmsg').html("Details Submitted Successfully");
}
},
error: function (result) {
alert("Error");
}
});
}
else {
alert('Please enter all the fields')
return false;
}
})
});
</script>
</body>
</html>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string InsertData(string username, string subj, string desc)
{
string msg = string.Empty;
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd = new SqlCommand("insert into TEMP_User(Name,Subject,Description) VALUES(@name,@subject,@desc)", con))
{
con.Open();
cmd.Parameters.AddWithValue("@name", username);
cmd.Parameters.AddWithValue("@subject", subj);
cmd.Parameters.AddWithValue("@desc", desc);
int i= cmd.ExecuteNonQuery();
con.Close();
if (i == 1)
{
msg = "true";
}
else
{
msg = "false";
}
}
}
return msg;
}

Friday, 2 January 2015

ASP.net application Performance.



Get Ready for Massive Gains
There are certain things you should take into account when you are developing your applications.  Over the last 12 years or so of working with asp and asp.net, I have learned to avoid and do certain things that increase your application performance by a massive amount!  Below are my top 20 tips to improving ASP.net application Performance.
Disable Session State
Disable Session State if you’re not going to use it.  By default it’s on. You can actually turn this off for specific pages, instead of for every page:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="WebApplication1.WebForm1"
EnableSessionState="false" %>
You can also disable it across the application in the web.config by setting the <sessionState> mode value to Off.
Output Buffering
Take advantage of this great feature.  Basically batch all of your work on the server, and then run a Response.Flush method to output the data.  This avoids chatty back and forth with the server.
<%response.buffer=true%>
Then use:
<%response.flush=
true%>
Avoid Server-Side Validation
Try to avoid server-side validation, use client-side instead. Server-Side will just consume valuable resources on your servers, and cause more chat back and forth.
Repeater Control Good,  DataList, DataGrid, and DataView controls Bad
Asp.net is a great platform, unfortunately a lot of the controls that were developed are heavy in html, and create not the greatest scaleable html from a performance standpoint.  ASP.net  repeater control is awesome!  Use it!  You might write more code, but you will thank me in the long run!
Take advantage of HttpResponse.IsClientConnected before performing a large operation:
if (Response.IsClientConnected)
{
// If still connected, redirect
// to another page.
Response.Redirect("Page2CS.aspx", false);
}
What is wrong with Response.Redirect?
Use HTTPServerUtility.Transfer instead of Response.Redirect
Redirect’s are also very chatty.  They should only be used when you are transferring people to another physical web server.  For any transfers within your server, use .transfer!  You will save a lot of needless HTTP requests.
Always check Page.IsValid when using Validator Controls
So you’ve dropped on some validator controls, and you think your good to go because ASP.net does everything for you!  Right? Wrong!  All that happens if bad data is received is the IsValid flag is set to false. So make sure you check Page.IsValid before processing your forms!
Deploy with Release Build
Make sure you use Release Build mode and not Debug Build when you deploy your site to production. If you think this doesn’t matter, think again.  By running in debug mode, you are creating PDB’s and cranking up the timeout.  Deploy Release mode and you will see the speed improvements.
Turn off Tracing
Tracing is awesome, however have you remembered to turn it off? If not, make sure you edit your web.config and turn it off!  It will add a lot of overhead to your application that is not needed in a production environment.
<configuration>
<system.web>
<trace enabled="false" pageOutput="false" />
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
<compilation debug="false" />
</system.web>
</configuration>
Page.IsPostBack is your friend
Make sure you don’t execute code needlessly. I don’t know how many web developers forget about checking IsPostBack!  It seems like such a basic thing to me!  Needless processing!
Avoid Exceptions
Avoid throwing exceptions, and handling useless exceptions. Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications.  Write your code so they don’t happen!  Don’t code by exception!
Caching is Possibly the number one tip!
Use Quick Page Caching and the ASP.net Cache API!  Lots to learn, its not as simple as you might think.  There is a lot of strategy involved here.  When do you cache?  what do you cache?
Create Per-Request Cache
Use HTTPContect.Items to add single page load to create a per-request cache.
StringBuilder
StringBuilder.Append is faster than String + String.  However in order to use StringBuilder, you must
new StringBuilder()
Therefore it is not something you want to use if you don’t have large strings.  If you are concatenating less than 3 times, then stick with String + String. You can also try String.Concat
Turn Off ViewState
If you are not using form postback, turn off viewsate, by default, controls will turn on viewsate and slow your site.
public ShowOrdersTablePage()
{
this.Init += new EventHandler(Page_Init);
}

private void Page_Init(object sender, System.EventArgs e)
{
this.EnableViewState = false;
}
Use Paging
Take advantage of paging’s simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster.  Just be careful when you mix in caching.  How many times do you hit the page 2, or page 3 button?  Hardly ever right!  So don’t cache all the data in the grid! Think of it this way: How big would the first search result page be for “music” on Google if they cached all the pages from 1 to goggle
Use the AppOffline.htm when updating binaries
I hate the generic asp.net error messages!  If I never had to see them again I would be so happy.  Make sure your users never see them!  Use the AppOffline.htm file!
Use ControlState and not ViewState for Controls
If you followed the last tip, you are probably freaking out at the though of your controls not working.  Simply use Control State.  Microsoft has an excellent example of using ControlState here, as I will not be able to get into all the detail in this short article.
Use the Finally Method
If you have opened any connections to the database, or files, etc, make sure that you close them at the end!  The Finally block is really the best place to do so, as it is the only block of code that will surely execute.
Option Strict and Option Explicit
This is an oldy, and not so much a strictly ASP.net tip, but a .net tip in general.  Make sure you turn BOTH on.  you should never trust .net or any compiler to perform conversions for you.  That’s just shady programming, and low quality code anyway.  If you have never turned both on, go turn them on right now and try and compile.  Fix all your errors.
There are hundreds more where these came from, however I really feel that these are the most critical of the speed improvements you can make in ASP.net that will have a dramatic impact on the user experience of your application.  As always if you have any suggestions or tips to add, please let us know!  We would love to hear them!
Have web development!