Anshul's Blog
Captcha create in asp.net with C#
Integrating the Mondor’s MSCaptcha in ASP.Net
The DLL of the Mondor’s Captcha is available along with the attached sample code. You simply need to place the DLL inside the BIN folder of your project and then register the control on the page as shown below.
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" %>
 
 
HTML Markup
The following HTML Markup consists of a TextBox, the MSCaptcha control, an ImageButton to refresh the Captcha, a CustomValidator to validate the Captcha and a Button.
<table border="0" cellpadding="3" cellspacing="0">
<tr>
    <td colspan="3">
        Enter Text
        <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
    </td>
</tr>
<tr>
    <td colspan="2">
        <cc1:CaptchaControl ID="Captcha1" runat="server" CaptchaBackgroundNoise="Low" CaptchaLength="5"
            CaptchaHeight="60" CaptchaWidth="200" CaptchaMinTimeout="5" CaptchaMaxTimeout="240"
            FontColor="#D20B0C" NoiseColor="#B1B1B1" />
    </td>
    <td>
        <asp:ImageButton ImageUrl="~/refresh.png" runat="server" CausesValidation="false" />
    </td>
</tr>
<tr>
    <td>
        <asp:CustomValidator ErrorMessage="Invalid. Please try again." OnServerValidate="ValidateCaptcha"
            runat="server" />
    </td>
    <td align="right">
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </td>
    <td>
    </td>
</tr>
</table>
 
 
Refreshing the Captcha Image using Refresh Button
The Mondor’s MSCaptcha automatically refreshes the image when PostBack happens and hence there’s no additional programming required. I have simply added a ImageButton in order to Refresh the Captcha Image.
 
 
Validating the TextBox text against the Captcha Image in ASP.Net
For validation I am making use of ASP.Net CustomValidator with Server Side validation function. When the Button is clicked, the CustomValidator OnServerValidate event is triggered.
Note: For more information on how to use ASP.Net CustomValidator with Server Side validation function, please refer ASP.Net Custom Validator Server Side validation using OnServerValidate event
C#
protected void ValidateCaptcha(object sender, ServerValidateEventArgs e)
{
    Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
    e.IsValid = Captcha1.UserValidated;
    if (e.IsValid)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Valid Captcha!');"true);
    }
}
 
VB.Net
Protected Sub ValidateCaptcha(sender As Object, e As ServerValidateEventArgs)
    Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim())
    e.IsValid = Captcha1.UserValidated
    If e.IsValid Then
        ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Valid Captcha!');"True)
    End If
End Sub
 
 
Web.Config Configuration
You will need to add the following handler to <httpHandlers> in <system.websection of your Web.Config.
 
<add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
 
And add the following handler to <handlers> in <system.webServersection of your Web.Config.
 
<add name="CaptchaImage" verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
 
Create Captcha Image with Refresh Button in ASP.Net
Posted by Anshul
SQL SERVER (TRANSACT-SQL): DATEDIFF FUNCTION

SQL SERVER (TRANSACT-SQL): DATEDIFF FUNCTION

Learn how to use the DATEDIFF function in SQL Server (Transact-SQL) with syntax and examples.

DESCRIPTION

The SQL Server (Transact-SQL) DATEDIFF function returns the difference between two date values, based on the interval specified.

SYNTAX

The syntax for the DATEDIFF function in SQL Server (Transact-SQL) is:

DATEDIFF( interval, date1, date2 )

PARAMETERS OR ARGUMENTS

interval is the interval of time to use to calculate the difference between date1 and date2. It can be one of the following values:

Value (any one of)Explanation
year, yyyy, yyYear interval
quarter, qq, qQuarter interval
month, mm, mMonth interval
dayofyearDay of year interval
day, dy, yDay interval
week, dw, wWeek interval
weekday, ww, wkWeekday interval
hour, hhHour interval
minute, mi, nMinute interval
second, ss, sSecond interval
millisecond, msMillisecond interval

date1 and date2 are the two dates to calculate the difference between.

APPLIES TO

The DATEDIFF function can be used in the following versions of SQL Server (Transact-SQL):

  • SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005

EXAMPLE

Let's look at some SQL Server DATEDIFF function examples and explore how to use the DATEDIFF function in SQL Server (Transact-SQL).

For example:

SELECT DATEDIFF(year, '2012/04/28', '2014/04/28');
Result: 2

SELECT DATEDIFF(yyyy, '2012/04/28', '2014/04/28');
Result: 2

SELECT DATEDIFF(yy, '2012/04/28', '2014/04/28');
Result: 2

SELECT DATEDIFF(month, '2014/01/01', '2014/04/28');
Result: 3

SELECT DATEDIFF(day, '2014/01/01', '2014/04/28');
Result: 117

SELECT DATEDIFF(hour, '2014/04/28 08:00', '2014/04/28 10:45');
Result: 2

SELECT DATEDIFF(minute, '2014/04/28 08:00', '2014/04/28 10:45');
Result: 165
Posted by Anshul Jain
Using the SUBSTRING() SQL Server Function

Using the SUBSTRING() SQL Server Function

Using SUBSTRING() in the SELECT clause

The SUBSTRING() function is used to extract a character string from a given starting position for a given length. 

SELECT  TOP 100
 SUBSTRING(course_designater,6,3) as 'Course number'                   
FROM    Courses
WHERE   course_designater LIKE 'Excel%'    

Format a column using SUBSTRING() and LOWER() and UPPER() functions

It is possible to use the SQL Server LOWER() and UPPER() functions in conjunction with the SUBSTRING() function to accomplish different types of formatting.

SELECT TOP 10
  UPPER(SUBSTRING (lastname,1,1)) + LOWER(SUBSTRING(lastname,2,29)) 
  AS 'Lastname'
FROM Students
Posted by Anshul Jain
JQuery form validations example in asp.net


Introduction: 

In this article I will explain how to show small popup or beautiful style of validation messages or inline form validation messages when validation fails in asp.net using JQuery.


Description: 
   
In previous articles I explained about 
Display validation error messages with images and Change textbox background when validation fails and Ajax Password Strength using asp.net  and many articles on JQUery. Now I will explain how to implement inline form validations when validation fails using JQuery in asp.net.

In one of the website I saw different type of form validations in registration form when we click on submit button without entering any data they are showing some small balloon type validation messages we can implement this functionality easily by using available JQuery plugins.
First open Visual Studio and create new website after that right click on your website and add new folder and give name as JS and insert script files in folder you should get it from attached folder same way add another new folder and give name as CSS and insert required css files in folder you should get it from attached folder. After that write the following code in your aspx page 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Show Inline validation Messages</title>
<link href="css/template.css" rel="stylesheet" type="text/css" />
<link href="css/validationEngine.jquery.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#form1").validationEngine();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table align="center">
<tr>
<td colspan="2">
<div style="border1px solid #CCCCCCpadding10px;">
<table cellpadding="0" cellspacing="30" style=" background-color:White">
<tr>
<td>First Name:</td>
<td><asp:TextBox ID="txtfname"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:TextBox ID="txtlname"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr >
<td>Email:</td>
<td><asp:TextBox ID="txtemail" runat="server"  CssClass="validate[required,custom[email]" />
</td>
</tr>
<tr >
<td>Url:</td>
<td><asp:TextBox ID="txtUrl" runat="server" CssClass="validate[required,custom[url]] text-input" />
</td>
</tr>
<tr>
<td valign="top">Address:</td>
<td>
<asp:TextBox ID="txtaddress" runat="server" TextMode="MultiLine" Rows="8" Columns="26"/></td>
</tr>
<tr>
<td>State:</td>
<td>
<asp:DropDownList ID="ddlState" runat="server" CssClass="validate[required] radio">
<asp:ListItem value="">Choose State</asp:ListItem>
<asp:ListItem Value="AL">Alabama</asp:ListItem>
<asp:ListItem value="AK">Alaska</asp:ListItem>
<asp:ListItem  value="AL">Alabama </asp:ListItem>
<asp:ListItem  value="AK">Alaska</asp:ListItem>
<asp:ListItem  value="AZ">Arizona</asp:ListItem>
<asp:ListItem  value="AR">Arkansas</asp:ListItem>
<asp:ListItem  value="CA">California</asp:ListItem>
<asp:ListItem  value="CO">Colorado</asp:ListItem>
<asp:ListItem  value="CT">Connecticut</asp:ListItem>
<asp:ListItem  value="DE">Delaware</asp:ListItem>
<asp:ListItem  value="FL">Florida</asp:ListItem>
<asp:ListItem  value="GA">Georgia</asp:ListItem>
<asp:ListItem  value="HI">Hawaii</asp:ListItem>
<asp:ListItem  value="ID">Idaho</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Zip:</td>
<td>
<asp:TextBox ID="txtZip" runat="server" CssClass="validate[required,custom[integer]] text-input"/>
</td>
</tr>
<tr>
<td> I Agree Conditions</td>
<td>
<input class="validate[required] checkbox" type="checkbox" id="agree" name="agree"/>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblResult" runat="server" Font-Bold="true"/>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
If you observe above code in header section I added some of script files and css files by using those files we have a chance to show popup messages when validation fails using JQuery in asp.net. Here one thing we need to remember that is if we want add validation for particular control then we need to add css class CssClass="validate[required]" to that particular control.
Posted by Anshul Jain
Example Of MVC is Asp.net

The following picture borrowed from Wikipedia shows the MVC pattern:

MVCDiagram.jpg

MVC divides an application into three concerns:

  • Model - Encapsulates core application data and functionality Domain Logic.
  • View - obtains data from the model and presents it to the user.
  • Controller - receives and translates input to requests on the model or the view.

Scott Guthrie gave a very good and detailed introduction on applying MVC pattern to ASP.NET projects in his blog. For obvious reasons, his introduction is very comprehensive and authoritative. It should be the first reference for application developers who want to understand ASP.NET MVC.

This article is intended to give a simpler tutorial on developing ASP.NET MVC applications in the Microsoft Visual Studio context to help application developers to get a quick start.

When working on ASP.NET MVC web sites, the first thing you may notice is that the URLs to access the web pages are no longer the familiar "http://www.codeproject.com/info/search.aspx" style. Instead the URLs will look likehttp://localhost/VirtualDirectoryName/Controller/Action.

After reading this article, hopefully you will be able to quickly develop your own ASP.NET MVC web applications in Visual Studio. The article is intended to answer the following questions:

  • How are the ASP.NET MVC URLs associated to the resources on the web server?
  • In ASP.NET, what are the Models, Views, and Controllers and how are they implemented?
  • How is information passed among the Models, Views, and Controllers?
  • How does the application code on the server access the data passed to the server by URL parameters and form submissions from the browser?
  • How to access the session data in ASP.NET MVC?
  • How to use code behind when implementing the Views?

This tutorial application is developed in Visual Studio 2008, and the language used is C#. If you have Visual Studio 2010, your environment may be different.

This article comes with the source code for this tutorial. It may be a good idea if you download the source code and run it in your Visual Studio before you start to read this tutorial. This should give you a better idea on the functions implemented in this simple tutorial ASP.NET MVC application. This should make your reading of this article easier. If you are unable to load the source code in your Visual Studio, you may need to first set up your development environment.

Let us begin the tutorial by first setting up our development environment.

Set up the Development Environment

In order to develop MVC ASP.NET applications, you will need to install the Visual Studio ASP.NET MVC Add-on. If you have not done so, you can go to the Microsoft web site to download the Add-on and install it on your computer.

Create an Empty MVC ASP.NET Project in Visual Studio

After installing the ASP.NET MVC Add-on, we can start to create an ASP.NET MVC project in Visual Studio.

CreateEmptyProject.jpg

We can create two types of ASP.NET MVC applications. In this tutorial, we will create an "ASP.NET MVC 2 Empty Web Application". Give the project the name "ASPNetMVCTutorial" and browse a folder where you want to save the files that the Visual Studio will be generating and click the "OK" button.

After the project is created, the solution explorer will have the following contents:

SolutionExplorerBeforeCleaning.jpg

In order to better focus on the MVC pattern in this ASP.NET development, I will be limiting the use of JavaScripts, and CSS style sheets. Let us delete the folders that are not MVC related and add a folder called "Utilities". The "Utilities" folder will be later used to add some utility classes to the project. After the cleaning, the solution explorer will have the following contents:

SolutionExplorerAfterCleaningUtil.jpg

In this project, we can see three folders generated by the "ASP.NET MVC 2 Empty Web Application" template:

  • Models
  • Views
  • Controllers

The models, views, and controllers (MVC) will be added into the corresponding folders later in this tutorial.

You can also notice that there are two "Web.config" files in the project. Most of the configuration information will be in the "Web.config" file in the root folder, the one in the "Views" folder is used to block direct access to the view "aspx" pages. For most of the ASP.NET MVC applications, we do not need to make changes to this "Web.config" file.

Add Some Configurations into the Root "Web.config" File

Before working on creating the models, views, and controllers, let us first change the "<AppSettings />" section of the "Web.config" file in the root folder to the following:

<appSettings>
    <add key="ApplicationName"
            value="A Simple Tutorial on How to Develop ASP.NET
		 Web Projects in MVC Pattern"/>
    <add key="Author" value="Song Li"/>
    <add key="DevelopmentTime" value="5/4/2010"/>
    <add key="DeploymentVirtualDirectory" value=""/>
</appSettings>

The configuration information will be used in the ASP.NET MVC application later.

Add Model Classes to the "Models" Folder

The models in the MVC pattern represent the application data. In this tutorial, we will be developing an application to manage a list of students. The application will allow the users to display, add, and delete the students. Right click the "Models" folder and choose to add a class. Give the class file a name called "StudentsModel.cs".

After the class is added, we can implement the class as the following:

using System;
using System.Data;
 
namespace ASPNetMVCTutorial.Models
{
    public class StudentsModel
    {
        private DataTable Students;
 
        public StudentsModel()
        {
            Students = new DataTable();
            DataColumn IDColumn = Students.Columns.Add
				("ID", Type.GetType("System.Int32"));
            IDColumn.AutoIncrement = true;
            IDColumn.AutoIncrementSeed = 1;
            IDColumn.AutoIncrementStep = 1;
 
            Students.Columns.Add("Name", Type.GetType("System.String"));
            Students.Columns.Add("Score", Type.GetType("System.Int32"));
            Students.Columns.Add("Time Added", Type.GetType("System.DateTime"));
 
            DataColumn[] keys = new DataColumn[1];
            keys[0] = IDColumn;
            Students.PrimaryKey = keys;
 
            Random rd = new Random();
            for (int Idex = 1; Idex <= 5; Idex++)
            {
                DataRow row = Students.NewRow();
                Students.Rows.Add(row);
                row["Name"] = "Student Name No. " + Idex.ToString();
                row["Score"] = 60 + rd.NextDouble() * 40;
                row["Time Added"] = System.DateTime.Now;
            }
        }
 
        public void AddStudent(string Name, int Score)
        {
            DataRow row = Students.NewRow();
            Students.Rows.Add(row);
            row["Name"] = Name;
            row["Score"] = Score;
            row["Time Added"] = System.DateTime.Now;
        }
 
        public void DeleteStudent(int ID)
        {
            DataRow RowToDelete = Students.Rows.Find(ID);
            if (RowToDelete != null)
            {
                Students.Rows.Remove(RowToDelete);
            }
        }
 
        public DataTable GetStudents()
        {
            return Students;
        }
    }
}

This class has a private variable "Students". Its data type is "DataTable". The information for the students is saved in this "DataTable". Besides the constructor, it exposes the methods to add and delete a student. The "GetSudents" method returns the "DataTable" which has the information for all the students to the caller. When an object of this class is first created, the constructor will initiate the "DataTable" and insert 5 randomly generated students in it.

For this ASP.NET MVC application to use the configuration information that we have added to the "Web.config" file, we will add another model class file called "ApplicationInformation.cs":

using System;
using System.Configuration;
 
namespace ASPNetMVCTutorial.Models
{
    public class ApplicationInformation
    {
        private static ApplicationInformation _thisInstance = null;
        private static object _threadLock = new Object();
 
        public string ApplicationName { get; private set; }
        public string Author { get; private set; }
        public string DevelopmentTime { get; private set; }
        public string DeploymentVirtualDirectory { get; private set; }
 
        public ApplicationInformation()
        {
            ApplicationName = ConfigurationManager.AppSettings["ApplicationName"];
            Author = ConfigurationManager.AppSettings["Author"];
            DevelopmentTime = ConfigurationManager.AppSettings["DevelopmentTime"];
            DeploymentVirtualDirectory = 
		ConfigurationManager.AppSettings["DeploymentVirtualDirectory"];
        }
 
        public static ApplicationInformation GetInstance()
        {
            lock (_threadLock)
            {
                if (_thisInstance == null)
                {
                    _thisInstance = new ApplicationInformation();
                }
            }
 
            return _thisInstance;
        }
    }
}

The ASP.NET MVC project will use the class "ApplicationInformation" to access the configurations.

Add a Utility Class to the "Utilities" Folder

To make the later development work easier, we will add a class "ApplicationUtility" to the "Utilities" folder. Right click the "Utilities" folder, and choose to add a class. Give the class file the name "ApplicationUtility.cs" and implement the class as the following:

using System;
using System.Text;
using ASPNetMVCTutorial.Models;
 
namespace ASPNetMVCTutorial.Utilities
{
    public static class ApplicationUtility
    {
        public static string FormatURL(string PathWithoutVirtualDirectoryName)
        {
            ApplicationInformation appInfomation 
                = ApplicationInformation.GetInstance();
            string DeploymentVirtualDirectory 
                = appInfomation.DeploymentVirtualDirectory;
 
            if (DeploymentVirtualDirectory == "")
            {
                return PathWithoutVirtualDirectoryName;
            }
 
            StringBuilder SB = new StringBuilder();
            SB.Append("/");
            SB.Append(appInfomation.DeploymentVirtualDirectory);
            SB.Append("/");
            SB.Append(PathWithoutVirtualDirectoryName);
 
            return SB.ToString();
        }
    }
}

The static method "FormatURL" is used to convert a relative ASP.NET MVC URL to an absolute URL depending on the virtual directory name at the deployment time. The virtual directory name is configured in the "Web.config" file. At development time, we will need to configure it as an empty string. At deployment time, we will have to put the correct virtual directory name in the "Web.config" file.

Add a Master Page for the ASP.NET MVC Project

Before adding the views, we will first add a master page for this ASP.NET project. By default, an ASP.NET MVCapplication will use master pages in Visual Studio, so let us first create a master page. The master page will be added to the "Views\Shared" folder.

Right click the "Views\Shared" folder and choose to add a new item.

AddMasterPage.jpg

Select the "Master Page" template, give the mater page the name "Site.Master" and click the "Add" button, the master page is added to the project.

We will implement the "Site.Master" file as the following:

<%@ Master Language="C#" 
    CodeBehind="~/Views/Shared/Site.Master.cs"
    Inherits="ASPNetMVCTutorial.Views.Shared.Site" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title><asp:Literal id="litAppTitle" runat="server" /></title>
    <style type="text/css">
        .ApplicationDefault {font-family: Verdana; font-size: 10px;}
        .Title {text-align: center; font-size: 12px; color:Maroon; font-family: 
                        Verdana; font-weight: bold;}
        .AuthorInformation {text-align: center; color:green; margin-top: 5px}
        .MainContent {margin-top: 10px; background-color: #F1FFFF; height: 600px; 
                              overflow: auto; width: 95%; text-align: center;
                              margin-left:auto; margin-right:auto;}
        .Copyright {margin-top: 10px; color: Gray; font-weight:bold; width: 100%; 
                            float: left; text-align: center;}
        .ErrorText {font-family: Verdana; font-weight: bold; color:Maroon;}
        .BoldText {font-family: Verdana; font-weight: bold;}
    </style>
</head>
 
<body class="ApplicationDefault">
    <div class="Title">
        <asp:Literal id="litApplicationName" runat="server" />
    </div>
    <div class="AuthorInformation">
        <asp:Literal id="litAuthorInformation" runat="server" />
    </div>
    
    <div id="MainContent" class="MainContent">
        <asp:ContentPlaceHolder id="ApplicationContent" runat="server" />
    </div>
    <div class="Copyright">Copy right: The Code Project Open License (CPOL)</div>
</body>
</html>

We will implement the code-behind file "Site.Master.cs" as the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.UI.WebControls;
using ASPNetMVCTutorial.Models;
using ASPNetMVCTutorial.Utilities;
 
namespace ASPNetMVCTutorial.Views.Shared
{
    public partial class Site : System.Web.Mvc.ViewMasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ApplicationInformation appInfomation = ApplicationInformation.GetInstance();
            litAppTitle.Text = appInfomation.ApplicationName;
            litApplicationName.Text = appInfomation.ApplicationName;
 
            StringBuilder SB = new StringBuilder();
            SB.Append("Developed by ");
            SB.Append(appInfomation.Author);
            SB.Append(" on ");
            SB.Append(appInfomation.DevelopmentTime);
            litAuthorInformation.Text = SB.ToString();
        }
    }
}

The master page will be used for the entire project to control the display style and to display some general information about the application.

Add the Views to the "Views" Folder

The views in ASP.NET MVC are actually specialized "aspx" pages. In this project, we will be adding three views:

  • StudentList.aspx
  • AddStudent.aspx
  • Error.aspx

The "StudentList.aspx" is used to list all the students and to provide the user interactions to navigate to the "AddStudent.aspx" view to add student. It also provides the user interaction to delete the students. The "Error.aspx" view is used to display any possible errors during the operation.

The "StudentList.aspx" and "AddStudent.aspx" views will be added to the "Views\Students" folder and the "Error.aspx" will be added to the "Views\Shared" folder. Right click the folder "Views" and add a folder "Students" to it. We can then add the "StudentList.aspx" view. Right click the "Views\Students" folder and add a view.

AddView.jpg

Give the view the name "StudentList", choose the master page "Site.Master", type in theContentPlaceHolderID as "ApplicationContent" and click the "Add" button. In the solution explorer, the view is created as "StudentList.aspx" file in the "Views\Students" folder.

AddViewWithoutCodeBehind.jpg

You may be surprised that the "StudentList.aspx" view does not have the familiar code-behind file. It is a hot discussion if the code-behind files should be used on the ASP.NET MVC views. Some people call the using of code-behind on views "Evil", but some other people say that it is "Not Evil". I am not going to get into this discussion. I just feel that if the application developers choose to use code-behind files, they should have the option to use it. We will add the code-behind file for the "StudentList.aspx" manually.

Right click the "Views\Students" folder and add a class file named "StudentList.aspx.cs". The "StudentList.aspx.cs" file will automatically implement a class "StudentList". Make the "SudentList" class inherit from "System.Web.Mvc.ViewPage". In the "StudentList.aspx" file, add the "CodeBehind" reference to the "StudentList.aspx.cs" and change the "Inherits" value to the class "StudentList". By doing this, the code behind file is manually added in the solution explorer:

AddViewWithCodeBehind.jpg

After adding the code behind file, we will implement the "StudentList.aspx" as the following:

<%@ Page Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    CodeBehind="~/Views/Students/StudentList.aspx.cs"
    Inherits="ASPNetMVCTutorial.Views.Students.StudentList" %>
 
<asp:Content id="IndexContent" ContentPlaceHolderID="ApplicationContent" runat="server">
    <div style="float: right; margin-right: 10px">
        <asp:HyperLink id="linkAddStudent" runat="server" 
		Text="Click to add a student to the list" />
    </div>
    <br />
    <div style="margin-top: 5px">
        <asp:Literal id="litStudentDetail" runat="server" />
    </div>
</asp:Content>

The code-behind file "StudentList.aspx" will be implemented as the following:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using ASPNetMVCTutorial.Models;
using ASPNetMVCTutorial.Utilities;
 
namespace ASPNetMVCTutorial.Views.Students
{
    public class StudentList : System.Web.Mvc.ViewPage
    {
        protected Literal litStudentDetail;
        protected HyperLink linkAddStudent;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
 
            linkAddStudent.NavigateUrl = 
                ApplicationUtility.FormatURL("/Students/AddStudent");
 
            DataTable StudentsTable = (DataTable)ViewData["Students"];
            DataView StudentsView = StudentsTable.DefaultView;
            StudentsView.Sort = "ID Desc";
 
            StringBuilder SB = new StringBuilder();
 
            SB.Append("<table style=\"width: 99%;\" ");
            SB.Append("rules=\"all\" border=\"1px\" ");
            SB.Append("cellspacing=\"0px\" cellpadding=\"4px\">");
 
            SB.Append("<tr style=\"background-color: Silver; color: white; ");
            SB.Append("font-weight: bold\">");
            foreach (DataColumn aColumn in StudentsTable.Columns)
            {
                SB.Append("<td>");
                SB.Append(aColumn.ColumnName);
                SB.Append("</td>");
            }
            SB.Append("<td>&nbsp;</td>");
            SB.Append("</tr>");
 
            foreach (DataRowView aRowView in StudentsView)
            {
                SB.Append("<tr>");
                foreach (DataColumn aColumn in StudentsTable.Columns)
                {
                    SB.Append("<td>");
                    SB.Append(aRowView[aColumn.ColumnName].ToString());
                    SB.Append("</td>");
                }
 
                string ID = aRowView["ID"].ToString();
                SB.Append("<td>");
                SB.Append("<a href=\"");
                SB.Append(ApplicationUtility.FormatURL("/Students/DeleteStudent"));
                SB.Append("?ID=");
                SB.Append(ID);
                SB.Append("\">Delete this student</a>");
                SB.Append("</td>");
                SB.Append("</tr>");
            }
 
            SB.Append("</table>");
 
            litStudentDetail.Text = SB.ToString();
        }
    }
}

Similarly we will implement the "AddStudent.aspx" to the "Views\Students" folder as the following:

<%@ Page Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    CodeBehind="~/Views/Students/AddStudent.aspx.cs"
    Inherits="ASPNetMVCTutorial.Views.Students.AddStudent" %>
 
<asp:Content ID="AddStudentContent" 
    ContentPlaceHolderID="ApplicationContent" runat="server">
<script language="javascript" type="text/javascript">
    function SubmitForm() {
        frmAddStudent.action = hidAddstudentActionURL.value;
        frmAddStudent.submit();
    }
</script>
 
<asp:Literal ID="litAddStudentActionHidden" runat="server" />
<form id="frmAddStudent" method="post" action="">
<div style="text-align: center">
    <table cellspacing="5px" cellpadding="0px" style="text-align: 
        center; margin-left:auto; margin-right:auto;">
        <tr>
            <td class="BoldText" style="text-align: left">
                Please provide the following information to add the student:
            </td>
        </tr>
        <tr><td style="height: 10px"></td></tr>
        <tr>
            <td>
                Name&nbsp;<input type="text" id="textName" name="textName" />
                &nbsp;&nbsp;
                Score&nbsp;<input type="text" id="txtScore" name="txtScore" />
            </td>
        </tr>
        
        <tr>
            <td>
                <asp:HyperLink ID="linkCancelAddStudent" 
                    Text="Cancel add student and 
			return to the main page" runat="server" />
                <input type="button" value="Add student" onclick="return SubmitForm()" />
            </td>
        </tr>
    </table>
</div>
</form>
</asp:Content>

The code-behind file for the "AddStudent.aspx" view will be implemented as the following:

using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using ASPNetMVCTutorial.Models;
using ASPNetMVCTutorial.Utilities;
 
namespace ASPNetMVCTutorial.Views.Students
{
    public class AddStudent : System.Web.Mvc.ViewPage
    {
        protected HyperLink linkCancelAddStudent;
        protected Literal litAddStudentActionHidden;
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
 
            StringBuilder SB = new StringBuilder();
            SB.Append("<input type=\"hidden\" id=\"hidAddstudentActionURL\" value=\"");
            SB.Append(ApplicationUtility.FormatURL("/Students/AddStudentAction"));
            SB.Append("\" />");
            linkCancelAddStudent.NavigateUrl
                = ApplicationUtility.FormatURL("/Students/StudentList");
            litAddStudentActionHidden.Text = SB.ToString();
        }
     }
}

The "Error.aspx" view will be implemented in the "Views\Shared" folder as the following:

<%@ Page Language="C#"
    CodeBehind="~/Views/Shared/Error.aspx.cs"
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="ASPNetMVCTutorial.Views.Shared.Error" %>
 
<asp:Content ID="ErrorContent" ContentPlaceHolderID="ApplicationContent" runat="server">
<div style="margin-top: 10px; text-align: center">
    <table cellpadding="4px" cellspacing="4px" style="margin-left:auto; 
	margin-right:auto;">
        <tr><td class="ErrorText"><asp:Literal ID="litErrorMessage" 
		runat="server" /></td></tr>
        <tr><td style="text-align: right">
            <asp:HyperLink ID="linkBackToMainPage" Text="Go back to main page" 
		runat="server" />
        </td></tr>
    </table>
</div>
</asp:Content>

The code-behind file for the "Error.aspx" will be implemented as the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using ASPNetMVCTutorial.Models;
using ASPNetMVCTutorial.Utilities;
 
namespace ASPNetMVCTutorial.Views.Shared
{
    public class Error : System.Web.Mvc.ViewPage
    {
        protected Literal litErrorMessage;
        protected HyperLink linkBackToMainPage;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
 
            linkBackToMainPage.NavigateUrl
                = ApplicationUtility.FormatURL("/Students/StudentList");
            string ErrorMessage = ViewData["ERROR"].ToString();
            litErrorMessage.Text = ErrorMessage;
        }
    }
}

The ASP.NET MVC views are specialized ASP.NET pages. The "System.Web.Mvc.ViewPage" class is an immediate child class of the "System.Web.UI.Page" class in the class inheritance hierarchy. When developing the views, it is important to avoid any modifications to the application data to better conform to the MVC methodology.

Add a Controller to the "Controllers" Folder

Now we are ready to add the controller for this ASP.NET MVC project. Right click the "Controllers" folder to add the control class and name the class as "StudentsController" and implement this controller class as the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ASPNetMVCTutorial.Models;
 
namespace ASPNetMVCTutorial.Controllers
{
    public class StudentsController : Controller
    {
        private StudentsModel GetStudentModelFromSession()
        {
            StudentsModel theModel = (StudentsModel)Session["Students"];
            if (theModel == null)
            {
                theModel = new StudentsModel();
                Session["Students"] = theModel;
            }
 
            return theModel;
        }
 
        public ActionResult StudentList()
        {
            StudentsModel theModel = GetStudentModelFromSession();
 
            ViewData["Students"] = theModel.GetStudents();
            return View();
        }
 
        public ActionResult AddStudent()
        {
            return View();
        }
 
        public ActionResult AddStudentAction()
        {
            string Name = Request.Form["textName"];
            string Score = Request.Form["txtScore"];
 
            if ((Name == null) || (Name.Trim() == ""))
            {
                ViewData["ERROR"] = "Please provide a name for the student to add";
                return View("../Shared/Error");
            }
 
            if (Name.Length < 6)
            {
                ViewData["ERROR"]
                    = "The student's name should not be less than 6 characters.";
                return View("../Shared/Error");
            }
  
            int intScore;
            if (!Int32.TryParse(Score, out intScore))
            {
                ViewData["ERROR"]
                    = "Please provide a valid score to the student to add.";
                return View("../Shared/Error");
            } 
 
            if ((intScore < 60) || (intScore > 100))
            {
                ViewData["ERROR"]
                    = "We only accept students with scores between 60 and 100.";
                return View("../Shared/Error");
            }
 
            StudentsModel theModel = GetStudentModelFromSession();
            theModel.AddStudent(Name, intScore);
 
            ViewData["Students"] = theModel.GetStudents();
            return View("StudentList");
        }
 
        public ActionResult DeleteStudent()
        {
            string ID = Request.QueryString["ID"];
            int intID;
 
            if (!Int32.TryParse(ID, out intID))
            {
                ViewData["ERROR"] = "Please provide a valid student ID";
                return View("../Shared/Error");
            }
 
            StudentsModel theModel = GetStudentModelFromSession();
            theModel.DeleteStudent(intID);
 
            return RedirectToAction("StudentList");
        }
    }
}

This controller is named as "StudentsController". It implements 5 methods.

The private method "GetStudentModelFromSession" is used to demonstrate how the web session is used in this ASP.NET MVC projects. It returns an object of type "StudentsModel", which is implemented in the "Models" folder. The method first tries to obtain this object from the web session. If it is unable to get it, it will create a new object and add it to the web session. This object will be used as the data storage in this tutorial web application.

The four public methods are called "actions" in the ASP.NET MVC terminology:

  • StudentList
  • AddStudent
  • AddStudentAction
  • DeleteStudent

These methods are used to perform certain operations on the application data saved in the web session. When the operations on the application data are completed, each method will choose a view implemented in the "Views" folder to display the data to the users. If the view of choice is the same name as the "action", the name of the view can be omitted. To access the user input from the browser, these methods can use the familiar "Request.QueryString' and "Request.Form" methods.

The action methods pass the data for the views to display by the "ViewData" dictionary.

"Global.asax" - Where the Magic Happens

When we create the ASP.NET MVC project, Visual Studio generates a default "Global.asax" file for us. Now we will make changes to this file to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace ASPNetMVCTutorial
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Students", 
                    action = "StudentList", 
                    id = UrlParameter.Optional }
            );
        }
 
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
 
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

The URLs to access the web pages developed in ASP.NET MVC projects are like "http://localhost/VirtualDirectoryName/Controller/Action". The calling of the "routes.MapRoute" method in the "Global.asax" file makes sure the correct controller and action are located. If the URL does not specify the controller and action, the controller "Student" and the action "StudentList" will be used as default.

When a URL is received by the web application, it will first find the controller. If the controller in the URL is "Student", the web application will try to locate a class named as "StudentController" in the "Controllers" folder. After thecontroller class is located, the method of the same name as the action, say "StudentList" is called. The chosen action method in the controller class will perform all the operations on the application data, and choose a view to display to the user. The action methods pass the data for the views to display by the "ViewData" dictionary.

If you want to mix regular "aspx" pages with the MVC views in the same ASP.NET project, you can add the following code before mapping the ASP.NET MVC routing:

routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");  

This way, the routing will ignore the URLs pointing to regular "aspx" pages. These pages will be loaded directly without going through the controller-action-view pattern.

The Completed Project Shown in the Solution Explorer

Now we completed the development of this tutorial ASP.NET MVC application. The following picture shows all the files including the code-behind files in the solution explorer:

SolutionExplorerComplete.jpg

Run the ASP.NET MVC Application

Press "F5" when Visual Studio is having the focus, we can start to debug run the tutorial application. The following picture shows the application running in "Google Chrome":

RunApplicationList.jpg

Click on one of the "Delete this student" links, we can delete the student from the list. Click on the link "Click to add a student to the list", the web page is then navigated to the following:

RunApplicationAdd.jpg

Type in a student name and give the student a score, and click the "Add student" button, we can see that the student is added.

RunApplicationComplete.jpg
Posted by Anshul Jain
Procedure with OutPut Parameter
CREATE PROCEDURE GetImmediateManager
   @employeeID INT,
   @managerID INT OUTPUT
AS
BEGIN
   SELECT @managerID = ManagerID 
   FROM HumanResources.Employee 
   WHERE EmployeeID = @employeeID
END
Posted by Anshul Jain
Replace Function in C#.Net


SELECT REPLACE('Jain Anshul''Jain''Aspdotnet')
Output'Aspdotnet Anshul'

In above query we declared string as 'Jain Anshul', and we tried to replace string part 'Jain' to'Aspdotnet' string value.

From above example we learned that Replace() function is used to replace particular part of string based on our requirement. Now I will explain how to use update statement with replace function.

I have a one table with some data in that I need to update particular part of column value with some other value.

Example

I have table userdetails like this

UserName
Location
Website
Anshul Jain
Bhopal
http//www.anshuljainbhopal.com
Ajay Nigam
Bhopal
http//www.ajaynigambhopal.com
Prabhat Tiwari
Bhopal
http//www.test.com
If you observe above table column “Website” it contains urls but those are not in correct format. Generally our website urls will be like this “http://www.” but here all the urls will be like this “http//www.

Now I need to update Website column data (url format) to correct format for that we need to write update query with replace function to modify particular part of column that would be like this


UPDATE SampleDetails SET Website=REPLACE(Website,'http//www.','http://www.')
Once we run above query our table Website column data will be like this 

UserName
Location
Website
Anshul Jain
Bhopal
http//www.anshuljainbhopal.com
Ajay Nigam
Bhopal
http://www.ajaynigambhopal.com
Prabhat Tiwari
Bhopal
http://www.test.com
By using replace function in update query we can update certain part of data easily.
Posted by Anshul Jain
Interview question for Asp.net
Difference between stored procedure and function

1) Procedure can return zero or n values whereas function can return one value which is mandatory.
2) Procedures can have input, output parameters for it whereas functions can have only input parameters.
3) Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
4) Functions can be called from procedure whereas procedures cannot be called from function.
5) Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
6) We can go for transaction management in procedure whereas we can't go in function.
7) Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

Difference between Abstract and Interface

Abstract Class:

-Abstract class provides a set of rules to implement next class
-Rules will be provided through abstract methods
-Abstract method does not contain any definition
-While inheriting abstract class all abstract methods must be override
-If a class contains at least one abstract method then it must be declared as an “Abstract Class”
-Abstract classes cannot be instantiated (i.e. we cannot create objects), but a reference can be created
-Reference depends on child class object’s memory
-Abstract classes are also called as “Partial abstract classes”
-Partial abstract class may contain functions with body and functions without body
-If a class contains all functions without body then it is called as “Fully Abstract Class” (Interface)

Interface:

-If a class contains all abstract methods then that class is known as “Interface”
-Interfaces support like multiple inheritance
-In interface all methods r public abstract by default
-Interfaces r implementable
-Interfaces cannot be instantiated, but a reference can be created

Index types in SQL Server

Clustered Index

Only 1 allowed per table physically rearranges the data in the table to confirm to the index constraints for use on columns that are frequently searched for ranges of data for use on columns with low selectivity.

Non-Clustered Index

Up to 249 allowed per table creates a separate list of key values with pointers to the location of the data in the data pages For use on columns that are searched for single values 

A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

Included Column Index (New in SQL Server 2005) 

In SQL Server 2005, the functionality of non-clustered indexes is extended by adding non-key columns to the leaf level of the non-clustered index. Non-key columns can help to create cover indexes. By including non-key columns, you can create non-clustered indexes that cover more queries. The Database Engine does not consider non-key columns when calculating the number of index key columns or index key size. Non-key columns can be included in non-clustered index to avoid exceeding the current index size limitations of a maximum of 16 key columns and a maximum index key size of 900 bytes. Another advantage is that using non-key column in index we can have index data types not allowed as index key columns generally.

In following example column Filename is varchar(400), which will increase the size of the index key bigger than it is allowed. If we still want to include in our cover index to gain performance we can do it by using the Keyword INCLUDE.

USE AdventureWorks
GO
CREATE INDEX IX_Document_Title
ON Production.Document (TitleRevision)
INCLUDE (FileName)

Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and they INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. For Included Column Index to exist there must be at least one key column defined with a maximum of 16 key columns and 1023 included columns. 

Avoid adding unnecessary columns. Adding too many index columns, key or non-key as they will affect negatively on performance. Fewer index rows will fit on a page. This could create I/O increases and reduced cache efficiency. More disk space will be required to store the index. Index maintenance may increase the time that it takes to perform modifications, inserts, updates, or deletes, to the underlying table or indexed view.

Another example to test:

Create following Index on Database AdventureWorks in SQL SERVER 2005

USE AdventureWorks
GO
CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1AddressLine2CityStateProvinceID)
GO 

Test the performance of following query before and after creating Index. The performance improvement is significant.
SELECT AddressLine1AddressLine2CityStateProvinceIDPostalCode
FROM Person.Address
WHERE PostalCode BETWEEN '98000'
AND '99999';
GO

Interview questions 

What are differences between Array list and Hash table?

Ans: 1) Hash table store data as name, value pair. While in array only value is store.
2) To access value from hash table, you need to pass name. While in array, to access value, you need to pass index number.
3) you can store different type of data in hash table, say int, string etc. while in array you can store only similar type of data.

What are differences between system.stringbuilder and system.string?

The main difference is system.string is immutable and system.stringbuilder is a mutable. Append keyword is used in string builder but not in system.string.
Immutable means once we created we cannot modified. Suppose if we want give new value to old value simply it will discarded the old value and it will create new instance in memory to hold the new value.

What are the differences between Application object and session object?

Ans: The session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted. If they again enter in to the application they get different session id.
But for application object the id is maintained for whole application. 

What are the different types of indexes?

Ans: Two types of indexes are there one is clustered index and non-clustered index

How many types of memories are there in .net? 

Ans: Two types of memories are there in .net stack memory and heap memory

Is it possible to set the session out time manually? 

Ans: Yes we can set the session out time manually in web.config.

What are differences between function and stored procedure?

Ans:
1) Function returns only one value but procedure returns one or more than one value.
2) Function can be utilized in select statements but that is not possible in procedure.
3) Procedure can have an input and output parameters but function has only input parameters only.
4) Exceptions can be handled by try catch block in procedures but that is not possible in function.

What are the differences between Abstract and interface?

Ans:  1) Abstract cannot be instantiated but we can inherit. Interface it cannot be inherit it can be instantiate
2) Interface contain only declarations no definitions. Abstract contain declarations and definitions.
3) The class which contains only abstract methods is interface class. A class which contains abstract method is called abstract class
4) Public is default access specifier for interface we don’t have a chance to declare other specifiers. In abstract we have chance to declare with any access specifier

Can you Explain Page lifecycle in .net?
Can you Explain .NET architecture in .net?

What is the difference between primary key and unique key with not null?

Ans: There is no difference between primary key and unique key with not null.

What is boxing and unboxing concepts in .net? 

Ans: Boxing is a process of converting value type into reference type
Unboxing is a process of converting reference type to value type.

What are the differences between value type and reference type?

Ans: Value type contain variable and reference type are not containing value directly in its memory.
Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration

Is it possible to host the website from desktop?

Ans: Yes 

Why we go for page rendering in Asp.Net Page life cycle?

Ans: Browser understands an only html control that’s why in page rendering we will convert the aspx controls into html controls.

Write a sample query for self join?

Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;

Can we change the index of primary key on table?

Ans: No

How to change the name of the table or stored procedure in sql?

Ans: sp_rename oldtablename newtablename
For changing the column name
Sp_rename  ‘tablename.[Oldcolumnname]’,’newcolumnname’,’Column’
Ex:sp_rename ‘tblemp.first’,’namechange’,’Column’

How to find out which index is defined on table?

Ans: sp_helpindex tablename

Can you write the program to find the length of string without using library function?

Ans: for (int i=0; str[i]!=”\n”; i++)
{
Count++;
}

What is the difference between scope_identity() and current_identity()?

Ans: Scope_identity and current _identity both are similar and it will return the last identity value generated in the table.
Scope_Identity will return the identity value in table that is currently in scope

What are difference between GET and POST Methods?

Ans:
GET Method (): 

1) Data is appended to the URL. 
2) Data is not secret. 
3) It is a single call system 
4) Maximum data that can be sent is 256. 
5) Data transmission is faster 
6) this is the default method for many browsers 

POST Method (): 


1) Data is not appended to the URL. 
2) Data is Secret 
3) it is a two call system. 
4) There is no Limit on the amount of data. That is characters any amount of data can be sent. 
5) Data transmission is comparatively slow. 
6) No default and should be explicitly specified.

What are difference between truncate and delete?

Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table not on all the row.
2) Counter of the Identity column is reset in Truncate where it is not reset in Delete. 
3) Trigger is not fired in Truncate where as trigger is fired in Delete.
4) In TRUNCATE we cannot rollback.
5) In DELETE we can rollback

What is the difference Grid View and between Data Grid (Windows)?

Ans:
1) GridView Control Enables you to add sorting, paging and editing capabilities without writing any code. 
2)GridView Control Automatically Supports paging by setting the ‘PagerSetting’ Property.The Page Setting Property supports four Modles 

a. Numeric(by default) 
b. Next Previous 
c. NumericFirstLast 
d. Next PreviousLast 

3)It is Used in asp.net 
4)GridView Supports RowUpdating and RowUpdated Events. 
5)GidView is Capable of Pre-Operations and Post-Operations. 
6)GridView Has EditTemplates for this control 
7)It has AutoFormat 

DataGrid(Windows) 

1)DataGid Control raises single Event for operations 
2)DataGird Supports the SortCommand Events that occur when a column is Soted. 
3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton is clicked for an item in the grid. 
4)DataGrid is used in Windows GUI Application. 
5)It doesnot have EditTemplates for this control 
6)It doesnot have AutoFormat

If I write System.exit (0); at the end of the try block, will the finally block still execute?

Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the program, and thus finally never executes.

What are the different levels of State management in ASP.NET?

Ans:
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

There are 2 types State Management: 

1. Client – Side State Management 
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client end are listed down below: 

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state. 

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state. 

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed. 

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. 

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL. 

2. Server – Side State Management 
a. Application State - Application State information is available to all pages, regardless of which user requests a page. 

b. Session State – Session State information is available to all pages opened by a user during a single visit. 

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

Abstract Class:

Abstract class is a class which can’t be instantiate. Class should have “Abstract” key word with the name.  In any one of the method of class having abstract method with in it, then it should be define as abstract class. The class which derived the abstract class should have definition of the abstract method. These classes which derived the abstract class and implement the abstract methods call concrete class.
Abstract class may have the definition of function or may not.  Below is the simple example of an abstract class
public abstract alass AbstractStudent
    {
        String Roll
        {
            get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
        
        String LastName
        {
            get;
            set;
        }
        

        Public String GetStudentDetails()
             {

                  // Implementation of Method    
             }

        public String SaveStudentDetails ()
            {
                  // Implementation of Method    
             }

        public abstract String CalculateWage();

    }
So, the class having one abstract method so we need to mention the class as "abstract" .

Difference between Abstract Class and Interface?

Abstract class is a class which can’t be instantiated and which can have methods with definition as well as declaration also. This can be inherited.  

As for Example:

public abstract class AbstractStudent
    {
        String Roll
        {
            get;
            set;
        }

        String FirstName
        {
           get;
           set;
        }
   
        String LastName
        {
           get;
            set;
        }

        Public String GetStudentDetails()
            {
                 // Implementation of Method   
             }

        public String SaveStudentDetails ()
            {
                  // Implementation of Method   
            }

        public abstract String CalculateWage();

    }


Interface can only contain the methods declaration and can be implemented in the class.

As for Example:
Public interface IStudnet
    {
        String Roll
        {
           get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
    
        String LastName
        {
            get;
            set;
        }
   
        String GetStudentDetails();
        String SaveStudentDetails ();
    }

Below are the few main difference between Abstract Class and Interface

a.    In abstract class method can have definition as well as declaration also. But Interface should have only definition.
b.    All the Methods are Public as default and don’t have any access Modifier Controls in interface, whereas for abstract class we can have access modifier for methods.
c.    Abstract class can have constructor or destructor, whereas interface not.
d.    Abstract class can’t be part of multiple inheritance and we can implement multiple interface.

What do you mean by String objects are immutable?

String objects are immutable as its state cannot be modified once created. Every time when we perform any operation like add, copy, replace, and case conversion or when we pass a string object as a parameter to a method a new object will be created.

Example:
String str = "ABC";

str.Replace("A","X");

Here Replace() method will not change data that "str" contains, instead a new string object is created to hold data "XBC" and the reference to this object is returned by Replace() method.

So in order to point str to this object we need to write below line.
str = str.Replace("A","X");
Now the new object is assigned to the variable str. earlier object that was assigned to str will take care by garbage collector as this one is no longer in used.

What is dll hell problem in .NET and how it will solve?

Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of version supportability of dll for (within) an application
.NET Framework provides operating system with a global assembly cache. This cache is a repository for all the .net components that are shared globally on a particular machine. When a .net component installed onto the machine, the global assembly cache looks at its version, its public key and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between the different versions of same component, or DLL

What is a Partial class?

Ans: Instead of defining an entire class, you can split the definition into multiple classes by using partial class keyword. When the application compiled, c# compiler will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of classes without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
{
}
}

What is difference between constants, read-only and, static?

Constants: The value can’t be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.

What is the cross page post backing?

Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information from one page to another.

Button control has property PostBackUrl that can be set to URL of any page in our ASP.Net WebSite where we want to transfer all form values to.
Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to get reference to the Page object that initiated the postback (in other words to get the actual reference to the Page object of the aspx page on which user clicked the Submit button on a HTML form).

So for example lets create two sample pages in our Web Application:  
  • SourcePage.aspx
  • DestinationPage.aspx
In SoucePage in Html form we will put two TextBox controls (one for First Name and one for Last Name) and one Button component  and set its PostBackUrl property to "~/DestinationPage.aspx". 

SourcePage.aspx:
    <form id="form1" runat="server">
        <div>
            First Name:&nbsp;<asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
            Last Name:&nbsp;<asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br />
            <asp:Button ID="Button1" runat="server" Text="Submit To Destination Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
        </div>
    </form>

When our user clicks the Submit button, all the values from the HTML Form on SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able to get reference to the SourcePage.aspx in our DestinationPage with the PreviousPage property like this:

So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox controls on SourcePage.aspx and show them in two label controls like this:
    protected void Page_Load(object sender, EventArgs e)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            Page previousPage = PreviousPage;
            TextBox firstName = (TextBox)previousPage.FindControl("FirstName");
            TextBox lastName = (TextBox)previousPage.FindControl("LastName");
            // we can now use the values from TextBoxes and display them in two Label controls..
            labelFirstName.Text = firstName.Text;
            labelLastName.Text = lastName.Text;
         }
    }

You probably noticed that we first checked if PreviousPage property of current page (DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in case that user opens our DestinationPage.aspx directly, without running a cross page postback.

Also here we checked the another PreviousPage property called IsCrossPagePostBack to see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property will be set to FALSE.

TIP: We can be completely sure that we have a  real CrossPagePostback ONLY IF:
  1. Page.PreviousPage is NOT NULL,
  2. PreviousPage.IsCrossPagePostback is true
This important to check to avoid errors in code.

Now this is very useful and i'm sure you are eager to use this in your next project. But wait, we are not over yet!

Finding the controls on PreviousPage with FindControl method and type-casting them from object to their real type is a little messy.
It feels like there must be a better solution for this!

And here it is: We can use the <%@ PreviousPageType %> directive in the header of our DestinationPage.aspx like this
    <%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

to declare our previous page type, and then we can access Public properties of the PreviousPage without typecasting.
Now all we need to do is to create some public properties on our SourcePage.aspx.cs to expose data/Controls we want to the destionation page:
    public partial class SourcePage : System.Web.UI.Page
    {
        public string FormFirstName
        {
            get { return FirstName.Text; }
        }

        public string FormLastName
        {
            get { return LastName.Text; }
        }
    }

And then we can change the Page_Load code in our DestinationPage.aspx to much cleaner code like this:
    protected void Page_Load(object sender, EventArgs e)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            SourcePage prevPage = PreviousPage;

            // we can now use the values from textboxes and display them in two Label controls..
            labelFirstName.Text = prevPage.FormFirstName;
            labelLastName.Text = prevPage.FormLastName;     
        }
    }

SourcePage type used in the code is offcourse name of the partial class defined is SourcePage.aspx.cs that inherits System.Web.UI.Page that is automatically created for us when we created new WebForm in VisualStudio.

This code is much cleaner and easier to follow, there is no ugly typecasting, just simple property values to use to retrieve the data from previous page.


When should you use Abstract Class vs Interface while programming?

 Ans: When we want that sub class must implement all the methods of base class. In such a situation we will implement the interface. In the other hand when we want only some method of base class in our sub class then use base class as abstract class.

What is the difference between application exception and system exception?

Ans: The difference between application exception and system exception is that system exceptions are thrown by CLR and application exceptions are thrown by applications.

What is the difference between authorization and authentication?

Ans: Authorization is a process of allowing or denying resources to particular user or record 

Declaration of authorization is

<authorization>
<allow users=”Suresh, Sanjay”/>
<deny users=”Ramana, Rakesh”>
</authorization>
Sometimes authorization allows the unauthorized persons at that time we will use
<deny users=”?”/>

Authentication means 

Authentication is a process where we identify the credentials of user i.e. username, password and create an identity to mention user as an authenticated.  

What is the use of n-tier architecture and 3-tier architecture?


Check this article for 3-tier architecture 3 tier architecture example in asp.net

How to get the version of the assembly?

Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();

What is the location of Global Assembly Cache on the system?

Ans: c:\Windows\assembly

 What is the serialization?

Ans: Serialization is a process of converting object into a stream of bites.

What is synchronization?

Ans: The mechanism needed to block one thread access to the data. If the data is being accessed by another thread.
Synchronization can be accessed by using system.monitor class
A monitor class methods are enter, exit, pulse for this lock statement is also used
Suppose if we need to synchronize some data at that time we need to place that data in this block
Lock
{
}
Whatever the data has been placed into the lock block that data has been blocked

What are the thread priority levels?

Ans: Thread priority levels are five types
         0 - Zero level
         1 - Below Normal
         2 - Normal
         3 - Above Normal
         4 - Highest
By Default priority level is 2

What is the difference between .tostring(), Convert.tostring()?

Ans: The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding
practice using “convert” is always safe.

What is Collation?

Ans: Collation refers to a set of rules that determine how the data is sorted and compared.

What is the difference between Primary key and unique key?

Ans: Primary key does not allow the null values but unique key allows one null value.
Primary key will create clustered index on column but unique key will create non-clustered index by default.

How many web.config files are there in 1 project?

Ans: There might be multiple web.config files for a single project depending on the hierarchy of folders inside the root folder of the project, so for each folder we can use one web.config file

What is the difference between throw and throw ex?
What is the difference between view state and hidden field?

Ans: viewstate is secured hidden field is insecure
Viewstate will store large amount of data but hidden filed will store small amount of data. 

What is the difference between binary serialization and xml serialization?
What is the Difference between read only and constant variables?

Ans: Read only can assign the values at runtime only.
Constant will assign the values at compile time only.
We cannot modify the both variable values.

What is static keyword in .Net?

Ans: Static is same as constant variable but we can change the value of static variable and we can access the variables without creating any instances

What is the use of business logic layer in 3-tier architecture in .net?

Ans: Though a web site could talk to the data access layer directly, it usually goes through another layer called the business layer. The business layer is vital in that it validates the input conditions before calling a method from the data layer. This ensures the data input is correct before proceeding, and can often ensure that the outputs are correct as well. This validation of input is called business rules, meaning the rules that the business layer uses to make “judgments” about the data.

However, business rules don’t only apply to data validation; these rules apply to any calculations or any other action that takes place in the business layer. Normally, it’s best to put as much logic as possible in the business layer, which makes this logic reusable across applications.

One of the best reasons for reusing logic is that applications that start off small usually grow in functionality. For instance, a company begins to develop a web site, and as they realize their business needs, they later decide to add a smart client application and windows service to supplement the web site. The business layer helps move logic to a central layer for “maximum reusability.”

Posted by Anshul Jain
how to bind or display images from folder to datalist using asp.net or how to insert images into folder and display images from folder to datalist using asp.net



Description:

In previous post I explained clearly how to bind images from folder to gridview . Now I will explain how to save images into folder and how we can bind that images to datalist using asp.net. It’s very easy to store images in folder and binding that images to datalist. For that first create one new website after that right click on that website select New Folder give name as Images because here I am using same name if you want to use another name you need to change the name in code also after completion of adding Imagesfolder to your website Design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Images to Datalist from folder</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" onclick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5">
<ItemTemplate>
<asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server"/>
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
</form>
</body>
</html>
After that add using System.IO and using System.Collections namespaces and write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();

}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
fileupload1.SaveAs(Server.MapPath("Images/" + filename));
BindDataList();
}
Posted by Anshul Jain
.NET Frame Work and CLR

What is the .NET Framework?

 

The .NET Framework is a new and revolutionary platform created by Microsoft for developingapplications 

  • It is a platform for application developers.
  • It is a Framework that supports Multiple Language and Cross language integration.
  • IT has IDE (Integrated Development Environment).
  • Framework is a set of utilities or can say building blocks of your application system.
  • .NET Framework provides GUI in a GUI manner.
  • .NET is a platform independent but with help of Mono Compilation System (MCS). MCS is a middle level interface.
  • .NET Framework provides interoperability between languages i.e. Common Type System (CTS) .
  • .NET Framework also includes the .NET Common Language Runtime (CLR), which is responsible for maintaining the execution of all applications developed using the .NET library.
  • The .NET Framework consists primarily of a gigantic library of code.

Definition: A programming infrastructure created by Microsoft for building, deploying, and running applications and services that use .NET technologies, such as desktop applications and Web services.

 

Cross Language integration

 

You can use a utility of a language in another language (It uses Class Language Integration).

 

.NET Framework includes no restriction on the type of applications that are possible. The .NET Framework allows the creation of Windows applications, Web applications, Web services, and lot more.

 

The .NET Framework has been designed so that it can be used from any language, including C#, C++, Visual Basic, JScript, and even older languages such as COBOL.

 

Difference between Visual Studio and Visual Studio .NET

 

Visual Studio

Visual Studio

It is object based

It is object oriented

Internet based application

- Web Application

Web services

- Internet enable application

- Third party API

- Peer to peer Application

All developing facilities in internet based application

Poor error handling Exception/Error

Advance error handler and debugger

Memory Management System Level Task

Memory Management Application Domain with help of GC (Garbage Collector)

DLL HELL

VS .NET has solved DLL HELL Problem

 

Simple explanation of definition used in the above comparision:

 

Web Application

 

All websites are example of web application. They use a web server.

 

Internet Enabled Application

 

They are desktop application. Yahoo messenger is an example of desktop application.

 

Peer to Peer

 

Communication through computers through some system.

 

Web Services

 

It doesn't use web-based server. Internet payment systems are example of web services.

 

DLL Hell

 

"DLL Hell" refers to the set of problems caused when multiple applications attempt to share a common component like a dynamic link library (DLL) or a Component Object Model (COM) class.

 

The reason for this issue was that the version information about the different components of an application was not recorded by the system. (Windows Registry cannot support the multiple versions of same COM component this is called the dll hell problem.)

 

.Net Framework provides operating systems with a Global Assembly Cache (GAC). This Cache is a repository for all the .Net components that are shared globally on a particular machine. When a .Net component is installed onto the machine, the Global Assembly Cache looks at its version, its public key, and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between different versions of the same component, or DLL.

 

Architecture of .NET Framework

framework (1).jpg
 

Architecture of CLR


CLR.gif

CLS (Common Language Specification)

 

It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS.

 

Code Manager

 

Code manager invokes class loader for execution.

 

.NET supports two kind of coding

 

1) Managed Code

2) Unmanaged Code

 

Managed Code

 

The resource, which is with in your application domain is, managed code. The resources that are within domain are faster.

 

The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.

 

Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.


managed_code.gif
 

Unmanaged Code

 

The code, which is developed outside .NET, Framework is known as unmanaged code.

 

Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.

 

Unmanaged code can be unmanaged source code and unmanaged compile code.

 

Unmanaged code is executed with help of wrapper classes.

 

Wrapper classes are of two types: CCW (COM callable wrapper) and RCW (Runtime Callable Wrapper).

 

Wrapper is used to cover difference with the help of CCW and RCW.

COM callable wrapper unmanaged code


unmanaged_code_COM.gif

Runtime Callable Wrapper unmanaged code

unmanaged_code_RCW.gif

Native Code

 

The code to be executed must be converted into a language that the target operating system understands, known as native code. This conversion is called compiling code, an act that is performed by a compiler.

 

Under the .NET Framework, however, this is a two - stage process. With help of MSIL and JIT.

 

MSIL (Microsoft Intermediate Language)

 

It is language independent code. When you compile code that uses the .NET Framework library, you don't immediately create operating system - specific native code.

 

Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL code is not specific to any operating system or to any language.

 

JIT (Just-in-Time)

 

Just - in - Time (JIT) compiler, which compiles MSIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just - in - time part of the name reflects the fact that MSIL code is only compiled as, and when, it is needed.

 

In the past, it was often necessary to compile your code into several applications, each of which targeted a specific operating system and CPU architecture. Often, this was a form of optimization.

 

This is now unnecessary, because JIT compilers (as their name suggests) use MSIL code, which is independent of the machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the appropriate one will be used to create the native code required.

 

The beauty of all this is that it requires a lot less work on your part - in fact, you can forget about system - dependent details and concentrate on the more interesting functionality of your code.

 

JIT are of three types:

  1. Pre JIT
  2. Econo JIT
  3. Normal JIT
Pre JIT

 

It converts all the code in executable code and it is slow

 

Econo JIT

 

It will convert the called executable code only. But it will convert code every time when a code is called again.

 

Normal JIT

 

It will only convert the called code and will store in cache so that it will not require converting code again. Normal JIT is fast.

 

Assemblies

 

When you compile an application, the MSIL code created is stored in an assembly. Assemblies include both executable application files that you can run directly from Windows without the need for any other programs (these have a .exe file extension), and libraries (which have a .dll extension) for use by other applications.

 

In addition to containing MSIL, assemblies also include meta information (that is, information about the information contained in the assembly, also known as metadata) and optional resources (additional data used by the MSIL, such as sound files and pictures).

 

The meta information enables assemblies to be fully self - descriptive. You need no other information to use an assembly, meaning you avoid situations such as failing to add required data to the system registry and so on, which was often a problem when developing with other platforms.

 

This means that deploying applications is often as simple as copying the files into a directory on a remote computer. Because no additional information is required on the target systems, you can just run an executable file from this directory and (assuming the .NET CLR is installed) you're good to go.

 

Of course, you won't necessarily want to include everything required to run an application in one place. You might write some code that performs tasks required by multiple applications. In situations like that, it is often useful to place the reusable code in a place accessible to all applications. In the .NET Framework, this is the Global Assembly Cache (GAC). Placing code in the GAC is simple - you just place the assembly containing the code in the directory containing this cache.

 

Garbage Collection (GC)

 

One of the most important features of managed code is the concept of garbage collection. This is the .NET method of making sure that the memory used by an application is freed up completely when the application is no longer in use.

 

Prior to .NET this was mostly the responsibility of programmers, and a few simple errors in code could result in large blocks of memory mysteriously disappearing as a result of being allocated to the wrong place in memory. That usually meant a progressive slowdown of your computer followed by a system crash.

 

.NET garbage collection works by inspecting the memory of your computer every so often and removing anything from it that is no longer needed. There is no set time frame for this; it might happen thousands of times a second, once every few seconds, or whenever, but you can rest assured that it will happen.

 

Will try to explain the processing in terms of C# code which is written using .NET Framework.

 

Step 1- Application code is written using a .NET - compatible language C#.


 

fig1.gif

Step 2 -
 Code is compiled into MSIL, which is stored in an assembly (see Figure 1 - 2).


 

fig2.gif

Step 3 -
 When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler.


 

fig3.gif

Step 4 -
 The native code is executed in the context of the managed CLR, along with any other running applications or processes.
 


fig4.gif
 

Note:  One additional point concerning this process. The C# code that compiles into MSIL in step 2 needn't be contained in a single file. It's possible to split application code across multiple source code files, which are then compiled together into a single assembly. This extremely useful process is known as linking.

 

This is because it is far easier to work with several smaller files than one enormous one. You can separate out logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed.

 

This also makes it easy to locate specific pieces of code when you need them and enables teams of developers to divide up the programming burden into manageable chunks, whereby individuals can check out pieces of code to work on without risking damage to otherwise satisfactory sections or sections other people are working on.

 

Posted by Anshul Jain
Jquery in Asp.Net

“jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web. A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code … There is a huge ecosystem and community built up around JQuery. The jQuery library also works well on the same page with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.”

With that, JQuery is officially embraced by ASP.NET.

A brief introduction of JQuery

jQuery is the star among the growing list of JavaScript libraries. A few of its characteristics are light-weight, cross-browser compatibility and simplicity. A common task that sometimes takes 10 lines of code with traditional JavaScript can be accomplished with jQuery in just one line of code. For example, if you want to dress up a table with an ID mytable with alternative color for every other row, you can simple do this in jQuery. 

Listing 1: jQuery code for making a zebra-style table

1.<script>
2.$(function() {
3.$("table#mytable tr:nth-child(even)").addClass("even");
4.});
5.</script>

The magic dollar sign ($) and a chain of operations

In jQuery, the most powerful character / symbol is the dollar sign. A $() function normally returns a set of objects followed by a chain of operations. An example

1.$("div.test").add("p.quote").html("a little test").fadeOut();

Think of it as a long sentence with punctuations. Indeed it is a chain of instructions to tell the browser to do the following:

  1. Get a div with class name is test;
  2. Insert a paragraph with class name is quote;
  3. Add a little text to the paragraph;
  4. Operate on the DIV using a predefined method called fadeout.

So there it is, the first two basics: $() and chainable.

jQuery Selectors

JQuery uses CSS selectors to single out one element or a group of elements, and normally we use a combination of them to target specific elements. For example:

$(‘p.note’) returns all <p> elements whose class name is note;

$(‘p#note’) returns the <p> element whose id is note;

$(‘p’) returns all <p> elements

To select a child or children, we use the right angle bracket (>), as in $(‘p>a’) (returns all of the hyper links within the <p> element);

To select element(s) with certain attributes, we use [], as in input[type=text] (returns all text input element);

To select a container of some other elements, we use has keyword, for example: $(‘p:has(a)’) (returns all <p> elements that contains an hyperlink);

jQuery also has a position-based selector for us to select elements by position, for example $(‘p:first’)

Document.Ready()

The most commonly used command in jQuery is Document.Ready(). It makes sure code is executed only when a page is fully loaded. We often place code blocks inside this Document.Ready() event. For example:

1.$(document).ready(function(){
2.$("#buttonTest").click(function(event){
3.alert("I am ready!");
4.});
5.});

So far, we have brushed upon a bit of the core jQuery library. The true power of jQuery lies in its speed and flexibility and extendibility, and the ever-growing however already immense collection of jQuery plugins that deal with tasks big and small. As of today, by the tally of jQuery.com, there are 1868 plug-ins, including 100 in AJAX, 123 in Animation and effects, 66 in data, 321 in user interface. After all, JQuery is designed to be small and nimble, providing only the core functionalities required in the most common scenarios, and make others available only when needed and serve in the form of a plug-in.

ASP .NET and JQuery

Long gone is the era when most computing was done on a desktop, when web pages were more or less like virtual bulletin board. Now the impatient and internet-saturated generation is insatiable with substance, dynamics and connectivity. They want rich content, dazzling visual and instant feedback. More than ever, web development has become a tight coordinated dance between server and client. The server does the heavy lifting in the background, processes requests, churns up data and passes it back to the requesting client; from which point the client computer takes over. Interactions now taken place between web and user would be taken care by client side script, and web server would only be involved when client initiates a new request for data operation. The introduction and adoption of AJAX (the technique of performing asynchronous requests through client scripts) is fueled by and fuels this trend.

While AJAX is now the unifying technique across browsers (IE or Firefox), platforms (PC or MAC) and languages (C# or Java or PhP), it did not launch onto this popularity train until just a few years ago, when Google showcased its power with an array of applications. So with Google maps, Gmail, Google news, AJAX becomes the gold messenger of server and client communication. As if overnight, more than 100 AJAX libraries sprung up to simplify and smooth this process.

jQuery is one of the more effective and light-weighted ones. ASP .NET team has come up with its own AJAX and JavaScript libraries in its unifying ambition to convert every programmer (be it C# or VB or something else) into a Microsoft faithful. However, its JavaScript library is considerably bulky, bandwidth-costly and poses a steep learning curve.

On the other hand, ASP .NET has always been predominantly a server side technology, web services and code behind page methods have always been the founding stones of web applications. The development of ASP .NET AJAX helps developers to easily make service calls from client side script.

Let’s take a look at how we can use jQuery to consume ASP .NET web services and page methods.

Consuming ASP .NET web services using jQuery

From the conception to now, web services has gone a long way. Web services use XML as the default data exchange format and SOAP as its protocol. However it has long been dogged by complaints of complexity and lack of open standards. XML as its default message format often feels cumbersome and bandwidth-heavy.

However, with AJAX, JSON overtook XML as a more efficient alternative. It retains all of the advantages claimed by XML, such as being readable and writable for humans, and easy to parse and generate. JSON, though completely language independent, borrows a lot of conventions from languages such as C, C++, C#, Java, JavaScript, Perl, Python, etc. This makes JSON an instant hit among programmers.

Tailored to accommodate this trend, data returned from ASP .NET web script services are by default in JSON format.

JSON serialized web service

The following is a dummy ASP .NET web service. Please note that this service is adorned with the ScriptService attribute that makes it available to JavaScript clients.

Listing 2: A Dummy web service

01.[WebService(Namespace = "http://tempuri.org/")]
02.[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
03.[System.Web.Script.Services.ScriptService]
04.public class dummyWebservice : System.Web.Services.WebService
05.{
06.[WebMethod()]
07.public string HelloToYou(string name)
08.{
09.return "Hello " + name;
10.}
11.[WebMethod()]
12.public string sayHello()
13.{
14.return "hello ";
15.
16.}

If we call the method sayHello and then use Firebug for Firefox to check the server response, it would look like this:

A call (GET or POST) to ASP .NET JSON-serialized web services must meet two criteria:

  • It must carry a HTTP Content-Type header with its value set to application/json
  • It must be called via the HTTP POST verb or else the request would be rejected. To submit a GET request, we just need to submit empty data string.

Consuming a web service using ASP .NET AJAX

It is easy to call web services with the native ASP .NET AJAX, which would automatically take care all of the gritty details. It takes two steps:

First, add a ServiceReference to the ScriptManager control in the web form, as such:

1.<asp:ScriptManager ID="_scriptManager" runat="server">
2.<Services>
3.<asp:ServiceReference Path="dummywebservice.asmx" />
4.</Services>
5.</asp:ScriptManager>

Second, call any web methods defined in the web service by passing the necessary parameters and a callback function. The callback will be invoked once the data is returned from server. The following is a complete example of how we call a web service using ASP .NET AJAX.

Listing 3: Calling a web service using ASP .NET AJAX

01.<%@ Page Language="C#" %>
02.<%@ Import Namespace="System.Web.Services" %>
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
05.<html  >
06.<head id="Head1" runat="server">
07.<title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
08.<script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">  
09.</script
10.<script type="text/javascript">
11.function OnSayHelloClick() {
12.var txtName = $get("name");
13.dummyWebservice.HelloToYou(txtName.value, SayHello);
14.}
15.function SayHello(result) {
16.alert(result);
17.}
18.</script
19.</head>
20.<body>
21.<form id="form1" runat="server">
22.<asp:ScriptManager ID="_scriptManager" runat="server">
23.<Services