+ All Categories
Home > Documents > A Guide to Dotnet

A Guide to Dotnet

Date post: 30-May-2018
Category:
Upload: hari-kishan-reddy
View: 226 times
Download: 0 times
Share this document with a friend

of 29

Transcript
  • 8/14/2019 A Guide to Dotnet

    1/29

    A Guide to .net

    Introduction to .NET Framework

    You can make use .Net Framework as a development environmentor a platform for developing user friendly web-based applicationsthat can allow seamless access by users from any where in theworld and from any type of client machines. You can apply theopen standards such as XML (eXtensible Markup Language), SOAP(Simple Object Access Protocol) and HTTP (HyperText TransferProtocol) for developing your web-applications and webapplications created with such open standards can interact wellwith other applications of other platforms.

    You can use different programming languages such as C#,VBScript, VB.NET, Managed C++ for developing your applicationsin .NET Framework, as the .NET Framework is not dependent onone particular language or platform and can support many kindsof platforms and programming languages that are in use today.Further, you can use .NET Framework for running yourapplications in almost all platforms such as Linux, Macintosh andUnix without any hitches.

    The presence of many off-the-shelf libraries in .NET Frameworkcan assist you in developing your applications in a faster, cheaperand easier manner. The most recent .Net Framework version iscapable of supporting over 20 different programming languagestoday.

    The functionality of .Net Framework supporting manyprogramming languages is due to the use of the powerful CLR,the Common Language Runtime engine. The applicationprogramming codes are first compiled by CLR into a Microsoft

    Intermediate Language (MSIL) code instead of native codes andthe MSIL, which is nothing but an instruction set, in turn createsthe native code for running the application.

    The main advantage of language and platform independentfeature of .NET Framework can be attributed to CLR and the sameCLR also takes care of run-time services such as memory

    1

  • 8/14/2019 A Guide to Dotnet

    2/29

    processes, security enforcement, integration of language, andthread management. Hence, you can make use of the variousinfrastructures that have been provided in .NET Framework forcreating your web-applications.

    As per the classification by the Microsoft, there are two categoriesof .NET Framework and they are CLR and .Net Framework classlibrary.

    Common Language Runtime: The CLR is responsible for providinga common runtime environment or services with which all .NETapplications can run. Further, the various capabilities of CLR canenable any developer to write even big applications with easeusing the features such as strong type naming, life-cycle

    management, dynamic binding that is capable of making anybusiness logic into re-usable component and finally the cross-language exception handling.

    .Net Framework class library: This class library constitutes variouspredefined functional sets that are very useful while developingthe applications by developers. There are three main componentsin this class library and they are:

    ASP.NET.

    Windows Forms. ADO.NET.

    With the .Net Framework you can make your codes written infewer lines and other favourable features such as easy websettings, easy deployment of applications, easy compilationprocedures, easy Web configuration makes the .NET Framework agreat platform to work with. In an overall scenario, the developerswill be able to concentrate more on Web controls and spend an

    efficient time in application design and implementation and tohave an effective control over the flow of the applicationsequence.

    Another great feature that any developer can take note of is thefeature of .NET Framework taking into cognisance all the Webcontrols, server-side blocks of codes and Web forms and getting

    2

  • 8/14/2019 A Guide to Dotnet

    3/29

    them compiled whenever a call for the page compilation iscompleted.

    Once the components of .NET framework are compiled in yourmachine, the compiled version can easily be uploaded with all therelevant pages in the /bin directory of the system. The process ofuploading is very easy when compared to the complicatedprocess of web-application in ASP, where in you have to firstupload the application pages with the relevant components andyou also need to register them with the operating system.

    In .NET Framework the simple uploading in /bin directory of theoperating system is enough and you need not carry out thecomplicated process of registering the components of web-

    application with the operating system.

    With the help of an XML based web.config file you can carry outthe web settings which is nothing but configuring the .NETapplications for successful running. The XML based web.config filecan be modified through a program and when any suchmodification is done, the system recognises the change andregisters it immediately that makes configuration of .NETapplications easy and quick.

    Caching is a process or a method with which the most commonlyand frequently used resources and data will get loaded onto thememory for easy and fast access. There are three types ofcaching in .Net Framework and they are output caching, datacaching, and fragment caching.

    Understanding Globalization in .NET

    Globalization refers to the process with which an application or

    software will be designed and developed so as to make it runacross all platforms and all sites with minimum or no modificationto the software application. The software is very amenable tocustomisation so as to suit to the location-specific conditions andit is also capable of providing information based on the variedinputs and the location-specific operating system.

    3

  • 8/14/2019 A Guide to Dotnet

    4/29

    Under any normal circumstance, there will be two processes inGlobalization and they are customisation or localisation of theapplication and internationalizing the application codes so as tomeet the standards of the local culture and other related matters.

    In internationalization process the application code base will besame and the efforts will be on jobs such as translating, storing,retrieving and to make the application user friendly for theselected locale. In any given place the culture and the languagewill always be different and besides this you should also take intoaccount the other factors such as time zone, normal date patternusage, cultural and language environments, currencies, telephonenumbers, and so many other factors that are specific to thelocale.

    In globalization the process of internationalization enables you toremove from the code base and the presentation layer all thecontents and make you to use only a single presentation layerand single code base with a common contents that can suit anyculture. The internationalization process will aid you to keep allthe contents in a common place with an idea of making it easilyaccessible by the programme codes and the results can easily bepopulated all over presentation layer and the application with

    ease and efficiently.In addition to the above, the internationalization process alsoenables you to store the contents and all the collected inputs fromthe user in a user friendly format and in a highly secured mannerwithout compromising any standards pertaining to the localculture. The internationalization process is one step before anyattempt for localising the application to suit to the local needs.

    With the help of the localization process of globalization, you can

    make your application adaptable to the various location specificconditions and it will be easy for you to translate and re-formatyour application to suit to your new location and that too withoutchanging any of the codes. Further, you can make use of theprocess for rectifying any of the reported bugs and for fine tuningthe application for running smoothly without any hitch.

    4

  • 8/14/2019 A Guide to Dotnet

    5/29

    The globalization process also makes use of the locally prevailinginformation on culture where the software or the application is tobe installed and maintained. The locational details and thelanguage used in that particular area constitute to culture

    information and for working with any culture based informationthe namespace concept is utilised and the SystemGlobalization,SystemResources and SystemThreading are the availablenamespaces in .NET Framework.

    Out of the various namespaces, the SystemGlobalizationnamespace constitute classes that are used to hold informationrelating to region or country, the local language used, type ofcalendars, date format used, numbers, currency, etc., all in ameticulously arranged fashion and all these classes are used

    while developing the globalized (internationalized) applications.

    You can use advanced globalization functionalities with theassistance of classes such as StringInfo and TextInfo classes andthe various functionalities include text element processing andsurrogate support systems.

    The SystemResources namespace constitutes interfaces andclasses that are very helpful for developers and maintenanceexperts in creating, storing, retrieving, and managing variousresources used in the application that are culture and location-specific.

    The SystemThreading namespace constitutes interfaces andclasses that aid in multithreaded programming. The classes thatare used in this type of SystemThreading namespace are alsouseful in accessing data and for synchronization of threadactivities.

    About Just in time (JIT) compiler in .NET

    The high level programming languages that need to be compiledrequire a runtime, so that the architecture on which the languageruns is provided with details on how to execute its code. All theprogramming languages use its corresponding runtime to run theapplication. For example, to run an application developed using

    5

  • 8/14/2019 A Guide to Dotnet

    6/29

    Visual Basic, the computer on which the application will be runmust be installed with the Visual Basic runtime. The Visual Basicruntime can run only the applications developed with Visual Basicand not the ones developed with any other programming

    language like Java.In the .NET Framework, all the Microsoft .NET languages use acommon language runtime, which solves the problem of installingseparate runtime for each of the programming languages.Microsoft .NET Common Language Runtime installed on acomputer can run any language that is Microsoft .NET compatible.

    The main advantage of the .NET Framework is the interoperabilitybetween different languages. As all the Microsoft .NET languages

    share the same common runtime language, they all work welltogether. For example, you can use an object written in C# fromVisual Basic.NET. The same applies for all the other Microsoft .NETlanguages.

    When you compile a Microsoft.NET language, the compliergenerates code written in the Microsoft Intermediate Language(MSIL). MSIL is a set of instructions that can quickly be translatedinto native code.

    A Microsoft.NET application can be run only after the MSIL code istranslated into native machine code. In .NET Framework, theintermediate language is complied "just in time" (JIT) into nativecode when the application or component is run instead ofcompiling the application at development time. The Microsoft.NETruntime consists of two JIT compilers. They are standard JITcompiler and the EconoJIT compiler. The EconoJIT compilercompiles faster than the standard JIT compiler, but the code itproduces is not as optimized as the code obtained from the

    standard JIT compiler.

    About ASP.NET Assemblies in .Net

    An assembly in ASP.NET is a collection of single-file or multiplefiles. The assembly that has more than one file contains either adynamic link library (DLL) or an EXE file. The assembly also

    6

  • 8/14/2019 A Guide to Dotnet

    7/29

    contains metadata that is known as assembly manifest. Theassembly manifest contains data about the versioningrequirements of the assembly, author name of the assembly, thesecurity requirements that the assembly requires to run, and the

    various files that form part of the assembly. The biggest advantage of using ASP.NET Assemblies is thatdevelopers can create applications without interfering with otherapplications on the system. When the developer creates anapplication that requires an assembly that assembly will not affectother applications. The assembly used for one application is notapplied to another application. However one assembly can beshared with other applications. In this case the assembly has tobe placed in the bin directory of the application that uses it.

    This is in contrast to DLL in the past. Earlier developers used toshare libraries of code through DLL. To use the DLL that isdeveloped by another developer for another application, you haveto register that DLL in your machine. In ASP.NET, the assembly iscreated by default whenever you build a DLL. You can check thedetails of the manifest of the assembly by using classes located inthe System.Reflection namespace.

    Thus you can create two types of ASP.NET Assemblies in ASP.NET:private ASP.NET Assemblies and shared assemblies. PrivateASP.NET Assemblies are created whey you build component fileslike DLLs that can be applied to one application. Shared ASP.NETAssemblies are created when you want to share the componentfiles across multiple applications. Shared ASP.NET Assembliesmust have a unique name and must be placed in Global AssemblyCache (GAC). The GAC is located in the Assembly directory inWinNT. You can view both the manifest and the IL usingILDisassembler (ildasm.exe).

    .NET Assemblies - I

    This article is going to be based on three parts.

    1. In the first part we will be discussing the 3-tier architecture.

    7

  • 8/14/2019 A Guide to Dotnet

    8/29

    2. In part-II of this article we will see what the .NET assembliesare and

    3. In the last part we will be practically implementing a simple.NET assembly.

    Part-I :: The Three-Tier Architecture

    A 3-tier architecture defines the division of a web basedapplication into three layers. When we say 3-tier architecture, weare actually meaning the number of nodes (or computers) thatare involved within the communication. Let's first of all see whatdo I mean when I say a 3-tier architecture or a n-tier architecture.

    For example, consider a simple scenario in which we have a

    client/server architecture. A user simply connects with the serverand communication starts. The server fulfills all the requirementsof the client as all of the contents have been placed on the server.

    This type of architecture is called as a client/server architecture orit can also be said as a two-tier architecture.

    In a two-tier architecture the server contains all the contents thatwould be requested from the client, the contents can include web

    pages, the server-side technology implemented and the data-store. If we separate the contents of the server-side technology

    from the web pages and place them on a separate machine thenthis architecture would become a three-tier architecture. Similarlyif we keep on increasing the number of machines in between ourclient/server communication then we would be implementing then-tier architecture for our communication.

    Why do we need the three-tier architecture?

    The three-tier architecture was introduced for better management

    of code and contents and to improve the performance of the webbased applications. Within the three-tier architecture we divideour application into a set of three layers.

    4. Presentation5. Business Logic6. Database

    8

  • 8/14/2019 A Guide to Dotnet

    9/29

    The first layer Presentation contains the interface code,that is going to be displayed to the user. This code couldcontain any technology that can be used on the client sidelike HTML, JavaScript or VBScript etc.

    The second layer Business Logic contains all the code ofthe server-side technology. This layer mainly contains thecode that is used for accessing the database and to query,manipulate, pass data to user interface and handle any inputfrom the UI as well.

    The third and last layer Data represents the data store likeMS Access, SQL Server, an XML file, an Excel file or even atext file containing data.

    The following diagram shows the layers we have just described.

    (Figure Displaying the layers of the three-tier architecture)

    One of the main benefits of the three-tier architecture is easymanagement of the contents of the web application. Consider ascenario in which you require to change the presentation of theweb pages because you have recently designed a new look foryour website. In the case of two-tier architecture you wouldrequire to change the web pages that would be containing boththe contents for the presentation as well as the business logic,this would mean an headache for you to keep the code for

    business logic as it is and change the code for the presentationlayer. In case of a three-tier architecture the code of the businesslogic would be residing on the middle layer, there for you wouldbe requiring only to make a change on the presentation layercontaining the code for your web page designs.Similarly if yourequire to change the database system for example, from Accessto Sql Server, then you would require only to change the database

    9

  • 8/14/2019 A Guide to Dotnet

    10/29

    on the data server without having to make any changes within thecode of your business logics.

    The three-tier application design also enables for betterperforming web applications, since the whole load of users is notplaced upon a single server. As we can see in the figure displayingthe design of a three-tier architectured web application, it can beseen that placing the business logic and the database on thedifferent machines reduces the load upon a single server.Similarly we can implement any number of servers we like on thebackend of the application and such an architecture would beknown as n-tierarchitecture.

    .NET Assemblies - II

    This is a three series article.

    1. In the first part we discussed the 3-tier architecture.2. In part-II of this article we will see what the .NET assemblies

    are and3. In the last part we will be practically implementing a simple

    .NET assembly.

    Part-II :: Introduction to .NET Assemblies

    ASP .NET introduces many techniques for better codemanagement and code reusability. Code Behind and CustomControls are one of the best implementations of thesetechniques where you can separate your HTML tags and codingfrom your server-side script. It also provides future facilities tomanage the code easily.

    The Code Behindand Custom Controls development is a goodapproach to better web development, but there is a performancehit that also exists. You may know about the CLR (CommonLanguage Runtime), I will not go into the detail of this, but justfor a brief introduction, it is the "black box" or the "heart" of the.NET where the compilation of your code takes place. Wheneveran ASP .NET page is opened or requested by the user, the pagegets compiled first and then is transferred to the user. The

    10

  • 8/14/2019 A Guide to Dotnet

    11/29

    compilation process is also completed in two steps. First of all anIL (Intermediate Language) is generated and then this ishanded over for JIT (Just In Time) compilation which producesthe machine code and our pages get displayed with their dynamic

    content. The performance of our web application can be improved bycreating pre-compiled libraries of IL which can then be handedover to JIT directly without having the inclusion of an extraprocess to make the conversion. This method is calledcomponentization. Components are pre-compiled set of classesthat have been developed in the form ofDLL files and can thenbe included within our projects. This is also known as anassembly.

    "An assembly is a logical grouping of functionality in aphysical file."

    Understanding the assemblies and their concepts is the focus ofthis article. An assembly has many benefits some of which are.

    4. Increased performance.5. Better code management and encapsulation.6. Introduces the n-tierconcepts and business logic.

    You might have heard of the n-tier and three-tier architectureconcepts. (To know about the detail of 3-tier architecturalconcepts please read Part-I of this article.). The practicalimplementation of the three-tier architecture is also implementedby using the assemblies. In the first part of this article wediscussed about the Business Logic layer. This layer is where weplace all the business rules that apply to the transactions thattake place between the client and the server, and this layer is

    implemented through components. The reason for this is that onewe hide our code and the business rules that have been applied(since the components are in compiled binary form, so they are amean of code encapsulation) and second because they are moreefficient (since the code is already transferred into IL thereforeonly the JIT compilation takes place instead of both the IL andJIT).

    11

  • 8/14/2019 A Guide to Dotnet

    12/29

    .NET Assemblies - III

    This is a three series article.

    1. In the first part we discussed the 3-tier architecture.

    2. In part-II of this article we had an introduction to what the.NET assemblies are? and

    3. In the last part we are practically going to be implementing asimple .NET assembly.

    Part-III :: Implementing a simple .NET Assembly

    This part of the article is going to be the last of the series. In thelast part I introduced you to what the .NET Assemblies are and for

    what reasons are they used? You also were informed about theadvantages of using the .NET Assemblies as compared to theother scripting techniques that we have available in the ASP .NET.

    Before implementing an assembly I would like to add, that weimplement many pre-built assemblies while we are working onASP .NET based applications. For example; the Systemnamespace and other namespaces like it i.e. System.Data,System.Web are also pre-built assemblies that have beenprovided in the .NET framwork to us by Microsoft. In addition to

    this they have also provided us the capability of making our ownassemblies. As compared to the classic ASP making componentsin form of assemblies in ASP .NET is much more easier andflexible.

    Now let's go ahead with creating our first component. This isgoing to be a simple component that would just provide us with afew options to display a message on the screen. Write thefollowing code in Notepador any other editor that you have.

    Imports System

    Namespace HRM.DisplayPublic Class DisplayConsole

    Public Function Welcome() As String

    12

  • 8/14/2019 A Guide to Dotnet

    13/29

    Return "Welcome to your first component!"End Function

    Public Function Output(strParam As String) As String

    Return strParamEnd Function

    End ClassEnd Namespace

    Save this file by the name "hrmDisplay.vb".

    Now for the process of converting this file into a compiled DLLfile, we require to make a batch file. Again open the Notepadand

    add the following to it. Save the following file by name"MakeComponent.bat"

    set indir=c:\inetpub\wwwroot\hrmDisplay.vbset outdir=c:\inetpub\wwwroot\bin\hrmDisplay.dllset assemblies=System.dllvbc /t:library /out:%outdir% %indir% /r:%assemblies%

    Before running the file you require to create a directory by the

    name ofbin. Create a directory in your current directory by nameofbin and then run the file. Checkout the bin directory your DLLfile would be placed there after its creation.

    Before using the component we require to do one more thing! andthat is to make a web.config file. Web.config is an XML basedfile that specifies important configuration for an ASP .NETapplication. Again open up the Notepadand write the followingcode.

    13

  • 8/14/2019 A Guide to Dotnet

    14/29

    Save this file as "web.config". The reason that we made the bindirectory and then placed the DLL file within it was that theweb.config would always search for the file in the bin directory,not only this assembly, but other user defined and third partyassemblies also require there references to be added into theweb.config.

    Now we are ready to use our component within our ASP .NETpage. Open up Notepad or any other editor and add the

    following code into the file and save it as "Test.aspx".

    Sub Page_Load(Source As Object, Sender As EventArgs)

    Dim objComponent As New DisplayConsole

    Response.Write (objComponent.Welcome())
    Response.Write (objComponent.Output("This is my message!"))

    End Sub

    Now open your page in Internet Exploreror any other browserthrough your server and see your component in action.

    Understanding User Controls in .NET Framework

    Though you can apply multiple server controls in your web form,ASP.NET allows you to create new controls according to your

    14

  • 8/14/2019 A Guide to Dotnet

    15/29

    requirements. The controls that you create are called ASP.NETUser Controls. ASP.NET User Controls have .ascx extension. Thebiggest advantage of ASP.NET User Controls is that it allows youto save a part of the web form and reuse it many other web

    forms. This drastically reduces the developers time.ASP.NET User Controls are self-contained entities that are saved inan independent file. You can relate a user control with a blackbox. ASP.NET User Controls are very helpful when you want touse functionality on multiple pages of a web-application. Forexample, if you want to use a site navigation header or footer onall the pages of the web application, you can create this sitenavigation header or footer as a user control in a separate page.

    You do not need to place this user control on each and every

    page. You just have to write a few lines code to call the usercontrol.

    As ASP.NET User Controls are self-contained the developersworking on the same project need not worry about transgressingon others code. ASP.NET User Controls offer a great deal offunctionality than Server-side Includes (SSIs). Using SSIs inencapsulating the site functionality is a quite tedious task whencompared to ASP.NET User Controls. You can create a user control

    by using the Register directive. This process is called registeringthe user control. For instance, you can use this code to register auser control:

    The TagPrefix is the exclusive namespace provided to the usercontrol so that multiple ASP.NET User Controls with similar namecan be discriminated from each other. The TagName is the name

    of the user control and the Src is the virtual path to the usercontrol. After registering the user control you can place the tag ofthe user control in an appropriate location on the web form. Youhave to include the runat=server attribute with the tag.

    You can create a user control using only one programminglanguage for a web form. However, you can create multiple

    15

  • 8/14/2019 A Guide to Dotnet

    16/29

    ASP.NET User Controls for a web form. For example, you cancreate a user control using C# and another user control usingVB.NET and use both the ASP.NET User Controls on the same webform.

    About Web Forms in .NET Framework

    Web pages in ASP.Net are called ASP.NET Web Forms which havecertain server controls such as text, dropdown list, checkboxes,and buttons. An ASP.NET Web Form looks similar to the web formsin HTML. The only difference is that in ASP.NET, the Web Formsruns at the server side and in HTML the web forms runs at theclient side. Apart from this difference an ASP.NET Web Form hasmore features than an ordinary HTML web form such as:

    The code blocks are processed on the server. The entire page in ASP.NET is compiled when it is requested forthe first time. When you make subsequent requests, the page isnot compiled but shown directly in your browser. ASP.NET Web Forms can contain page directives. Page directivesallow you to set the default language and user controls tags forthe entire page. You can also turn off session state and ViewStatemanagement using page directives. An ASP.NET Web Form can contain both user controls and Serverside Includes (SSIs). An ASP.NET Web Form though run on the server can containclient side script such as JavaScript or Jscript.

    An ASP.NET Web Form first gets compiled into IntermediateLanguage (IL) and later to the machine language. Not just theserver side code gets compiled but every control and element inthe page gets compiled. This enables the ASP.NET Web Form to bein any language that is compatible with Common Language

    Runtime (CLR) engine. Another advantage with the code gettingtranslated to IL is that the user can use the application in anybrowser. In addition, you can reduce the processors and serversload when you compile the ASP.NET Web Forms in ASP.NET,thereby, increasing the users productivity time. Thus ASP.NETallows you to create Web Forms that are platform independent,language independent, and browser independent.

    16

  • 8/14/2019 A Guide to Dotnet

    17/29

    Access Control List in .NET Framework

    Once you complete developing a web application, you need tosecure it. This is when the aspect of security comes into picture.

    There will be some portions of your application which need to besecured from users. Securing an application may need extrahardware to build complex multi-layer systems with firewalls, andalso some highly secure features. Security enables you to provideaccess to a specified user after the user is authenticated andauthorized to access the resources in your web application. TheAccess Control List is used in the authorization process.

    The basic concepts of security are Authentication, Authorization,Impersonation and Data or functional security. Authentication is

    the process that enables to identify a user, so that only that useris provided access to the resources. Authorization is the processthat enables to determine whether a particular user can be givenaccess to the resources that the user requests. Impersonation isthe process that provides access to resources requested by a userunder a different identity. Data or functional security is theprocess of securing a system physically, updating the operatingsystem and using robust software.

    Some elements of an operating system, the Internet InformationServer (IIS), and the .NET Framework work in coordination toprovide the features required to execute the security conceptsmentioned above. For example, Windows 2000 uses its own list ofuser accounts for identifying and authenticating users. IISidentifies the users based on the information provided byWindows, when the users access a web site. IIS after identificationof the users, passes this information to ASP.NET. Then the userinformation is checked for authorization.

    To restrict access to the users for certain resources of anapplication, a process of identifying the users becomes anecessity. Authentication enables to restrict a user to access theresources by certain ways. It could be a combination of ausername and password, a digital certificate, a smart card or afingerprint reader. The validity of the information provided by theuser helps identify the user, so that the user is provided access to

    17

  • 8/14/2019 A Guide to Dotnet

    18/29

    the requested resources. The process of successful identificationof the user implies that the user is authenticated.

    After identification of the user is over, the next step is todetermine whether the authenticated user has access to theresources. The process of determining the access to the resourcesfor a particular user is known as Authorization. In Windows basedsystems, resources have an Access Control List, which provides alist of users who have access to that resource. The list alsospecifies the kind of access such as read, write, modify, anddelete the resource, for each user. For example, if a user requestsan ASP page, the operating system checks whether the user hasRead access to the page and if the user has read permission, thenthe operating system allows the IIS to fetch the page. The IIS has

    authorization settings which enable the IIS to control the access ofresources by users. File Access Control Lists are set for a given fileor directory using the Security tab in the Explorer property page.

    Understanding ASP.NET Validation Controls

    After you create a web form, you should make sure thatmandatory fields of the form elements such as login name andpassword are not left blank; data inserted is correct and is withinthe specified range. Validation is the method of scrutinizing thatthe user has entered the correct values in input fields. In HTMLyou can perform validation either by checking the values at client-side or after submitting the form at the server-side. But thesemethods in HTML take lots of time to create and maintain thecode. Moreover, if the user has disabled JavaScript then he or shemay not receive the message regarding the error.

    Therefore, in ASP.NET you can use ASP.NET Validation Controlswhile creating the form and specify what ASP.NET Validation

    Controls you want to use and to which server control you wantbind this. ASP.NET Validation Controls are derived from a commonbase class and share a common set of properties and methods.

    You just have to drag and drop the ASP.NET Validation Control inthe web form and write one line of code to describe itsfunctionality.

    18

  • 8/14/2019 A Guide to Dotnet

    19/29

    This reduces the developer time from writing JavaScript for eachtype of validation. Moreover, through ASP.NET Validation Controlsif any invalid data is entered the browser itself detects the erroron the client side and displays the error without requesting the

    server. This is another advantage because it reduces the serverload.

    The five types of ASP.NET Validation Controls in ASP.NETFramework include:

    RequiredField Validation control: prompts message if any inputfield is left blank. This validation control can also be used toprompt message to the user if he or she has left any input fieldwith its default value.

    Range Validation control: Prompts message to the user, if thedata entered in the input field is not within the range of thevalues specified by the Maximum and Minimum properties of thevalidation control.

    Comparison Validation control: Allows the user to compare twovalues and check for comparisons such as equality, greater-than,less-than etc. In addition you can check whether the data enteredin the input field is of the data type as specified by you.

    RegularExpression Validation control: Allows you to validate ifthe format of a certain input field is correct or not. You can checkthe validation of the commonly performed formats such as socialsecurity numbers, e-mail addresses, telephone numbers, andpostal code.

    Custom Validation control: Allows you to define your owncondition for validating the data in the input fields. Two validation

    functions can be performed using Custom Validation control: firston the server-side and second on the client-side. These functionscontain logic defined by you to validate the input fields. Thesefunctions returns the True value and False value, if the conditionyou specified is correct or not respectively.

    19

  • 8/14/2019 A Guide to Dotnet

    20/29

    If the controls value does not validate to what you have specifiedin the validation control tag, the web form displays an errormessage. Moreover, you can customize the format of the errormessage by using the control properties such as BackColor,

    BorderStyle, and BorderWidth. In addition, you can use CascadingStyle Sheet (CSS) to format an error message.

    Understanding ASP.NET Web Server Controls

    ASP.NET Web Server Controls are controls that run at the webserver. All ASP.NET Web Server Controls can be identified by theirattribute runat=server. ASP.NET Web Server Controls aresimilar to HTML controls. The only difference is that HTML controlsrun at the client-side and the developers have to write the code

    for each type of browsers. The ASP.NET Web Server Controls runat the server-side and automatically adapt to the type of browserthat request it.

    ASP.NET Web Server Controls also encapsulates and generateslarge amount of HTML tags, thereby allowing the developers timeto concentrate on coding. ASP.NET Web Server Controls makesexhaustive use of ViewState management. This makes data andvalues to be consistent across ASP.NET pages.

    All web controls are obtained from a common base class. Thisensures that the object model remains consistent across variouscontrols. For example, in order to move the cursor consistentlyacross a form you can specify the Web control TabIndex property.

    This is very difficult while using normal HTML. You can also disablea particular web control by exposing the Enabled property. Thisprocess is also difficult in HTML and ASP.

    ASP.NET ASP.NET Web Server Controls consists of Web form

    controls, List controls, and Rich controls. All the web form controlsare defined within the namespace System.Web.UI.WebControls.This namespace is a collection of classes that enables you tocreate new ASP.NET Web Server Controls. The controls that youcan use web form controls category are button control, checkboxcontrol, radiobutton control, table control, image control, labelcontrol, and panel control. These web form controls have a

    20

  • 8/14/2019 A Guide to Dotnet

    21/29

    common set of properties that can be used across multiplecontrols.

    The controls listed in the List controls category are dropdown listcontrol, repeater control, datalist control, and datagrid control.

    These controls use the concept of data binding. The controls listedin the Rich controls category include calendar control andadrotator control. These controls are specifically being employedfor complex tasks.

    Understanding WSDL and UDDI

    Web Services Description Language (WSDL) is one of the primespecifications in web services, the other two being SOAP and

    UDDI. WSDL is the description language for web services thatdescribes a set of SOAP messages and how these messages areexchanged across network. WSDL will be in XML format; thereforeit can be easily understood and edited by humans and machines.

    Another advantage of WSDL being in XML format is that it isprogramming language independent and also platformindependent. In addition, WSDL defines where the web service isavailable from and what communications protocol has been usedto talk to the web service. As a result the WSDL file describes

    everything that is required to write a program for an XML Webservice. There are tools available in Microsoft Visual Studio .NETto read a WSDL file and generate the code required tocommunicate with an XML Web service.

    Universal Discovery Description Language (UDDI) is a directorywhere you can expose your web services for other users to easilyaccess it. You can also consume the web service that is alreadyposted in UDDI. However, you can also post a web service without

    registering it in UDDI. DISCO is another directory where you canpost your web service. But if you want to reach to maximum ofcustomers, you can place it in UDDI. The UDDI directory offersthree parts for you to register:

    21

  • 8/14/2019 A Guide to Dotnet

    22/29

    White Pages Yellow Pages Green Pages

    The white pages consist of the description such as name andaddress of the company offering the service. The yellow pagesconsist of industrial categories based on standard taxonomiessuch as North American Industry Classification System andStandard Industrial Classification. The green pages describe theinterface to the web service in detail so that anyone can write anapplication after using the web service. Web services aredescribed in UDDI directory through a document called TypeModel or tmodel. Normally, this tModel contains a WSDL file thatdescribes a SOAP interface to an XML Web service, but the tModel

    is flexible enough to describe almost any kind of web service.

    Apart from using the web services from UDDI, you can also searcha particular web service in UDDI. In addition, you can search forcompanies information that posted web services. In certaintimes, you might know the names of the companies that offerweb services but you may not be aware of the web services thatthey offer. The WS Inspection is a specification in UDDI that allowsyou to search for a collection of web services that are located in a

    particular company name. You can evaluate these web servicesaccording to your requirements.

    Understanding Impersonation in ASP.NET

    At times users access a resource as though they were someoneelse. This is known as impersonation. For example, if a web pagehas no access controls, then any user can access that web page.HTML pages, ASP pages, and components in version 3.0 andearlier can be accessed through two accounts named

    IUSR_machinename and IWAM_machinename. Both the accountsare set up during IIS installation, and are automatically added toall the folders in every web site on the server.

    Anonymous access to a resource in IIS makes the task ofidentifying a user extremely difficult. But there is no need toauthenticate a user in the case of IIS. When IIS receives a request

    22

  • 8/14/2019 A Guide to Dotnet

    23/29

    for a web page or other resource that has permission foranonymous access, IIS treats the IUSR_machinename account asthe user's account, to access the resources. If the resourcerequested by the user is an ASP page that uses a COM or COM+

    component, that component is executed using theIWAM_machinename account.

    In ASP.NET, when impersonation is turned off, the resources canbe accessed using a "local system process" account. Whenimpersonation is turned on, ASP.NET executes every resourceusing the account of a specified user who is authenticated whenthe user makes the request. If you specify the IUSR_machinenameaccount to be used as the user account, then ASP.NET will behavelike previous versions of ASP, in providing access to the resources.

    In ASP.NET, you first need to check whether the application isconfigured to use impersonation. In the case of IIS, the IISimpersonates users with its own IUSR account. In the case ofASP.NET, impersonation is used to decide whether the user'srequest should be executed using the account of the requesteduser, or that of a local system-process account that ASP.NET usesfor anonymous requests.

    The concept of impersonation is complex to some extent due tothe fact that ASP.NET uses the dynamic compilation features ofthe .NET Framework. The IUSR account has only limitedpermissions on the local machine, and so is not suitable withoutsome reconfiguration. This account is also used by IIS to accessresources like HTML pages, documents, and zip files that are notexecuted as part of the .NET Framework.

    If impersonation is enabled in an ASP.NET application then: If anonymous access is enabled in IIS, the request is made using

    the IUSR_machinename account. If anonymous access is disabled in IIS, the request is madeusing the account of the authenticated user. In either case, permissions for the account are checked in theWindows Access Control List (ACL) for the resource(s) that a userrequests, and a resource is only available if the account they arerunning under is valid for that resource.

    23

  • 8/14/2019 A Guide to Dotnet

    24/29

    If impersonation is disabled in an ASP.NET application then: If anonymous access is enabled in IIS, the request is made usingthe system-level process account. If anonymous access is disabled in IIS, the request is made

    using the account of the authenticated user. In either case, permissions for the account are checked in theWindows ACL for the resource(s) that a user requests, and aresource is only available if the account they are running under isvalid for that resource.

    Basic use of Session in ASP.NET (C#):

    STORE:DataSet ds = GetDataSet(whatever parameters);

    Session["mydataset")=ds;

    RETRIEVE:DataSet ds = (DataSet)Session["mydataset"];

    Storage location

    InProc - session kept as live objects in web server(aspnet_wp.exe). Use "cookieless" configuration inweb.config to "munge" the sessionId onto the URL (solves

    cookie/domain/path RFC problems too!) StateServer - session serialized and stored in memory in a

    separate process (aspnet_state.exe). State Server can run onanother machine

    SQLServer - session serialized and stored in SQL server

    Performance

    InProc - Fastest, but the more session data, the morememory is consumed on the web server, and that can affectperformance.

    StateServer - When storing data of basic types (e.g. string,integer, etc), in one test environment it's 15% slower thanInProc. However, the cost of serialization/deserialization canaffect performance if you're storing lots

    24

  • 8/14/2019 A Guide to Dotnet

    25/29

    of objects. You have to do performance testing for your ownscenario.

    SQLServer - When storing data of basic types (e.g. string,integer, etc), in one test environment it's 25% slower than

    InProc. Same warning about serialization as in StateServer.Performance tips for Out-of-Proc (OOP) modes

    If you're using OOP modes (State Server or SQL Server), one ofyour major cost is the serialization/deserialization of objects inyour session state. ASP.NET performs theserialization/deserialization of certain "basic" types using anoptimized internal method. "Basic" types include numeric types ofall sizes (e.g. Int, Byte, Decimal, ... etc), String, DateTime,

    TimeSpan, Guid, IntPtr and UIntPtr.

    If you have a session variable (e.g. an ArrayList object) that is notone of the "basic" types, ASP.NET will serialize/deserialize it usingthe BinaryFormatter, which is relatively slower.

    For performance sake it is better to store all session state datausing one of the "basic" types listed above. For example, if youwant to store two things, Name and Address, in session state, youcan either

    (a) store them using two String session variables, or(b) create a class with two String members, and store that classobject in a sessionvariable. Performance wise, you should go with option (a).

    Robustness

    InProc - Session state will be lost if the worker process(aspnet_wp.exe) recycles, or if the appdomain restarts. It'sbecause session state is stored in the memory space of anappdomain. StateServer - Solve the session state lossproblem in InProc mode. Allows a webfarm to store sessionon a central server. Single point of failure at the State Server.

    25

  • 8/14/2019 A Guide to Dotnet

    26/29

  • 8/14/2019 A Guide to Dotnet

    27/29

    Q: Why does the SessionID changes in every request?A: This may happen if your application has never stored anythingin the session state. In this case, a new session state (with a newID) is created in every request, but is never saved because it

    contains nothing.However, there are two exceptions to this same session IDbehavior:- If the user has used the same browser instance to requestanother page that uses the session state, you will get the samesession ID every time. For details, see "Why does the SessionIDremain the same after the Session times out?"- If the Session_OnStart event is used, ASP.NET will save thesession state even when it is empty.

    Q: What kinds of object can I store in session state?A: It depends on which mode you are using:- If you are using InProc mode, objects stored in session state areactually live objects, and so you can store whatever object youhave created.- If you are using State Server or SQL Server mode, objects in thesession state will be serialized and deserialized when a request isprocessed. So make sure your objects are serializable and their

    classes must be marked as so. If not, the session state will not besaved successfully. In v1, there is a bug which makes the problemhappen unnoticed.

    Q: How come Response.Redirect and Server.Transfer is notworking in Session_End?A: Session_End is fired internally by the server, based on aninternal timer. Thus, there is no HttpRequest associted when thathappens. That is why Response.Redirect or Server.Transferdoesnot make sense and will not work.

    Q: Do I have a valid HttpContext in Session_End?A: No, because this event is not associated with any request.

    Q: Will my session state be saved when my page hit an error?No. Unless you call Server.ClearError in your exception handler.

    27

  • 8/14/2019 A Guide to Dotnet

    28/29

    Q: How do I use session state with web services?A: The extra trick needed is on the caller side. You have to saveand store the cookies used by the web service. See the MSDNdocumentation on HttpWebClientProtocol.CookieContainer

    property.However, please note if you're using proxy object to call a webservice from your page, the web service and your page cannotshare the same session state due to architecture limitation.

    This can be done if you call your web service through redirect.

    Q: I am writing my own HttpHandler. Why is session state notworking?

    A: Your HttpHandler has to implement the "marker" interfaceIRequiresSessionState or IReadOnlySessionState in order to usesession state.

    Q: I am using a webfarm, and I lost session state when directed tosome web servers.A: For session state to be maintained across different web serversin the web farm, the Application Path of the website (For example\LM\W3SVC\2) in the IIS Metabase should be identical in all theweb servers in the web farm.

    See KB 325056 for details.

    Q: If using "cookieless", how can I redirect from a HTTP page to anHTTPS page?A: Try this:String originalUrl = "/fxtest3/sub/foo2.aspx";String modifiedUrl = "https://localhost" +Response.ApplyAppPathModifier(originalUrl);Response.Redirect(modifiedUrl);

    NOTE: Fully qualified URLs in the response.redirect,server.transfer, and FORM actiontags cannot be used with cookiless sessions

    Q: What isn't Session available in my event handler inglobal.asax?

    28

  • 8/14/2019 A Guide to Dotnet

    29/29

    A: It depends on which event you're handling. Session is availableonly after AcquireRequestState event.

    Q: Does session state have a locking mechanism that serialize theaccess to state?Session state implements a reader/writer locking mechanism:- A page (or frame) that has session state write access (e.g. ) will hold a writer lock onthe session until the request finishes.- A page (or frame) that has session state read access (e.g. ) will hold a reader lockon the session until the request finishes.- Reader lock will block a writer lock; Reader lock will NOT blockreader lock; Writer lock will block all reader and writer lock.

    - That's why if two frames both have session state write access,one frame has to wait for the other to finish first

    29


Recommended