Showing posts with label ASP.NET Tutorial. Show all posts
Showing posts with label ASP.NET Tutorial. Show all posts

Monday, 16 June 2014

ASP.NET - Quick Guide

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

ASP.NET - Quick Guide

What is ASP.Net?

ASP.Net is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web application for PC, as well as mobile devices.
ASP.Net is a part of Microsoft .Net platform. ASP.Net applications could be written in either of the following languages:
  • C#
  • Visual Basic .Net
  • Jscript
  • J#
ASP.Net framework helps in storing the information regarding the state of the application, which consists of:
  • Page state
  • Session state
The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state.

ASP.Net Environment Setup:

The key development tool for building ASP.Net applications and front ends is Visual Studio.
Visual Studio is an integrated development environment for writing, compiling and debugging the code. It provides a complete set of development tools for building ASP.Net web applications, web services, desktop applications and mobile applications.
When you start a new web site, ASP.NET provides the starting folders and files for the site, including two files for the first web form of the site.
The file named Default.aspx contains the HTML and asp code that defines the form, and the file named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for vb coding) contains the code in the language you have chosen and this code is responsible for the form's works.
A typical ASP.Net application consists of many items: the web content files (.aspx), source files (e.g., the .cs files), assemblies (e.g., the .dll files and .exe files), data source files (e.g., .mdb files), references, icons, user controls and miscellaneous other files and folders. All these files that make up the website are contained in a Solution.
Typically a project contains the following content files:
  • Page file (.aspx)
  • User control (.ascx)
  • Web service (.asmx)
  • Master page (.master)
  • Site map (.sitemap)
  • Website configuration file (.config)
The application is run by selecting either Start or Start Without Debugging from the Debug menu, or by pressing F5 or Ctrl-F5. The program is built i.e. the .exe or the .dll files are generated by selecting a command from the Build menu.

ASP.Net Life Cycle:

ASP.Net life cycle specifies, how:
  • ASP.Net processes pages to produce dynamic output
  • The application and its pages are instantiated and processed
  • ASP.Net compiles the pages dynamically
The ASP.Net life cycle could be divided into two groups:
  • Application Life Cycle: When user makes a request for accessing application resource, a page. Browser sends this request to the web server and it request passes through several stages before server response gets back.
  • Page Life Cycle: When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.

ASP.Net Example:

An ASP.Net page is also a server side file saved with the .aspx extension. It is modular in nature and can be divided into the following core sections:
  • Page directives
  • Code Section
  • Page Layout

Page directives:

The page directives set up the environments for the page to run. The @Page directive defines page-specific attributes used by the ASP.Net page parser and compiler. Page directives specify how the page should be processed, and which assumptions are to be taken about the page.
It allows importing namespaces, loading assemblies and registering new controls with custom tag names and namespace prefixes. We will discuss all of these concepts in due time.

Code Section:

The code section provides the handlers for the page and control events along with other functions required. We mentioned that, ASP.Net follows an object model. Now, these objects raises events when something happens on the user interface, like a user clicks a button or moves the cursor. How these events should be handled? That code is provided in the event handlers of the controls, which are nothing but functions bound to the controls.
The code section or the code behind file provides all these event handler routines, and other functions used by the developer. The page code could be precompiled and deployed in the form of a binary assembly.

Page Layout:

The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript and HTML tags:
The following code snippet provides a sample ASP.Net page explaining pafe directives, code section and page layout written in C#:
<!-- directives -->
<% @Page Language="C#" %>
 
<!-- code section -->
<script runat="server">
private void convertoupper(object sender, EventArgs e)
{
	string str = mytext.Value;
	changed_text.InnerHtml = str.ToUpper();
}
</script>
 
<!-- Layout -->
<html>
<head> <title> Change to Upper Case </title> </head>
<body>
<h3> Conversion to Upper Case </h3>
<form runat="server">
	<input runat="server" id="mytext" type="text" />
	<input runat="server" id="button1" type="submit" 
    value="Enter..." OnServerClick="convertoupper"/>
<hr />
<h3> Results: </h3>
<span runat="server" id="changed_text" />
</form>
</body>
</html>
Copy this file to the web server's root directory. Generally it is c:\inetput\wwwroot. Open the file from the browser to run it and it should generate following result:
ASP.NET First Example

Using Visual Studio IDE:

Let us develop the same example using Visual Studio IDE. Instead of typing the code, you can just drag the controls into the design view:
ASP.NET First Example 2
The content file is automatically developed. All you need to add is the Button1_Click routine, which is as follows:
protected void Button1_Click(object sender, EventArgs e)
{
     string buf = TextBox1.Text;
     changed_text.InnerHtml = buf.ToUpper();
}
The content file code is:
<%@ Page Language="C#" AutoEventWireup="true" 
                       CodeBehind="Default.aspx.cs" 
                       Inherits="firstexample._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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
      <asp:TextBox ID="TextBox1" runat="server" style="width:224px">
      </asp:TextBox>
      <br />
      <br />
      <asp:Button ID="Button1" runat="server" Text="Enter..." 
                  style="width:85px" onclick="Button1_Click" />
      <hr />
      <h3> Results: </h3>
      <span runat="server" id="changed_text" />
   </div>
   </form>
</body>
</html>
Run the example either from Debug menu, or by pressing Ctrl-F5 or by right clicking on the design view and choosing 'View in Browser' from the popup menu. This should generate following result:
ASP.NET First Example 3

Posted By MIrza Abdul Hannan7:19:00 pm

ASP.NET - Deployment

Filled under:

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

ASP.NET - Deployment

There are two categories of ASP.Net deployment:
  • Local deployment – in this case the entire application is contained within a virtual directory and all the contents and assemblies are contained within it and available to the application.
  • Global deployment – in this case, assemblies are available to every application running on the server.
There are different techniques used for deployment, however, we will discuss the following most common and easiest ways of deployment:
  • XCOPY deployment
  • Copying a Website
  • Creating a set up project

XCOPY Deployment:

XCOPY deployment means making recursive copies of all the files to the target folder on the target machine. You can use any of the commonly used techniques:
  • FTP transfer
  • Using Server Management tools providing replication on a remote site
  • MSI installer application
XCOPY deployment simply copies the application file to the production server and set a virtual directory there. You need to set a virtual directory using the Internet Information Manager Microsoft Management Consol (MMC snap-in).

Copying a Website:

The Copy Web Site option is available in Visual Studio. It is available from the Website --> Copy Web Site menu option. This menu items allows copying the current web site to another local or remote location. It is a sort of integrated FTP tool.
Using this option, you connect to the target destination, select the desired copy mode:
  • Overwrite
  • Source to Target Files
  • Sync UP Source And Target Projects
Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of deployment is done from Visual Studio environment. However, there are the following problems with both the above deployment methods:
  • You pass on your source code
  • There is no pre-compilation and related error checking for the files
  • The initail page load will be slow

Creating a Setup Project:

In this method you use Windows Installer and package your web applications so it is ready to deploy on the production server. Visual Studio allows you to build deployment packages. Let us test this on one of our existing project, say the data binding project.
Open the project and take the following steps:
Step (1): Select File -> Add-> New Project with the website root directory highlighted in the Solution Explorer.
Step (2): Select Setup and Deployement, under Other Project Types. Select Setup Wizard.
Select Setup Wizard
Step (3): Choosing the default location ensures that the set up project will be located in its own folder under the root directory of the site. Click on okay to get the first splash screen of the wizard.
splash screen Wizard
Step (4): The second screen asks to choose a project type. Select 'Create a setup for a web application'.
splash screen Wizard2
Step (5): Next, the third screen asks to choose project outputs from all the projects in the solution. Check the check box next to 'Content Files from...'
splash screen Wizard3
Step (6): The fourth screen allows including other files like ReadMe. However, in our case there is no such file. Click on finish.
splash screen Wizard4
Step (7): The final screen displays a summary of settings for the set up project.
splash screen Wizard5
Step (8): The Set up project is added to the Solution Explorer and the main design window shows a file system editor
splash screen Wizard6
Step (9): Next step is to build the setup project. Right–click on the project name in the Solution Explorer and select Build.
splash screen Wizard7
Step (10): When build is completed, you get the following message in the Output window:
splash screen Wizard8
Two files are created by the build process:
  • Setup.exe
  • Setup-databinding.msi
You need to copy these files to the server and double-clicking the setup file will cause the content of the .msi file to be installed on the local machine.

Posted By MIrza Abdul Hannan7:18:00 pm

ASP.NET - Configuration

Filled under:

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

ASP.NET - Configuration

The behaviour of an ASP.Net application is affected by different settings in the configuration files:
  • machine.config
  • web.config
The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file.
An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file.
If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner.
Any web.config file can locally extend, restrict or override any settings defined on the upper level.
Visual Studio generates a default web.config file for each project. An application can run without a web.config file, however, you cannot debug an application without a web.config file.
The following figure shows the Solution Explorer for the sample example used in the web services tutorial:
Solution Explorer-2
In this application there are two web.config files for two projects i.e., the web service and the web site calling the web service.
The web.config file has the configuration element as the root node. Information inside this element is grouped into two main areas: the configuration section-handler declaration area, and the configuration section settings area.
The following code snippet shows the basic syntax of a configuration file:
<configuration>
  <!-- Configuration section-handler declaration area. -->
  <configSections>
    <section name="section1" type="section1Handler" />
    <section name="section2" type="section2Handler" />
  </configSections>
  <!-- Configuration section settings area. -->
  <section1>
    <s1Setting1 attribute1="attr1" />
  </section1>
  <section2>
    <s2Setting1 attribute1="attr1" />
  </section2>
  <system.web>
    <authentication mode="Windows" />
  </system.web>
</configuration>

The Configuration Section Handler declarations:

The configuration section handlers are contained within the <configSections> tags. Each configuration handler specifies name of a configuration section, contained within the file, which provides some configuration data. It has the following basic syntax:
<configSections>
   <section />
   <sectionGroup />
   <remove />
   <clear/>
</configSections>
It has the following elements:
  • Clear - it removes all references to inherited sections and section groups.
  • Remove - it removes a reference to an inherited section and section group.
  • Section - it defines an association between a configuration section handler and a configuration element.
  • Section group - it defines an association between a configuration section handler and a configuration section.

The Application Settings:

The application settings allow storing application-wide name-value pairs for read-only access. For example, you can define a custom application setting as:
<configuration>
   <appSettings>
      <add key="Application Name" value="MyApplication" />
   </appSettings>
</configuration>
For example, you can store the name of a book and its ISBN number:
<configuration>
   <appSettings>
      <add key="appISBN" value="0-273-68726-3" />
      <add key="appBook" value="Corporate Finance" />
   </appSettings>
</configuration>

The Connection Strings:

The connection strings shows which database connection strings are available to the website. For example:
<connectionStrings>
   <add name="ASPDotNetStepByStepConnectionString" 
        connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
        Data Source=E:\\projects\datacaching\ /
        datacaching\App_Data\ASPDotNetStepByStep.mdb"
        providerName="System.Data.OleDb" />
   <add name="booksConnectionString" 
        connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\ \databinding\App_Data\books.mdb"
   providerName="System.Data.OleDb" />
</connectionStrings>

The System.Web Element:

The system.web element specifies the root element for the ASP.NET configuration section and contains configuration elements that configure ASP.NET Web applications and control how the applications behave.
It holds most of the configuration elements needed to be adjusted in common applications. The basic syntax for the element:
<system.web> 
   <anonymousIdentification> 
   <authentication> 
   <authorization> 
   <browserCaps> 
   <caching> 
   <clientTarget> 
   <compilation> 
   <customErrors> 
   <deployment> 
   <deviceFilters> 
   <globalization> 
   <healthMonitoring> 
   <hostingEnvironment> 
   <httpCookies> 
   <httpHandlers> 
   <httpModules> 
   <httpRuntime> 
   <identity> 
   <machineKey> 
   <membership> 
   <mobileControls> 
   <pages> 
   <processModel> 
   <profile> 
   <roleManager> 
   <securityPolicy> 
   <sessionPageState> 
   <sessionState> 
   <siteMap> 
   <trace> 
   <trust> 
   <urlMappings> 
   <webControls> 
   <webParts> 
   <webServices> 
   <xhtmlConformance> 
</system.web>
The following table provides brief description of some of common sub elements of the system.webelement:

anonymousIdentification:

This is required to identify users who are not authenticated when authorization is required.

authentication:

It configures the authentication support. Basic syntax:
<authentication mode="[Windows|Forms|Passport|None]"> 
   <forms>...</forms>
   <passport/>
</authentication>

authorization

It configures the authorization support.Basic syntax:
<authorization> 
   <allow .../>
   <deny .../>
</authorization>

caching:

Configures the cache settings.Basic syntax:
<caching>
   <cache>...</cache>
   <outputCache>...</outputCache>
   <outputCacheSettings>...</outputCacheSettings>
   <sqlCacheDependency>...</sqlCacheDependency>
</caching>

customErrors:

Defines custom error messages. Basic syntax:
<customErrors defaultRedirect="url" mode="On|Off|RemoteOnly">
     <error. . ./>
</customErrors>

deployment:

Defines configuration settings used for deployment. Basic syntax:
<deployment retail="true|false" />

hostingEnvironment:

Defines configuration settings for hosting environment.Basic syntax:
<hostingEnvironment 
    idleTimeout="HH:MM:SS" 
    shadowCopyBinAssemblies="true|false" 
    shutdownTimeout="number"
    urlMetadataSlidingExpiration="HH:MM:SS"
/>

identity:

Configures the identity of the application. Basic syntax:
<identity impersonate="true|false" 
          userName="domain\username"
          password="<secure password>"/>

machineKey:

Configures keys to use for encryption and decryption of Forms authentication cookie data.
It also allows configuring a validation key that performs message authentication checks on view-state data and Forms authentication tickets. Basic syntax:
<machineKey 
  validationKey="AutoGenerate,IsolateApps" [String]
  decryptionKey="AutoGenerate,IsolateApps" [String]
  validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | 
    HMACSHA384 | HMACSHA512 | alg:algorithm_name]
  decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
/>

membership:

This configures parameters of managing and authenticating user accounts.Basic syntax:
<membership
    defaultProvider="provider name"
    userIsOnlineTimeWindow="number of minutes"
    hashAlgorithmType="SHA1">
    <providers>...</providers>
</membership>

pages:

Provides page-specific configurations. Basic syntax:
<pages     
   asyncTimeout="number"
   autoEventWireup="[True|False]"
   buffer="[True|False]"
   clientIDMode="[AutoID|Predictable|Static]"
   compilationMode="[Always|Auto|Never]" 
   controlRenderingCompatibilityVersion="[3.5|4.0]"
   enableEventValidation="[True|False]"
   enableSessionState="[True|False|ReadOnly]"
   enableViewState="[True|False]"
   enableViewStateMac="[True|False]"
   maintainScrollPositionOnPostBack="[True|False]" 
   masterPageFile="file path" 
   maxPageStateFieldLength="number" 
   pageBaseType="typename, assembly"
   pageParserFilterType="string" 
   smartNavigation="[True|False]"
   styleSheetTheme="string"
   theme="string"
   userControlBaseType="typename"
   validateRequest="[True|False]"
   viewStateEncryptionMode="[Always|Auto|Never]" 
>
   <controls>...</controls>
   <namespaces>...</namespaces>
   <tagMapping>...</tagMapping>
   <ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>

profile:

Configures user profile parameters. Basic syntax:
<profile
    enabled="true|false"
    inherits="fully qualified type reference"
    automaticSaveEnabled="true|false"
    defaultProvider="provider name">
    <properties>...</properties>
    <providers>...</providers>
</profile>

roleManager:

Configures settings for user roles. Basic syntax:
<roleManager
    cacheRolesInCookie="true|false"
    cookieName="name"
    cookiePath="/"
    cookieProtection="All|Encryption|Validation|None"
    cookieRequireSSL="true|false "
    cookieSlidingExpiration="true|false "
    cookieTimeout="number of minutes"
    createPersistentCookie="true|false"
    defaultProvider="provider name"
    domain="cookie domain">
    enabled="true|false"
    maxCachedResults="maximum number of role names cached"
    <providers>...</providers>
</roleManager>

securityPolicy:

Configures the security policy. Basic syntax:
<securityPolicy>
   <trustLevel />
</securityPolicy>

urlMappings:

Defines the mappings for hiding the actual URL and providing a more user friendly URL. Basic syntax:
<urlMappings enabled="true|false">
    <add.../>
    <clear />
    <remove.../>
</urlMappings>

webControls:

It provides the name of shared location for client scipts. Basic syntax:
<webControls clientScriptsLocation="String" />

webServices:

This configures the web services.

Posted By MIrza Abdul Hannan7:17:00 pm