Home
Home Page
And again about functional programming on Python
Where the Python has come crawling?
Practical application OOP in PHP5
Functional programming in language Python
Approaches of language Python - an amusing example of optimization
Use ext/mysqli: Part I - the Review and the prepared expressions
How to receive the maximal result from registration in catalogues
XML-RPC In language Python
The API-specification of databases of language Python, version 2.0
Programming of the Web-client in language Python
Useful advice for job with XML
Future Web - behind semantics
Whether it is necessary to cancel spaces of names XML?
Use AJAX in ASP.NET
ASP .NET 2.0: Reference pages
Patterns of registration
What is ASP.NET. Installation and the test project.
Anatomy ASP.NET. ASP.NET in operation.
Server elements of management Continuation.
Links
 
topic


Anatomy ASP.NET. ASP.NET in operation.

Introduction


ASP.NET - one of components .NET Framework. We list briefly basic features of this technology.


* Nontechnical executive CLR environment

* Library of classes .NET Framework

* Languages. NET (C *, VB.NET, J * and others)

* ADO.NET

* ASP.NET

* Web-services

* Intermediate language MSIL (Microsoft Intermediate Language). It is the assembler for Wednesday of performance CLR.


ADO.NET - a set of the classes intended for access to databases Microsoft SQL Server, to sources of data OLEDB and to files XML.


Different parts of your project can be written in different languages, it is called interoperability. We shall try to write the project where one of pages will be on Visual Basic, and another on With *.


Kompjuternye languages are kompiliruemymi and interpretive. During compilation of the program written on kompiliruemom language, the carried out file (In Windows - exe) is created. He is carried out quickly, but cannot be executed on other platform. The machine on which she is carried out, should have a similar configuration. For example, if the program uses dll this library should be established and by the target machine. Interpretive programs are compiled at the moment of performance, therefore they work more slowly, but do not depend on the concrete machine. V. NET Framework compilation is applied dvukhehtapnaja, that is the first stage is a compilation in MSIL, and the second - compilation "Just-in-time" the compiler during execution{performance}. The JIT-compiler optimizes a code for that machine on which he is executed. In ASP.NET page is compiled in MSIL at the first reference{manipulation} of the client to page. Together with her classes which she uses are compiled. If you use Visual Studio 2005, it is possible to not expect the first search, and compulsorily to compile all pages of your project. It will allow to reveal syntactic and other mistakes.


MSIL is an assembler, not dependent on the machine. He can be carried out by any machine where it is established CLR. Project Mono tries to transfer CLR on other platforms, allowing to cooperate to the servers working on different platforms.


You can familiarize with the project on a site http://mono-project.com


On page http://go-mono.com/archive/xsp-0.10.html is XSP - the server ASP.NET which can serve as expansion of Apache server - the preferred server *nix - systems.



As works ASP.NET


When we istalliruem .NET, in sootvetsvujuhhikh directories C:WINDOWSMicrosoft. NETFramework the file aspnet_isapi.dll is located also. It - ISAPI-expansion, also is intended it for reception of the searches addressed to ASP.NET-applications (*.aspx *.asmx, etc.), and also creations of working processes aspnet_wp.exe, obratyvajuhhikh searches. The Internet - server - IIS either built - in in WebMatrix or built - in in Visual Studio Cassini - use this expansion when they should process the reference{manipulation} to pages with expansion aspx.


This module assorts (parse) contents of pages aspx together with a file of the separated code and generates a class in language of page with object Page. The page aspx differs from usual HTML-page presence of server elements of management which are described special tegami. For understanding of job ASP.NET it is important to note, that to everyone tegu an element of management there corresponds{meets} the member of a class of page. For example,



<asp:Label ID = "Label1" runat = "server"> </asp:Label>


It will be transformed in



__ ctrl = new global:: System. Web. UI.WebControls. Label ();


The primary goal of object Page - a parcel{sending} a HTML-code in a target stream. This class is compiled in library .dll which is loaded into process of the web - server. The subsequent searches to page also processes dll if the initial code of page does not vary. All these files can be found in a directory « Temporary ASP.NET Files » the current version .NET. If we work in the environment of development Visual Studio 2005 or VWD, for each project the subdirectory is created.



Types of pages and folders of the project


In the project it is possible to add new files through dialogue New File. If to remove{take off} a mark from a tag ” Place code in separate file “, Visual Studio will create one file in which will be both page, and a code for its{her} processing (in style WebMatrix).


All files are located in a directory of the project. And on the contrary, all files which will be placed in a directory of the project, become his{its} part. For websites there is no special file .csproj in which his{its} components as it was in previous versions Visual Studio would be listed{transferred}. The structure of the decision (solution) is described in a text file .sln. The decision can include some websites and libraries.


In ASP.NET 2.0 there are special subdirectories of the project for different types of files. For example, shared classes, text files are stored{kept} in folder App_Code and some other (DataSet, the diagram of classes). Files with expansions .cs or .vb, got there, are automatically compiled, when any page of the project is requested. In App_Data sources of the data used in the project - databases Access and Microsoft SQL, XML-files contain. It is impossible to get access to this directory from the outside, but only from the application. Subjects of the project are stored{kept} in folder Themes (lecture 13). Application by that allows to adjust uniform appearance of a site and on-line him{it} to operate. In App_GlobalResources there are resources, for example tables of lines which can be created in different languages. Language of resources gets out automatically depending on adjustments of a browser of the user. In folder App_WebReferences there are links to used webs - services.


It is possible to create own subdirectories of the project, for example, for storage of pictures.



The project in 2 languages


The project of a Web-site will consist of pages aspx and classes which are used on pages (and, certainly, various resources). Files with classes to which it is possible to address from different pages, place in special folder App_Code. At compilation they are located in one assembly - library .dll in a format portable executable. completely never mind, in what language the class if it is language .NET is written.


The ready compiled assembly of foreign manufacturers too can be used in the project. Them place in folder Bin. Thus they are necessary for importing to the project.



<% Import Namespace = "MyCustomNamespace" %>


Create the new project. Add in him{it} a file, having chosen type of file Class and language Visual Basic. Environment{Wednesday} itself will suggest to place it{him} in folder Code. We shall name it{him} CustomClass. He{it} will have very simple code. Only one function which adds word Hello to a name transferred{handed} as parameter.



Imports Microsoft. VisualBasic

  Public Class CustomClass

      Public Function GetMessage (ByVal name As String) As String

          Return "Hello", and name

      End Function

  End Class


Add in the project page CodeFolder_cs.aspx. It is page it is written on C *, but she creates a class written on VB.NET.



<% page language = " C * " %>

  <script runat = "server">

    void Button1_Click (object sender, EventArgs e)

    {

      CustomClass c = new CustomClass ();

      Label1. Text = c. GetMessage (TextBox1. Text);

}

  </script>

  <html>

  <head>

      <title> ASP.NET Inline Pages </title>

  </head>

  <body>

      <form id = "Form1" runat = "server">

        <h1> Welcome to ASP.NET 2.0! </h1>

        <b> Enter Your Name: </b>

        <asp:TextBox ID = "TextBox1" Runat = "server"/>

        <asp:Button ID = "Button1" Text = " Click Me " OnClick = "Button1_Click" Runat = "server"/>

        <br/>

        <br/>

        <asp:Label ID = "Label1" Text = "Hello" Runat = "server"/>

      </form>

  </body>

  </html>


On page the form reminding the form of the Windows-application is determined. On her there is a button, pressing on which is processed in function Button1_Click. In her the class is created and his{its} function GetMessage with parameter which undertakes from an element of editing is caused. Returned value enters the name in element Label1. In more simple variant it looks so:



Label1. Text = "Hello" +TextBox1. Text;


The class can be written on C *, and be used from page on Visual Basic.



using System;

  public class CustomClass2

  {

      public String GetMessage (String input) {

          return " Hello from C * " + input;

}

}

   Code of page CodeFolder_vb.aspx:

  <script runat = "server">

    Sub Button1_Click (ByVal sender As Object, ByVal e As System. EventArgs)

      Dim c As New CustomClass2

      Label1. Text = c. GetMessage (TextBox1. Text)

    End Sub

  </script>


However to place in directory App_Code it is possible only in one language. If will be there files in different languages, the project will not be compiled. To use two languages, it is necessary to create a subdirectory, to add her{it} in a file web.config and to place in it{her} files in the other language.


Registration in a file web.config:



<configuration>

  <system.web>

    ...

    <compilation>

      <codeSubDirectories>

        <add directoryName = "VBCode"/>

      </codeSubDirectories>

      <codeSubDirectories>

        <add directoryName = "CSCode"/>

      </codeSubDirectories>

    </compilation>

    ...

  </system.web>

</configuration>



Directives


On each page aspx directives with which help you can supervise behaviour of page are usually set. It is possible to count their language with which you communicate with the compiler, specifying to him how to process the given page. Directives usually place in the beginning of a file. We already met Page directive in the first lecture.


Sintaskis announcements of directives such:



<% [Directive] [Attribute=Value] %>


It is possible to declare some directives simultaneously:



<% [Directive] [Attribute=Value] [Attribute=Value] %>


In ASP.NET 2.0 there are 11 directives.

The directive Attributes the Description

@Assembly Name

Src Imports on page or to an element of management assembly with the set name

@Control same as at Page It is applied to the task of properties at creation of own user elements of management.

@Implements Interface Specifies, that the class of the given page realizes the given interface

@Import Namespace Imports space of names

@Master same as at Page It is applied on pages of a pattern of design (Master page). New in ASP.NET 2.0

@MasterType TypeName

VirtualPath Gives strictly typified link to a class contained in a pattern of design. Allows to address to properties of this class.

@OutputCache Duration

Location

VaryByCustom

VaryByHeader

VaryByParam

VaryByControl Operates caching of page or an element of management. It is more in detail described in lecture 15.

@Page the Attributes concerning to the given page are See lower. It is used only in files with expansion aspx

@PreviousPageType TypeName

VirtualPath Page from which the data entered by the user have been sent. New in ASP.NET 2.0. Before page sent a post only to itself.

@Reference Page

Control Page or an element of management which needs to be compiled together with given

@Register Assembly

Namespace

Src

TagName

TagPrefix Creates pseudonyms for spaces of names and the user elements of management


Meanwhile we shall in detail consider 2 of them - Page and Import.



Page directive


Page directive allows to establish properties of page which will be used during compilation. This directive is used more often than the others, therefore she{it} is necessary for considering in more detail.


The most important attributes of the directive are listed in the table:


AutoEventWireup         Automatic processing events of page

Buffer         Operates buffering of page. By default buferizuetsja

ClassName         Allows to appoint a classname, generated the given page

CodeFile         The name of a file with the separated code for the given page

Culture         Establishes a set of regional parameters, i.e. language, a format of currency, date, numbers

Debug         If true, on page the debugging information is deduced

Trace         A conclusion of the route-making information

EnableViewState         Preservation of a status of page. By default she is saved

EnableTheming         Allows to switch on or off support of registration by that. It is by default switched on

Inherits         A class from which the class of the given page in technology of the separated code is inherited

IsAsync         Shows, whether the page asynchronously is processed.

Language         The language used in the introduced code

WarningLevel         The greatest allowable level of preventions{warnings} of the compiler

CompilerOptions         Options of the compiler



Spaces of names of library of classes


The library of classes FCL contains thousand classes. For convenience of use they are incorporated into spaces of names. To address to the classes declared in space of names, without the instruction{indication} of a full way, it{he} needs to be imported to the project. If you want to work with files of format XML, you need to import space of names System. XML. In pages of the separated code on C * using directive, as always, is used.



using System. XML;


On page aspx - Import directive



<% Import Namespace = " System. XML " %>


For each space of names separate Import directive is required.


Visual Studio.NET and VWD by default include in page on C * most often used spaces of names. On page aspx to import these spaces of names it is not required.



using System;

  using System. Data;

  using System. Configuration;

  using System. Collections;

  using System. Web;

  using System. Web. Security;

  using System. Web. UI;

  using System. Web. UI.WebControls;

  using System. Web. UI.WebControls. WebParts;

  using System. Web. UI.HtmlControls;


For example, in space of names System. Web. UI there is class Page without which there can not be no page ASP.NET, in System. Web - HttpRequest and HttpResponse.



The browser of classes


How to learn{find out}, what classes are available in library of classes .NET? For this purpose it is intended Object Browser (Visual Studio 2005) and Class Browser WebMatrix. To open Object Browser in Visual Studio 2005 or VWD Express, choose item{point} of menu View-> Object Browser. If you use WebMatrix Class Browser is in the same folder of menu Windows, as WebMatrix - All Programs-> ASP.NET WebMatrix. In a format ASP.NET Class Browser it is switched on in structure Framework SDK.


All available spaces of names are shown as sites of treelike structure. Us interests System. Web. Open this site. Inside there were other spaces of names. Open System. Web. UI. There there is a plenty of classes, interfaces, delegates, transfers. They can be learned{be found out} on icons. For example, the icon of the delegate is similar to a suitcase.

Choose class Page. In okoshke the list of his{its} methods, fields and events on the right will appear. If to choose a method, in the third window under the second his{its} description will appear. Inside a class there are two more folders - classes - primogenitors (Base Classes) and classes - descendants. All too can be seen{overlooked} them. Object Browser shows also classes of the current project. If classes zakommentirovan tegami generation of documentation XML this information too is visible, for example Summary, Parameters, Values, Returns.


Investigating property IsPostBack, it is possible to learn{find out}, that it has bulevskoe value, and is intended only for reading.



Check of conformity to standards


There are different standards HTML and XHTML. Later standards show more strict requirements, for example, XHTML 1.1 does not allow to use <br> and others simple tegami without closing slehsha <br/>. At the same time old standards do not support new tegi.


In heading of HTTP-search the standard of the document is underlined, Visual Studio 2005 in all pages specifies the following standard:



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


This standard demands presence of attribute xmlns in tege <html> - the link to a site with the description of the standard.



<html xmlns = " http: // www.w3.org/1999/xhtml ">


Many pages made for the previous versions ASP.NET, have no such attribute. In the panel instumentov Html Source Editing also there is a dropping out list in which it is possible to choose the standard or the version a browser for which the given page is intended. The page is automatically checked on conformity to this standard.

Properties of page


The page is a basis of all in the Web-application.


Class System. Web. UI.Page inkapsuliruet the functionality necessary for creation and processing of pages ASP.NET.


Each page ASP.NET is an object of a class which is automatically generated by a nucleus ASP.NET. The class is inherited from the class associated with page if we use the separated code, or directly inherited from System. Web. UI.Page if the code on C * is built - in page. Environment{Wednesday} also creates the designer by default.


To be convinced of it, we can create page "PageType.aspx":



<% Page Language = " C * " %>

  <html xmlns = " http: // www.w3.org/1999/xhtml ">

  <head runat = "server">

      <title> Type of page </title>

  </head>

  <body>

      <div>

      <% Response. Output. Write (" Type of the given page {0} ", this. GetType ()); %>

      </div>

       <div>

      <% Response. Output. Write (" Base type of the given page {0} ", this. GetType () .BaseType); %>

      </div>

  </body>

  </html>


Result:


Type of given page ASP.pagetype_aspx

Base type of given page System. Web. UI.Page



The same page created on technology of division of a code.



<% Page Language = " C * " AutoEventWireup = "true" CodeFile = "PageType.aspx.cs" Inherits = "PageType" %>


Writes result


Type of given page ASP.pagetype_aspx

Base type of given page PageType



That PageType - successor System. Web. UI.Page, is registered in a file of the separated code:



public partial class PageType: System. Web. UI.Page


To the current object of page it is possible to address as to variable Page. Page is a container of elements of management of the given page, therefore comprises collection Controls. If in tege <head> there is an attribute runat = "server" in Page field Header through which can be operated the heading of page contains also. For example, to change the name to page in heading of a browser, to appoint a file of cascade tables of styles.



<script runat = "server">

      protected void Page_Init (object sender, EventArgs e)

      {    

          HtmlLink myHtmlLink = new HtmlLink ();

          myHtmlLink. Href = "printable.css";

          myHtmlLink. Attributes. Add ("rel", "stylesheet");

          myHtmlLink. Attributes. Add ("type", "text/css");

          Page. Header. Controls. Add (myHtmlLink);

          Page. Header. Title = " New heading ";

}

      protected void Page_Load (object sender, System. EventArgs e)

      {

          Style bodyStyle = new Style ();

          bodyStyle. ForeColor = System. Drawing. Color. Blue;

          bodyStyle. BackColor = System. Drawing. Color. Beige;

          Page. Header. StyleSheet. CreateStyleRule (bodyStyle, null, "p");

}

  </script>

  <html xmlns = " http: // www.w3.org/1999/xhtml ">

  <head runat = "server">

      <title> Hello ASP.NET </title>

  </head>

  <body>

        <p> Study to program on ASP.NET </p>

  </body>

  </html>


In this example we have changed the text of heading. Start this page. In the turned out HTML-code inside tega <title> costs{stands} any more « Untitled Page », and « the New heading » which has been established through Page. Header. Title. has been created style for tega <p>, that was reflected thus:



<style type = "text/css">

        p {color:Blue; background-color:Beige;}

  </style>


External page CSS has been imported from a file.



<link href = "printable.css" rel = "stylesheet" type = "text/css"/> <style type = "text/css">


If attribute AutoEventWireup which is present at heading of the pages generated VS, is established, methods with prefix Page_ automatic are appointed obrabotchikami events of page.


The page has two important properties - Response and Request. Property Response has type HttpResponse. Response of page it is possible to perceive as a target stream. All HTML the code of generated page basically can be deduced{removed} through recording in this stream. It was usual mode of work of developers asp. But in ASP.NET there are more convenient means of a conclusion of the data with the help of server elements of management. Response it is better to use for recording Cookies, for the task of various parameters of heading - to operate caching, property Expires.


Example from MSDN:



HttpCookie MyCookie = new HttpCookie ("LastVisit");

      DateTime now = DateTime. Now;

      MyCookie. Value = now. ToString ();

      MyCookie. Expires = now. AddHours (1);

      Response. Cookies. Add (MyCookie);


It is possible to change the codepage.



<head runat = "server">

  <%Response. Charset = "windows-1251"; %>

      <title> Russian coding </title>

  </head>


Function Response. Redirect perenapravljaet a browser on other page.



Response. Redirect (" NavigationTarget.aspx? name = " + System. Web. HttpUtility. UrlEncode (Name. Text);


Here the command line with parameters QueryString which the target page can read is formed.


Property Request is similar is the search transferred{handed} on the server for a conclusion of the necessary page. He has type HttpRequest. All is stored{kept} in him about the client, including adjustments of his{its} browser, files - cookie and the data entered by him{it} in the form.



NameLabel. Text = Server. HtmlEncode (Request. QueryString ["Name"]);



Events of page


Job of environment{Wednesday} ASP.NET with page begins with reception and processing by IIS Web-server of search to the given page and transfers of this search to the environment of performance ASP.NET. The environment of performance analyzes, whether it is necessary to compile page or possible to give out as the answer page from a cache.


Then life cycle of page begins. He begins with stage PreInit. After reception of search the environment of performance loads a class of caused page, establishes properties of a class of page, builds a tree of elements, fills in properties Request and Response and properties UICulture and causes method IHttpHandler. ProcessRequest. After that the environment of performance checks, how this page and if the page is called by data transfer from other page about what it will be told further the environment of performance establishes property PreviousPage has been called.


At this stage property IsPostback of object Page which allows to learn{find out} is established also, whether the form is loaded into first time or she should be formed as result of the data processing, entered by the user.


In obrabotchikakh events of page it is possible to check up this property:



if (! Page. IsPostBack)

      {

          // To process

}


Further there is an initialization of page - event Init. In time of initialization of page affiliated user elements of management and by him{it} ustanovlivajutsja properties id are created. During same time to page subjects of registration are applied. If the page is called in result postbehka at this stage the data sent on the server, are not loaded yet in properties of elements of management. The programmer can initialize their properties.


Loading. During event Load properties of elements of management are established on the basis of the information on a status if the page is created as a result of sending the data of the form.


If on page exist validatory (classes of check of the data, see lecture 5), for them method Validate is caused (). Then are caused obrabotchiki events (provided that the page is generated in reply to action of the user).


In method Render the HTML-code of deduced{removed} page is generated. Thus the page causes corresponding methods of affiliated elements, those - methods of the affiliated elements. In method Render the code is deduced in Response. OutputStream. The page too is considered an element of management - class Page is the successor of class Control. If on page there are blocks of display, they become a part of function otrisovki (rendering).


At last, the page is unloaded from memory of the server and there is event Unload.


During life cycle of page there are various events. It is possible to switch on trace of page to see the order from occurrence.



<% Page Language = " C * " Trace = "true" TraceMode = "SortByTime" %>


During trace event Unload because it occurs when all code is already deduced{removed} is not deduced. During processing this event it is necessary to release{exempt} resources, for example connections with databases or open files.


The full list of events of page which can be redefined in a class of page:


* PreInit

* Init

* InitComplete

* PreLoad

* Load

* LoadComplete

* PreRender

* PreRenderComplete

* Unload


For all events are determined obrabotchiki - virtual functions OnInit, OnLoad. When AutoEventWireup it is equal true, functions - obrabotchiki of events automatically appear in a class with prefix Page - Page_Load, Page_Init and so on. One of the most popular events is Page_Load. Creating new page, Visual Studio creates obrabotchik this event. Here it is possible to change appearance of elements and to create new. It is possible to establish AutoEventWireup in false. In that case it is necessary to write the overloaded versions of virtual functions.



protected override void OnInit (EventArgs e)

  {

}


So it is possible to achieve acceleration of job of page.

Ways of introduction of a code ASP.NET in page.


There are three ways to introduce a code in program language in page aspx.


The block <script runat = "server"> </script> is called as the block of the announcement of a code.


Teg <script> it is similar to by what scripts JavaScript are entered. But with the big difference - the script is carried out on the server. Therefore it is necessary to set attribute runat = "server". The attribute language at him{it} can accept values With *, VB, J *. In pages with the separated code it is possible to write and on C ++. Value of language Visual Basic by default is accepted, therefore it is not necessary to overlook to specify language when write on With *. But there is no necessity it to do{make}, if language is determined in Page directive. It is possible to write in different languages in one application, but it is impossible to mix different languages on one page.


Inside the block it is possible to declare variables, constants and functions. Actually in C * there are no global variables so it there will be members of a class of page. But they look global because the class is not described by the programmer, it{him} generates ASP.NET. We shall name therefore their variables of page.


Here it is possible to redefine virtual methods of a class of page. In the block also it is possible to declare classes, but they will be internal in relation to a class of page.



Blocks of display


Any code introduced with the help <of % and %>, is processed during event Render as a part of page.


In a body of the block <% of %> is allowable to declare variables then they will be local for that method in which the given block will be realized, but it is impossible to declare methods or types.


Such style of programming was characteristic for asp. More often in blocks of display the HTML-code with help Response. Write is deduced.



<% = someExpr %> is reduction <% Response. Write (someExpr) %>.


  <html>

  <head>

  </head>

  <body>

  1 Line HTML <br/>

  <% Response. Write (" 1 Line ASP.NET <br/> "); %>

  2 Line HTML <br/>

  <% Response. Write (" 2 Line ASP.NET <br/> "); %>

  3 Line HTML <br/>

  <% = " 3 Line ASP.NET <br/> "; %>

  </body>

  </html>


More modern way - use of server elements of management. They are described in a body of page is similar to usual elements of a marking, are members of a class of page. To them the reference{manipulation} through the identifier is possible. For example, instead of deducing{removing} the text through Response. Write, it is possible to establish the text of an element of management, as in an example from the first lecture.


The object of any class is created with the help of syntax « teg object »



<object id = "items" class = " System. Collections. ArrayList " runat = "server"/>


It is equivalent to the description in a class of page of a field



System. Collections. ArrayList items;


One more way is applied to linkage with sources of the data and will be considered in 7 lectures.



The conclusion


The technology ASP.NET is constructed on the object-oriented sobytijno-controlled approach to creation of web-page. The classes used for generation of web-pages, are a part of library .NET Frameworks. For many of them there are analogues in Windows Forms, that pulls together programming desktop applications with programming web-applications.