Asp.Net examples

This asp.net tutorial for beginners will help you to learn asp.net with few ecamples. We will see below asp.net examples:

  • Bind dropdownlist from ArrayList or hashtable in Asp.Net
  • Bind dropdownlist from enum in Asp.Net
  • Set default focus to controls in Asp.Net
  • Cross-page posting in Asp.Net
  • What is AutoEventWireup attribute in Asp.Net?
  • Preventing Files from Being Downloaded in Asp.Net.
  • Page.IsPostBack Property in Asp.Net
  • Post form data to 3rd party URL in Asp.Net
  • How to store custom objects in view state in asp.net?
  • Caching in Asp.Net
  • Page Level Output Caching in Asp.Net
  • Fragment Caching or User Control Output Caching in Asp.Net
  • Data Caching in Asp.Net
  • GAC in Asp.Net
  • DataAdapter in Asp.Net
  • How to populate dataset with data adapter and XML in Asp.Net?
  • Adding meta tags to aspx pages in asp.net
  • Performance Monitoring in ASP.Net 4.0
  • What is Bundling and Minification in ASP.Net 4.5?
  • Hosting in Asp.Net vs Windows Service
  • Hosting in a Windows Service
  • Hosting in a Windows Service:
  • global.asax file in Asp.Net
  • How to send data through SoapHeader in webservices in Asp.net?
  • What is SOAP in Asp.Net?
  • How to use WSDL.exe in Asp.Net?
  • Secure Socket Layer (SSL) in Asp.Net
  • await and async Task-Based Asynchronous Modules and Handlers in Asp.Net

You may like below .net tutorials:

Permanently Redirect a Page in Asp.Net

Now, we will see how to permanently redirect a page to a different address in Asp.Net.

In Asp.Net we can redirect one page to another page using Response. Redirect. But the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

But in Asp.Net 4, ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example:

RedirectPermanent("/new path/foroldcontent.aspx");

Search engines and other user agents that recognize permanent redirects will store the new URL that is associated with the content, which eliminates the unnecessary round trip made by the browser for temporary redirects.

Bind dropdownlist from ArrayList or hashtable in Asp.Net

Now, we will see how to bind a dropdown list using ArrayList or hashtable in Asp.Net.

Here I have taken 2 dropdownlist name as ddlWebSiteListArrayList and ddlWebSiteListHashTable in an asp.net web page. And I am binding the ddlWebSiteListArrayList from the array list and binding ddlWebSiteListHashTable from a Hashtable.

Below is the code to bind dropdownlist from arraylist or hashtable in Asp.Net

.Aspx code:

<div>
Bind From ArrayList:
<asp:DropDownList ID="ddlWebSiteList" runat="server">
</asp:DropDownList>
<br /><br />
Bind From Hashtable:
<asp:DropDownList ID="ddlWebSiteListHashTable" runat="server">
</asp:DropDownList>
</div>

.cs code:

First we have to include the System.Collections namespace.

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

public partial class BindDropDownListFromArrayList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownFromArrayList();
BindDropDownFromHashTable();
}
}

//This function will bind the dropdownlist from ArrayList
void BindDropDownFromArrayList()
{
ArrayList list = new ArrayList();
list.Add("AspDotNetHelp.com");
list.Add("SharePointDotNet.com");
list.Add("EnjoySharePoint.com");
list.Insert(1, "Fewlines4Biju.com");

ddlWebSiteList.DataSource = list;
ddlWebSiteList.DataBind();
}

//This function will bind the dropdownlist from Hashtable
void BindDropDownFromHashTable()
{
Hashtable hashItems = new Hashtable();
hashItems.Add("1", "AspDotNetHelp.com");
hashItems.Add("2", "SharePointDotNet.com");
hashItems.Add("3", "EnjoySharePoint.com");
hashItems.Add("4", "Fewlines4Biju.com");

ddlWebSiteListHashTable.DataSource = hashItems;
ddlWebSiteListHashTable.DataTextField = "Value";
ddlWebSiteListHashTable.DataValueField = "Key";
ddlWebSiteListHashTable.DataBind();
}
}

The output is shown in the figure below:

Bind dropdownlist from Arraylist in asp.net
Bind dropdownlist from hashtable in Asp.Net

Bind dropdownlist from enum in Asp.Net

Now, we will see how to bind a dropdown list from enum in asp.net.

Here is an example where I am binding a drop-down list from an enum.

First write an enum like below:

public enum UserRole
{
Developer = 1,
Admin = 2,
SuperAdmin = 3,
SuperDuperAdmin = 4
}

Now we can put a dropdownlist in the .aspx page and we can bind like below:

Below is the full code to bind dropdownlist from enum in Asp.Net

.Aspx Code:

<div>
User Roles: <asp:DropDownList ID="ddlUserRoles" runat="server"></asp:DropDownList>
</div>

.CS Code:

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

public partial class EnumTest : System.Web.UI.Page
{
public enum UserRole
{
Developer = 1,
Admin = 2,
SuperAdmin = 3,
SuperDuperAdmin = 4
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] enumRoles = Enum.GetNames(typeof(UserRole));
foreach (string item in enumRoles)
{
//get the enum item value
int value = (int)Enum.Parse(typeof(UserRole), item);
ListItem listItem = new ListItem(item, value.ToString());
ddlUserRoles.Items.Add(listItem);
}
}
}
}

After this it will come like below:

Bind dropdownlist from enum in Asp.Net

Set default focus to controls in Asp.Net

Now, we will see how to set the default focus to controls in Asp.Net.

To set focus on an ASP.NET Web server control, you can call the Focus method of the web server control. The focus method id available to controls like: Button, LinkButton, ImageButton, CheckBox, DropDownList, FileUpload, HyperLink, ListBox, RadioButton, TextBox etc.

You can set the focus of control at run time like below:

protected void Page_Load(object sender, EventArgs e)
{
txtUserName.Focus();
}

Also you can set focus by using the SetFocus method like below:

protected void Page_Load(object sender, EventArgs e)
{
Page.SetFocus(txtUserName);
}

To set default focus in a form:

To set the focus in a form do like below:

<form id="form1″ runat="server" defaultfocus="txtUserName" >
<div>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</div>
</form>

This is how to set default focus to controls in Asp.Net.

Cross-page posting in Asp.Net

Here, we saw how to do cross page posting in asp.net.

Cross page posting helps send data from one page to another in Asp.Net. This helps the postback mechanism.

This can be achieved by a proerty name as PostBackUrl, which is defined by the IButtonControl interface. Its available for controls like ImageButton, LinkButton, and Button etc.

To use cross-posting, you simply set PostBackUrl to the name of another web form. When the user clicks the button, the page will be posted to that new URL with the values from all the input controls on the current page.

Example:

<asp:Button runat="server" ID="btnClick" PostBackUrl="Page2.aspx" Text="Cross-Page Postback" />

To retrieve the value in the second page, write like below:

protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
string previousPageTitle = PreviousPage.Title;
}
}

This page is meant for single page only.

What is AutoEventWireup attribute in Asp.Net?

Now, we will see what is AutoEventWireup attribute in Asp.Net?

  • AutoEventWireup attribute is a boolean attribute which is usually used in the Page directive. The ASP.NET page framework supports an automatic way to associate page events and methods.
  • If the AutoEventWireup attribute of the Page directive is set to true, the page framework calls page events automatically, specifically the Page_Init and Page_Load methods.
  • If AutoEventWireup=”false” but still you want to execute the Page_Load event then you have to explicitly code for it like below:
  • When AutoEventWireup is true, handlers are automatically bound to events at runtime based on their name and signature.
  • The default value is true if AutoEventWireup is not specified in the @ Page directive. Visual Studio automatically includes the attribute when it creates code-behind files.
  • For ASP.NET pages written in C#, Visual Studio sets the value to true. For Visual Basic, Visual Studio sets the value to false because handlers are bound to events by using the Handles keyword, which is inserted automatically by Visual Studio when it generates an event handler.
  • The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers.

Preventing Files from Being Downloaded in Asp.Net.

HttpForbiddenHandler class is used to prevent certain file types from being downloaded over the Web. This class is used internally by ASP.NET to prevent the download of certain system level files.

To use the HttpForbiddenHandler to prevent a particular file type from being downloaded, refer below.

Create an application mapping in IIS for the specified file type to map it to Aspnet_isapi.dll.

  • On the taskbar, click the Start button, click Programs, click Administrative Tools, and then select Internet Information Services.
  • Select your application’s virtual directory, right-click, and then click Properties.
  • Select Application Settings, click Configuration.
  • Click Add to create a new application mapping.
  • Click Browse, and select c:\winnt\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll.
  • Enter the file extension for the file type you want to prevent being downloaded (for example, .xyz) in the Extension field.
  • Ensure All Verbs and Script engine is selected and Check that file exists is not selected.
  • Click OK to close the Add/Edit Application Extension Mapping dialog box.
  • Click OK to close the Application Configuration dialog box, and then click OK again to close the Properties dialog box.

Add an <HttpHandler> mapping in Web.config for the specified file type. An example for the .xyz file type is shown below.

<httpHandlers>
<add verb="*" path="*.xyz" type="System.Web.HttpForbiddenHandler"/>
</httpHandlers>

Page.IsPostBack Property in Asp.Net

Now, we will see the Page.IsPostBack Property in Asp.Net.

  • Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
  • The IsPostBack property can be used to determine if the page is submitted to itself. When a form is submitted back to the same page that contains it, it’s called a post back. ASP.NET provides a property called IsPostBack that is TRUE when the page is being loaded as a result of a post back, and is FALSE otherwise.

Below is the way to use IsPostBack property

C#.Net Syntax:

private void Page_Load()
{
    if (!IsPostBack)
    {
        //You can write here the code, which you want to execute in the first time when the page is  loaded.
        FunctionToBindSomething();
    }
}

VB.Net Syntax:

Sub Page_Load
         IF Not IsPostBack THEN
                    ‘ You can write here the code, which you want to execute in the first time when the  page is loaded.
        FunctionToBindSomething();
          END IF
End Sub

This is how we can use Page.IsPostBack Property in Asp.Net.

Post form data to 3rd party URL in Asp.Net

Now, we will see how to send form data to a 3rd party URL in Asp.Net.

There will be certain situations where you will not prefer to send data through a query string to a 3rd party URL. In that, we can use the post method to send data to the 3rd party URL.

For this, we have to write a JavaScript method as well as we need to put input variables inside the form tag. Follow the below code:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Post form data to 3rd party URL in Asp.Net</title>
<script language="javascript" type="text/javascript">
function postvaluesTraining() {
document.forms[0].action = ‘http://UR 3rd Party URL/welcome.aspx’;
document.forms[0].submit();
return true;
}
</script>
</head>
<body>
<form id="form1″ runat="server">
<div>
<input type="hidden" name="Name" value="enjoysharepoint" />
<input type="hidden" name="siteURL" value="www.enjoysharepoint.com" />
<input type="hidden" name="email" value="info@enjoysharepoint.com" />
</div>
</div>
</form>
</body>
</html>

How to store custom objects in view state in asp.net?

Now, we will see how to store custom objects in the view state in asp.net.

To store an object in view state, the object must be serializable means, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is known as serialization.

To make your objects serializable, you need to add a Serializable attribute before your class declaration.

[Serializable] public class Employee
{
private string firstName;
private string lastName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}

Here the above class becomes a serializabled class since we write the [Serializable] attribute at the beginning of the class.

Employee objEmployee = new Employee("Bijay", "Kumar");
ViewState["NewEmployee"] = objEmployee;

Here the Employee object will be stored in the view state.

To retrieve the custom object from the view state writes like below:

Employee obj = (Employee)ViewState["NewEmployee"];

Remember If the Serializable attribute isn’t present, the class isn’t serializable, and you won’t be able to place instances of it in view state.

Caching in Asp.Net

Caching is a very good technique provided by Asp.Net to improve the performance of an Asp.Net site. Caching is the process of storing frequently used data on the server to fulfill subsequent requests.

This technique improves web response time. Through this technique, we store some static or dynamic content in server cache memory so that the webserver can easily retrieve data the next time when the request comes. This also minimizes the database hits as well as minimize the consumption of server resources.

There are different types of caching in asp.net like below:

Page Level Output Caching in Asp.Net

This is the simplest form of caching. Output caching simply keeps a copy of the HTML that was sent in response to a request in memory. Subsequent requests are then sent the cached output until the cache expires, resulting in potentially very large performance gains.

To implement page output caching we have to add OutputCache directive to the page like below:

<%@ OutputCache Duration="60" VaryByParam="*" %>

Here Duration and VaryByParam are mandatory parameters and appart from that there are also parameters like Location, VaryByHeader, VaryByCustom.

Duration: specifies the time the page should be cached (in seconds).

VaryByParam: Specifies the name of variables for request. The value “none” represents no variation and the value “*” represents to create new cache entries for every different set of variables.

Fragment Caching or User Control Output Caching in Asp.Net

Like page level caching we can also implement caching to the user controls. Fragment caching allows us to cache certain blocks of your website.

To implement caching we have to add OutputCache directive like below:

<%@ OutputCache Duration="60" VaryByParam="*" %>

The parameters will be as explained in the Page Level Output Caching.

Data Caching in Asp.Net

The above type of caching will be helpful in caching the output of a page. We can also cache DataSet objects like below:

Cache["MyDataSet"] = dsMyDataSet;

Similarly to retrieve the dataset from the cache we can use like below:

DataSet dsFromCache = new DataSet();
dsFromCache = (DataSet) Cache["MyDataSet"];

Here we learned about caching in asp.net.

GAC in Asp.Net

Now, let us understand what is GAC in.Net.

GAC stands for Global Assembly Cache. GAC can be termed as a registry of.Net framework for maintaining shared assemblies. This comes with.Net installation.

Location of GAC is C:\Windows\assembly. The GAC folder is accessible with security options-

  • The folder will only accept strong name assemblies.
  • The folder is accessible to the user with administrative privileges for placing assembly or removing the assembly.

You can place an assembly into GAC in two ways:

  • Drag and Drop: Through explorer view, you can drag and drop the assembly to the GAC.
  • GACUtil.exe: You can put assembly to GAC using the command line utility GACUtil.exe
Gacutil -i "Path of the assembly"

It will put the dll into GAC.

To remove an assembly from GAC you can use the same GACUtil utility as below:

Gacutil -u AssemblyName

The above command will remove the assembly from GAC.

Windows registry will maintain the location of COM components whereas GAC will contain assembly.

Windows registry cannot contain multiple versions of COM component whereas GAC can contain multiple versions of an assembly.

DataAdapter in Asp.Net

Now, we will see what is a DataAdapter in asp.net and how to use DataAdapter in asp.net.

DataAdapter will act as a mediator between dataset and database server. This will perform 2 things:

  • It will read data from the database and place it within the dataset in the form of datatables.
  • The manipulation on the dataset table will be updated with database.
string conn = "You connection string will goes here";
string strSQL = "SELECT * FROM EMPLOYEES";
SqlConnection conn = new SqlConnection(conn);
SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Employees");

Here Employees is the datatable name.

Check out the below diagram how it is working:

DataAdapter in Asp.Net

How to populate dataset with data adapter and XML in Asp.Net?

Now, we will see how to populate a dataset with data adapter and XML datasource in asp.net.

Populate from Data Adapter:

We can fill the dataset by calling the Fill() method of the Data Adapter class. Below is the full code that will fill the database.

string conn = "You connection string will goes here";
string strSQL = "SELECT * FROM EMPLOYEES";
SqlConnection conn = new SqlConnection(conn);
SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Employees");

Also you can call the fill method like below:

da.Fill(ds);

But when you want to retrieve then you have to retrieve using the index like ds.Tables[0].

But in the above method you can retrieve like ds.Tables[“Employees”].

Populate from XML:

To load XML into a DataSet class, we have to call the ReadXML() method like below:

DataSet ds = new DataSet();
ds.ReadXml("C:\\Employees.xml")

HTTP-GET in Asp.Net

The use of HTTP-GET has been rather popular for quite a while. It enables you to send your entire request, along with any required parameter, all contained within the URL submission.

Here is an example of a URL request that is passing a parameter to the server that will respond.
http://www.EnjoySharePoint.com?newcategory=AspDotNet

In this example, a request from the EnjoySharePoint.com website is made, but in addition to a typical web request, it is also passing along a parameter. Any parameters that are sent along using HTTP-GET can only be in a name /value pair construction-also known as query strings. This means that you can have only a single value assigned to a single parameter. You can’t provide hierarchical structures through query strings. As you can tell from the previous URL construction, the name/value pair is attached to the URL by ending the URL string with a question mark, followed by the variable name.

Using query strings, you can also pass more than a single name/value pair with the URL request as the following example shows:

http://ww.enjoysharepoint.com/?newcategory=AspDotNet&language=en

In this example, the URL construction includes two name/value pairs. The name /value pairs are separated with an ampersand(&).

Now turn your attention to working with the addition of web service using the HTTP-GET. To accomplish this task, you must enable HTTP-GET from within the web service application because it is disabled by default.

Enabling HTTP-GET in your web service applications

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0″>
<system.web>
<webservices>
<protocols>
<add name="HTTP-GET"/>
</protocols>
</webServices>
</system.web>
</configuration>

Creating the <protocols> section in your web.config file enables you to add or remove protocol communications.

Adding meta tags to aspx pages in asp.net

Now, we will discuss how to add meta tags and meta description to the .aspx page in an Asp.Net website.

Meta tags and descriptions are very much useful in the context of the search engine. So it is necessary to give meta tags and meta descriptions to web sites.

There are at least 3 ways we can add meta tags and descriptions to a .aspx page.

Add in the page directive

We can add meta tags and description to the page directive of a .aspx page like below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MetaTagTest.aspx.cs" Inherits="MetaTagTest" MetaDescription="A SharePoint and Asp.Net web site" MetaKeywords="SharePoint,Asp.Net,C#.Net,SQL Server" %>

Here MetaDescription, MetaKeywords are the tags to whom we can set the description and tag respectively.

Inside head section

We can add Meta tags and description inside the <head></head> section of an .aspx page like below:

<meta name="description" content="A SharePoint and Asp.Net web site" />
<meta name="keywords" content="SharePoint,Asp.Net,C#.Net,SQL Server" />

Through .aspx.cs code

Through code we can also add meta tag and meta description to a page like below:

protected void Page_Load(object sender, EventArgs e)
{
Page.MetaDescription = “A SharePoint and Asp.Net web site";
Page.MetaKeywords = “SharePoint,Asp.Net,C#.Net,SQL Server";
}

Performance Monitoring in ASP.Net 4.0

Now, we will discuss Performance Monitoring in ASP.Net 4.0.

In order to increase the number of Web sites that can be hosted on a single server, many hosters run multiple ASP.NET applications in a single worker process. However, if multiple applications use a single shared worker process, it is difficult for server administrators to identify an individual application that is experiencing problems.

ASP.NET 4.0 provides new resource-monitoring functionality introduced by the CLR. To enable this functionality, add the following XML configuration snippet to the aspnet.config configuration file.

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <runtime>
    <appDomainResourceMonitoring enabled="true"/>
  </runtime>
</configuration>

The aspnet.config file is in the directory where the .NET Framework is installed. It is not the Web.config file.

When the appDomainResourceMonitoring feature has been enabled, two new performance counters are available in the “ASP.NET Applications” performance category: % Managed Processor Time and Managed Memory Used. Both of these performance counters use the new CLR application-domain resource management feature to track estimated CPU time and managed memory utilization of individual ASP.NET applications.

As a result, with ASP.NET 4, administrators now have a more granular view into the resource consumption of individual applications running in a single worker process.

What is Bundling and Minification in ASP.Net 4.5?

Bundling is a process of combining JavaScript and CSS files into a bundle that can be treated like a single file. Minification condenses JavaScript and CSS files by removing whitespace and other characters that are not required. These features work with Web Forms, ASP.NET MVC, and Web Pages.

Bundles are created using the Bundle class or one of its child classes say ScriptBundle and StyleBundle. After configuring an instance of a bundle, the bundle is made available to incoming requests by simply adding it to a global BundleCollection instance.

In the default templates, bundle configuration is performed in a BundleConfig file. This default configuration creates bundles for all of the core scripts and CSS files used by the templates.

Bundles are referenced from within views by using one of a couple possible helper methods. In order to support rendering different markup for a bundle when in debug vs. release mode, the ScriptBundle and StyleBundle classes have the helper method, Render.

When in debug mode, Render will generate markup for each resource in the bundle. When in release mode, Render will generate a single markup element for the entire bundle. Toggling between debug and release mode can be accomplished by modifying the debug attribute of the compilation element in web.config as shown below:

<system.web>
<compilation targetframework="4.5" debug="true" />
…</system.web>

Additionally, enabling or disabling optimization can be set directly via the BundleTable.EnableOptimizations property.

BundleTable.EnableOptimizations = true;

When files are bundled, they have first sorted alphabetically (the way they are displayed in the Solution Explorer). Then they are organized so that known libraries and their custom extensions (such as jQuery, MooTools, and Dojo) are loaded first.

For example, the final order for the bundling of the Scripts folder, as shown above, will be:

  • jquery-1.6.2.js
  • jquery-ui.js
  • jquery.tools.js
  • a.js

CSS files are also sorted alphabetically and then reorganized so that reset.css and normalize.css come before any other file. The final sorting of the bundling of the Styles folder shown above will be this:

  • reset.css
  • content.css
  • forms.css
  • globals.css
  • menu.css
  • styles.css

Hosting in Asp.Net vs Windows Service

Now we will discuss the advantages and disadvantages of Hosting in Asp.Net and Hosting in a Windows Service.

Hosting in a Windows Service

When you host a remote object in ASP.NET:

  • The object is accessed using the HTTP protocol.
  • It has an endpoint that is accessible by a URL.
  • It inherits the security features offered by IIS and ASP.NET.

Advantages:

  • If you host remote objects in IIS, you benefit from the following advantages:
  • Authentication, authorization, and secure communication features provided by IIS and ASP.NET are immediately available.
  • You can use the auditing features of IIS.
  • You have a high degree of control over the hosting executable through the element in Machine.config. You can control thread management, fault tolerance, memory management, and so on.

Disadvantages:

  • If you use ASP.NET to host remote objects, you should know the disadvantages:
  • It requires the use of the HTTP channel which is slower than the TCP channel.
  • User profiles are not loaded by ASP.NET. Various encryption techniques may require user profiles.
  • If the object is being accessed from code running in an ASP.NET Web application, you may have to use Basic authentication.

Hosting in a Windows Service:

  • When you host a remote object in a Windows service, the remote object lives in an application domain contained within the service process.
  • You must provide a custom authentication solution.
  • Authorization is possible only if you implement a custom authentication solution.

Advantages:

  • If you host remote objects in Windows services, you benefit from the following advantages:
  • High degree of activation control over the host process
  • Inherits the benefits of Windows service architecture
  • User profiles are automatically loaded

Disadvantages:

  • You must provide custom authentication and authorization solutions.
  • You must provide secure communication solutions.

global.asax file in Asp.Net

Let us understand the use of global.asax file in Asp.net.

  • global.asax file is responsible for writing code for global events. These events fire at various points during the lifetime of a web application, including when the application domain is first created.
  • There can be only one global.asax file in a Asp.Net application. You can add it through visual studio, Right click on the web site -> Add New Item and then select Global Application Class file type.
  • It can’t contain any HTML or ASP.NET tags, it contains event handlers that respond to application events.

Some of the global events are:

  • Application_Start(): Occurs when the application starts, which is the first time it receives a request from any user.
  • Application_End(): Occurs when the application is shutting down, generally because the web server is being restarted.
  • Application_BeginRequest(): Occurs with each request the application receives, just before the page code is executed.
  • Application_EndRequest(): Occurs with each request the application receives, just after the page code is executed.
  • Session_Start(): Occurs whenever a new user request is received and a session is started.
  • Session_End(): Occurs when a session times out or is programmatically ended.
  • Application_Error(): Occurs in response to an unhandled error.

Example:

<%@ Application Language = "C#" %>
<script language = "c#" runat = "server">
protected void Application_EndRequest(object sender, EventArgs e)
{
//You can write code here.
}
</script>

How to send data through SoapHeader in webservices in Asp.net?

Now, I will explain how to send user data through SoapHeader in web services in asp.net.

  • Create a class named securityInfo which contains user credentials that inherits SoapHeader class.
  • Send securityInfo object in the SoapHeader attribute of the webmethod.
  • Set MustUnderstand property to true to insists that SoapHeader must understood the data.
  • Use DidUnderstand property to check whether XML webservice method properly processed the SoapHeader.
  • Create a client application, add web refference to the webservice.

WebService code:

using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public class securityInfo : SoapHeader
{
public string username;
public string password;
}
public securityInfo obj1 = new securityInfo();
[WebMethod, SoapHeader("obj1")]
public string validate()
{
string s1, s2, result;
result = "n";
obj1.MustUnderstand = true;
SqlConnection con = new SqlConnection("uid=sa;pwd=systems; Database=abi");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from Info",con);
da.Fill(ds, "userInfo");
for (int i = 0; i <= ds.Tables["userInfo"].Rows.Count; i++)
{
s1 = Convert.ToString(ds.Tables["userInfo"].Rows[i][0]);
s2 = Convert.ToString(ds.Tables["userInfo"].Rows[i][1]);
if (s1 == obj1.username.ToString() && s2 == obj1.password.ToString())
{
result = "y";
break;
}
}
if (result == "y")
{
return "valid login";
obj1.DidUnderstand = true;
}
else
return "invalid login";
}
}

Client Application Source page:

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
<asp:Button ID=" btnSubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" />
<asp:Label ID="Label1″ runat="server"></asp:Label>

Client Application Code behind page:

protected void btnSubmit_Click(object sender, EventArgs e)
{
localhost.Service obj1 = new localhost.Service();
localhost.securityInfo obj2 = new localhost.securityInfo();
obj2.username = txtUserName.Text;
obj2.password = txtPwd.Text;
obj1.securityInfoValue = obj2;
string res = obj1.validate();
if (res == "valid login")
Label1.Text = "valid user";
else
Label1.Text = "Invalid user";
}

This is how we can send data through SoapHeader in webservices in Asp.net?

What is SOAP in Asp.Net?

Now we will discuss what is SOAP in asp.net?

What is SOAP in Asp.Net

SOAP is a formatting protocol which provides standards for the arrangement of requests and response for the communication between client and web service. These standards are open industry standards given by W3C.

What is SOAP in Asp.Net

Client Application makes a method call. The request will go to a proxy. The proxy will package all the information. It includes:

  • Method Name
  • Parameters Name.
  • Parameters Value.

Then the request will be forward to SOAP. SOAP will encode the request into an XML based format called as SOAP message. The SOAP message will be given to HTTP. HTTP will carry soap message to the web service environment.

The requested method will be executed by the stub object and result will be given to SOAP. SOAP will encode the result into an XML based format called as SOAP message. This SOAP message will be given to HTTP. HTTP will carry SOAP message to the client environment. In the client, environment proxy will convert SOAP messages into normal data and provides to the client APP.

What is SOAP in Asp.Net
  • SOAP header will contain any additional information which has to be sent with the method call. This information will be authentication information that is username, password security token so on.
  • SOAP body will contain method information or result of the method.
  • SOAP fault will contain error information.

How to use WSDL.exe in Asp.Net?

Now, let us see how to generate the WSDL file using wsdl.exe.

WSDL (Web Services Description Language) is an XML-based language for describing Web services and how to access them.

This will generally create a proxy class.

The WSDL command line utility is presented in the below location. (For visual studio 2012)

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

The utility takes a different parameter, some examples given below:

wsdl http://URL/Service1.asmx?WSDL

Once you run the above command by default it will generate Service1.cs file in the below location.

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

You can also change the name of the Service1.cs file like below:

wsdl /out:myProxyClass.cs http://URL/Service1.asmx?WSDL

By default it will use C#.Net language.

You can also generate file in VB.Net like below:

wsdl /language:VB /out:myProxyClass.vb http://URL/Service1.asmx?WSDL

Secure Socket Layer (SSL) in Asp.Net

  • Secure Socket Layer (SSL) will provide secure communication between client and web service.
  • The secure communication will be provided with encryption and decryption.
  • This is strongly recommended when there is sensitive data transmitted between client and web service. The sensitive information can be a credit card number, bank account number, etc.
  • The encryption and decryption services will be provided by a Certification Authority (CA). The well-known certification authority will be verysign, awte.
  • The certification authority will provide encryption at various bit labels like 64 bit, 128 bit etc. When the bit label is high security will be more.
  • The Certification Authority (CA) will charge for providing services.
  • The company should purchase a certificate from CA and the certificate will be provided with a private and public key.
  • The certificate has to be configured with the website to implement SSL.
  • The web site configured with SSL should run on port number 443.
  • The web site configured with SSL cannot communicate with HTTP protocol, it requires https protocol.
  • When a client makes a request to the website, the public key will be given to the client. When a client submits data, encryption will take place based on the public key. The encrypted data will be sent to the web server. The web server will perform decryption with the matching private key. Then the request will be processed.
  • The response will be encrypted based on the private key. Then it will be sent to the client system. It will decrypt with the public key and the result will be given to the client.

Open Excel template in Asp.net

We have a requirement in our project that we have a link named as “ExcelTemplates”, when user clicks this link, one exceltemplate should open.

Under our project solution, we have a folder named as “TestDataTemplateExcel”,which contains the excel template named as “TestTemplate.xlsx”.

So what we did is we added a button in the .aspx page and in the .aspx.cs file in the button click event we called the below method.

private void GetTemplate()
        {
            //Get the application Path including the last \ and and truncate update to application root               //folder.
            string executablePath1 = Environment.CommandLine.Substring(1,                 Environment.CommandLine.IndexOf("\\bin"));
            // Append the Excel template folder file path from root folder onwards.
            executablePath1 = executablePath1 + "TestDataTemplateExcel\\TestTemplate.xlsx";
            System.Diagnostics.Process.Start(executablePath1);
        }

Description:

string executablePath1 = Environment.CommandLine.Substring(1, Environment.CommandLine.IndexOf("\\bin"));

The above line of code will get the application Path including the last \ and and truncate update to application root folder.

executablePath1 = executablePath1 + "TestDataTemplateExcel\\TestTemplate.xlsx";

This line of code will append the Excel template folder file path from root folder onwards.

System.Diagnostics.Process.Start(executablePath1);

System.Diagnostics.Process.Start will process and start the respective excel from the specified path.

This is how we can open Open Excel template in Asp.net programmatically.

How to use NuGet in Asp.Net

Now, we will see how to use NuGet in Asp.Net.

NuGet is a package management system for .NET and Visual Studio which helps to add, update, and remove external libraries and their dependencies in your application. Also, it helps to create packages that you can share with others.

How to install NuGet?

If you have Asp.Net MVC or Visual Studio 2012 installed, then no need to install NuGet because it has been automatically installed.

But if you are using Visual Studio 2010, then follow the below steps to install:

Open Visual Studio 2010 -> then click on Tools -> Extension Manager as shown in the fig below:

NuGet in Asp.Net

This will open the “Extension Manager” window which will show all the lists installed packages by default. Then click on the Online Gallery tab as shown in the fig below:

How to use NuGet in Asp.Net

Then type NuGet in the search bar and click on Find. Once you find NuGet, then click on the Download button and then install it.

Or if you have NuGet already installed then click on the Updates to get the latest version.

await and async Task-Based Asynchronous Modules and Handlers in Asp.Net

In .NET 4.0 an asynchronous programming concept has been introduced named as a task. Tasks are represented by the Task type and belong to System.Threading.Tasks namespace. The .NET Framework 4.5 builds on this with compiler enhancements that make working with Task objects simple. In the .NET Framework 4.5, the compilers support two new keywords: await and async. The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods.

The combination of await, async, and the Task object makes it much easier for you to write asynchronous code in .NET 4.5. ASP.NET 4.5 supports these simplifications with new APIs that let you write asynchronous HTTP modules and asynchronous HTTP handlers using the new compiler enhancements.

Asynchronous HTTP modules

Suppose that you want to perform asynchronous work within a method that returns a Task object. The following code snippet defines an asynchronous method that makes an asynchronous call to download the asp .net help page. The async keyword in the method signature says that the method is a task-based asynchronous method and the await keyword says that asynchronously wait and call to the method DownloadStringTaskAsync.

private async Task
ScrapeHtmlPage(object caller, EventArgs e)
{
WebClient wc = new WebClient();
var result = await wc.DownloadStringTaskAsync(“http://www. aspdotnethelp.com”);
// Do something with the result
}

The .NET Framework will automatically handle unwinding the call stack while waiting for the download to complete, as well as automatically restoring the call stack after the download is done.

You can use this asynchronous method in an asynchronous ASP.NET HTTP module. ASP.NET 4.5 includes a helper method called EventHandlerTaskAsyncHelper and a new delegate type named TaskEventHandler. The TaskEventHandler delegate is used to integrate task-based asynchronous methods with the older asynchronous programming model exposed by the ASP.NET HTTP pipeline. This example shows how:

public void Init(HttpApplication context)
{
// Wrap the Task-based method so that it can be used with
// the older async programming model.
EventHandlerTaskAsyncHelper helper =
new EventHandlerTaskAsyncHelper(ScrapeHtmlPage);

// The helper object makes it easy to extract Begin/End methods out of
// a method that returns a Task object. The ASP.NET pipeline calls the
// Begin and End methods to start and complete calls on asynchronous
// HTTP modules.
context.AddOnPostAuthorizeRequestAsync(
helper.BeginEventHandler, helper.EndEventHandler);
}

Asynchronous HTTP handlers

The traditional way of writing asynchronous handlers in ASP.NET is through the IHttpAsyncHandler interface. ASP.NET 4.5 introduces an asynchronous base type abstract class named HttpTaskAsyncHandler. You can write asynchronous handlers easily by deriving this base class. Since this is an abstract class you need to override the method named ProcessRequestAsync. Internally ASP.NET takes care of integrating the return signature (a Task object) of ProcessRequestAsync with the older asynchronous programming model used by the ASP.NET pipeline.

The following code snippet shows how you can use Task and await as part of the implementation of an asynchronous HTTP handler:

public class MyAsyncHandler : HttpTaskAsyncHandler
{
// ASP.NET automatically takes care of integrating the Task based override
// with the ASP.NET pipeline.
public override async Task ProcessRequestAsync(HttpContext context)
{
WebClient wc = new WebClient();
var result = await
wc.DownloadStringTaskAsync(“http://www.microsoft.com”);
// Do something with the result
}
}

Asp.Net provider model tutorial

The Asp.Net provider model is an important framework to understand as you build your applications. The Asp.Net provider model was a major change introduced back with the release of Asp.Net 2.0.

The simple nature of this model means that requests come in and then responses are sent back. On top of that, Asp.Net does not differentiate one request from another. The server containing an Asp.Net application is simply reacting to any request thrown at it.

A provider is an object that allows for programmatic access to data stores, processes, and more.
The available providers for storing session information including

  • InProc
  • StateServer
  • SQLServer

This provider model was an object that sat between the Session object and the actual place in which the sessions were stored. By default, sessions in Asp.Net are stored InProc, meaning in the same process where ASP.NET is running.

Besides InProc, you can use StateServer that enables you to store sessions in a process that is entirely separate from the one in which Asp.Net runs. This protects your sessions if the Asp.Net process shuts down.

Different Methods in SqlRoleProvider class in Asp.Net

Now, we will see various method of SqlRoleProvider class like Createrole(), deleterole(), AddUsersToRoles() Method etc.

The Createrole() Method:

The CreateRole() method in the SqlRoleProvider class allows developers to add any role to the system.

The only parameter required for this method is a string value that is the name of the role.

For this example, instead of letting developers create any role they want, this provider limits the role creation to only the Administrator and Manager roles.

Allowing only the administrator or Manager role in the Createrole() method

You are going to need to import the System.Configuration.Provider namespace for this code to work.

public override void CreateRole(string roleName)
{
if (roleName == "Administrator" || roleName == "Manager")
{
base.CreateRole(roleName);
}
else
{
throw new
ProviderException("Role creation limited to only Administrator and Manager");
}
}

In this method, you can see that a check is first done to determine whether the role being created is either Administrator or Manager. If the role being created is not one of these defi ned roles, a ProviderException is thrown informing the developer of which roles he or she is allowed to create.

If Administrator or Manager is one of the roles, then the base class ( SqlRoleProvider ) CreateRole() method is invoked.

The deleterole() Method:

If you allow developers using this provider to create only specifi c roles, you might not want them to delete any role after it is created. If this is the case, you want to override the DeleteRole() method of the SqlRoleProvider class.

public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
return false;
}

Looking at the DeleteRole() method, you can see that deleting any role is completely disallowed. Instead of raising the base class’s DeleteRole() and returning the following:

Return MyBase.DeleteRole(roleName, throwOnPopulatedRole) a False value is returned and no action is taken.

The AddUsersToRoles() Method:

Only one single method allows you to add any number of users to any number of roles. Multiple methods in the Roles class actually map to this method.

All these actually map to the AddUsersToRoles() method that is available in the RoleProvider base class.

Disallowing users to be added to a particular role.

public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
foreach (string roleItem in roleNames)
{
if (roleItem == "Administrator")
{
throw new ProviderException("You are not authorized to add any users" + " to the Administrator role");
}
}
base.AddUsersToRoles(usernames, roleNames);
}

This overridden method iterates through all the provided roles, and if one of the roles contained in the string array is the role Administrator, then a ProviderException instance is thrown informing the developer that he or she is not allowed to add any users to this particular role. Although it is not shown here, you can also take the same approach with the RemoveUsersFromRoles() method exposed from the RoleProvider base class.

Logging in Users Programmatically in Asp.Net

Now, we will see how to do Logging in users programmatically in Asp.Net.

You can use pre-built mechanics of the Login control or you can also perform this task programmatically using the Membership class. To validate credentials that you receive, you use the ValidateUser() method of this class. The ValidateUser() method takes a single signature:

Membership.ValidateUser(username As String, password As String)

Validating a user’s credentials programmatically

In VB.net:

If Membership.ValidateUser(TextBox1.Text, TextBox2.Text) Then
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, False)
Else
Label1.Text = "You are not registered with the site."
End If

In C#.net:

if (Membership.ValidateUser(TextBox1.Text, TextBox2.Text)
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text.ToString(), false);
}
else
{
Label1.Text = "You are not registered with the site.";
}

The ValidateUser() method returns a Boolean value of True if the user credentials pass the test and False if they do not.

you can see that end users whose credentials are verified as correct are redirected from the login page using the RedirectFromLoginPage() method. This method takes the username and a Boolean value that specifies whether the credentials are persisted through a cookie setting.

Lock users who provide bad passwords in Asp.Net

Now, we will see how we can locking out users who provide bad passwords in asp.net.

When providing a user login form in any application you build, always guard against repeated bogus password attempts. If you have a malicious end user who knows a username, he may try to access the application by repeatedly trying different passwords. You want to guard against this kind of activity. You don’t want to allow this person to try hundreds of possible passwords with this username.

ASP.NET has built-in protection against this type of activity.

FailedPasswordAttemptCount and FailedPasswordAttemptWindowStart are the two columns provided by Asp.net to control this type of activity.

By default, a username can be used with an incorrect password in a login attempt only five times within a 10-minute window. On the fifth failed attempt, the account is locked down. You do this in ASP.NET by setting the IsLockedOut column to True.

You can actually control the number of password attempts that are allowed and the length of the attempt window for your application. These two items are defined in the SqlMembershipProvider declaration in the machine.config file. You can change the values either in the server-wide configuration files or in your application’s web.config file like below.

Changing the values for password attempts in the provider declaration

<configuration>
<system.web>
<membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
<clear />

<add connectionStringName="ApplicationServices"
applicationName="/"
maxInvalidPasswordAttempts="3"
passwordAttemptWindow="15"
name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
</system.web>
</configuration>

To determine the number of password attempts that are allowed, use maxInvalidPasswordAttempts.

This example changes the value to 3, meaning that users are allowed to enter an incorrect password three times before being locked out (within the time window defined). The default value of the maxInvalidPasswordAttempts attribute is 5. You can set the time allowed for bad password attempts to 15 minutes using the passwordAttemptWindow attribute. The default value of this attribute is 10.

A sample page to test password attempts:

protected void Button1_Click(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
MembershipUser user = Membership.GetUser(TextBox1.Text);
user.UnlockUser();
}
if (Membership.ValidateUser(TextBox1.Text, TextBox2.Text))
{
Label1.Text = “You are logged on!";
}
else
{
MembershipUser user = Membership.GetUser(TextBox1.Text);
Label1.Text = “Locked out value: " + user.IsLockedOut.ToString();
}
}

This page contains two text boxes: one for the username and another for the password. Above these, however, is a check box that you can use to unlock a user after you have locked down the account because of bad password attempts.

The IsLockedOut property is read through an instantiation of the MembershipUser object. The IsLockedOut property is retrieved and displayed on the screen.

UnlockUser() is invoked if the checkbox is selected in the button-click event.

You may also like following asp.net tutorials:

Here, we discussed below asp.net examples:

  • Bind dropdownlist from ArrayList or hashtable in Asp.Net
  • Bind dropdownlist from enum in Asp.Net
  • Set default focus to controls in Asp.Net
  • Cross-page posting in Asp.Net
  • What is AutoEventWireup attribute in Asp.Net?
  • Preventing Files from Being Downloaded in Asp.Net.
  • Page.IsPostBack Property in Asp.Net
  • Post form data to 3rd party URL in Asp.Net
  • How to store custom objects in view state in asp.net?
  • Caching in Asp.Net
  • Page Level Output Caching in Asp.Net
  • Fragment Caching or User Control Output Caching in Asp.Net
  • Data Caching in Asp.Net
  • GAC in Asp.Net
  • DataAdapter in Asp.Net
  • How to populate dataset with data adapter and XML in Asp.Net?
  • Adding meta tags to aspx pages in asp.net
  • Performance Monitoring in ASP.Net 4.0
  • What is Bundling and Minification in ASP.Net 4.5?
  • Hosting in Asp.Net vs Windows Service
  • Hosting in a Windows Service
  • Hosting in a Windows Service:
  • global.asax file in Asp.Net
  • How to send data through SoapHeader in webservices in Asp.net?
  • What is SOAP in Asp.Net?
  • How to use WSDL.exe in Asp.Net?
  • Secure Socket Layer (SSL) in Asp.Net
  • await and async Task-Based Asynchronous Modules and Handlers in Asp.Net
Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>