aspnetdeveloper

,ASP.NET

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

This website belongs to Kevin Harris who resides in Homer Illinois and works in Champaign Illinois. I update the website as I learn more about .NET.

ASP.NET is Microsoft's open-source Web application framework. ASP.NET was released in 2002 as part of Microsoft's .NET Framework. After the release of ASP.NET, Microsoft's previous ASP scripting engine became known as Classic ASP. While Classic ASP used scripting languages to embedded server-code into HTML files, much like the PHP environment, ASP.NET took a much different approach. ASP.NET compiles strongly-typed languages which fully support object-oriented programming (OOP). The compilation model provides better performance, better security, and allows for more powerful development tools.

The current version of ASP.NET is ASP.NET Core which is a lean and composable framework released in June 2016. .NET Core is a cross-platform version of .NET that is designed for the cloud, and runs on Windows, Linux and Mac. ASP.NET Core is an open source project residing on GitHub. In ASP.NET Core, MVC, Web API, and Web Pages have merged into a unified MVC 6. .NET Core
works with Entity Framework 7.

..NET Core

ASP.NET continues to evolve to keep pace with changing web technologies and is strongly supported through its ties to the .NET Framework, by third-party vendors, and the open source community. Informative ASP.NET websites include:

Classic ASP

ASP (Active Server Pages) is a Microsoft server-side scripting engine. ASP is similar to the method in which the PHP language is used to interpret code for web clients. Both ASP and PHP embed their scripting languages into a single file which contains code which can be processed by the web clients (HTML, CSS, JavaScript). This macaroni code is interpreted as the web page runs to produce additional native code for the web clients. PHP was first developed as a series of Common Gateway Interface (CGI) binaries written in C. Instead of using CGI, ASP was one of the first web application development environments to use a more efficient method of integrating web application execution directly into the web server.

In 1996 the most popular method of writing web applications was to call external executable programs known as CGI scripts. The CGI method created a server process to interpret each script. The integration of the script processing directly into the web server eliminated the need to create a process for each script. Instead only the web process was required. The integration method proved to be a more efficient way to process dynamic web pages than CGI. Today if the webserver has an embedded PHP interpreter (e.g. mod_php in Apache), then the CGI phase is skipped in favor of the more efficient direct protocol between the web server and the interpreter.

ASP and PHP are the two heavyweights in the world of web applications. Blogs are filled with biased opinions why one is better than the other. However they have both become hugely successful ventures. As both products matured, they grew to have smaller differences. PHP was enhanced with more objected-oriented support, however object-oriented support has never become fundamentally integrated into PHP the way it is in ASP. Both development environments have improved. But the Visual Studio IDE gained an inherent advantage (better debugging, intellisense, etc.) over PHP IDEs when ASP moved to the compilation of strongly-typed languages. PHP is considerably easier to learn, especially since ASP has integrated complicated design patterns into its development models. However using these development models tend to prevent ASP developers from coding their own web frameworks, which all too often end up as a big ball of mud.

As ASP evolved to use the .NET framework, the original version of ASP became referred to "classic ASP". Three versions of classic ASP were introduced with different versions of IIS:

  • ASP 1.0 - released December 1996 as part of IIS 3.0
  • ASP 2.0 - released September 1997 as part of IIS 4.0
  • ASP 3.0 - released November 2000 as part of IIS 5.0

Classic ASP uses embedded server scripting code in a similar way as PHP. ASP uses "<%" and "%>" while PHP uses "<?php" and ">" as delimiters for the server code. The PHP language is similar in complexity to the default language used in Classic ASP (VBScript). A considerable amount of spaghetti or spaghetti with meatballs code have been written in both languages. Implementations of classic ASP were initially developed for other web servers (Apache, I-Planet, Zeus, Red Hat Secure Server, etc.) . Sun Microsystems produced a product called Chili!Soft ASP which was used various flavors of the Unix operating systems. The Sun Chili!Beans product enabled the use of Java objects with ASP applications. The Sun ASP products have been discontinued, however you can still find web hosts who support Chili!Soft ASP. Apache::ASP is an active project which provides an ASP port to the Apache Web Server with Perl scripting. As ASP transformed into ASP.NET and became open source, it is now capable of running on several platforms besides its traditional IIS.

Two examples of creating Microsoft ASP scripts are listed below. The first script uses the default VBScript language, while the second uses JavaScript:

VBScript1.asp
  1.   <!DOCTYPE html>
  2. <html>  
  3.       <body>  
  4.       <%  
  5.            For i = 0 To 5  
  6.                 response.write("Hello World!<br/>")  
  7.            Next  
  8.       %>            
  9.       </body>  
  10.   </html>


JavaScript1.asp
  1.   <%@ language="javascript"%>
  2. <!DOCTYPE html>  
  3. <html>  
  4.       <body>  
  5.       <%  
  6.            for (var i = 0; i < 5; i++) {  
  7.                 Response.Write("Hello World!<br/>")  
  8.            }  
  9.       %>            
  10.       </body>  
  11.   </html>


.NET Framework

The .NET Framework is Microsoft's software framework for developing the following types of applications:

  1. Web Applications - Web Forms, MVC, Web Pages.
  2. Desktop Applications - Windows Forms, Windows Presentation Foundation (WPF), p&p Prism for WPF.
  3. Tablets - Universal Windows Apps, Windows Store Apps, p&p Unity for Windows Store Apps.
  4. Mobile Devices - Windows Phone (WP), Xamarin partner for iOS and Android development.
  5. Internet Devices - a.k.a. Internet of Things (IOT), Micro Framework, Compact Framework.
  6. Cloud Applications - Azure SDKs, Azure Mobile Services, Azure Media Services.
  7. Services - Windows Communication Foundation (WCF), Web API, SignalR

The .NET Framework was initially released in 2002. It has evolved quickly and constantly to keep up with advancing technologies. The .NET Framework is going through a progression toward open source licensing. The open source components already included C#, VB, ASP.NET 5, and Entity Framework, when on November 12, 2014 Microsoft announced the .NET Core (runtime and class libraries) would go open source. The .NET code repository resides on GitHub with the .NET Foundation hosting an independent forum to foster the open development and collaboration of open source technologies for .NET.

Alternate implementations of .NET technologies include:

  1. Mono - includes support for a wide range of architectures and operating systems.
  2. NET Micro Framework - is a .NET platform for extremely resource-constrained devices.
  3. Portable.NET - supports a variety of CPUs and operating systems.
  4. CrossNet - free software using the open source MIT License.
  5. Numerous open-source languages - which are compliant with the Common Language Infrastructure (CLI) specifications which can be run on the CLR, or Mono, or Portable.NET. A few of these languages are: IronPython, IronRuby, IronLisp, Phalanger (PHP), Niecza (Perl), Cobra, Eiffel, Component Pascal, Lisp#, and A#.

.NET contains a Common Language Runtime (CLR) which manages the execution of code. The CLR provides core services such as memory management, thread management, strict type safety and other forms of code accuracy that promotes security and robustness. It is also possible to develop code which does not target the CLR (unmanaged code). The .NET Framework class library (FCL) is a collection of reusable objects which are tightly integrated with the CLR.

The .NET framework contains several languages (C#, C++, VB, F#) which are interoperable (i.e. exchange data between processes running on different platforms written in different languages) where they conform to the Common Language Specification (CLS). Most of the members defined in the FCL are CLS-compliant. An example of CLS-noncompliance is some of the specifications from C and C++ which were brought over to C#. The CLSCompliantAttribute attribute is used to test for CLS compliance. In the following example the code will not compile because the unsigned integer data type isn't part of the CLS.

Checking for CLS Compliance
  1. using System;
  2. [assembly: CLSCompliantAttribute(true)]
  3. [CLSCompliantAttribute(true)]
  4. public class Class1
  5. {
  6.     public void x(UInt32 x) { }
  7.     public static void Main()
  8.     {
  9.     }
  10. }

The FCL contains Microsoft created code for providing support for various core functions: security, database connectivity, web development, network communications and much more. Programmers produce software by combining their own source code with .NET Framework and other third-party libraries. There are many open-source third-party libraries which can be pulled into a .NET project to instantly add functionality (e.g. custom controls, creating html editors in a page, importing exporting files, system logging, etc.). The NuGet Package Manger is now integrated in Visual Studio and simplifies the way libraries are added to a project.

It is possible create .NET programs using a simple text editor. An example of this is the DB2 database conversion program called Conversion Assistant which I wrote using only Notepad. Fortunately today there are free IDEs to assist with development. In recent years developers would get the free "Express" editions which had limited capabilities and usage license. Since .NET went open-source, Microsoft provides a free fully-functional version of Visual Studio (Visual Studio 2013 Community Edition) which contains all the same capabilities as the Professional Edition. VS 2013 Community Edition is free for everyone except large enterprises.

The release of .NET and Visual Studio versions are frequently tied to operating system releases:

.NET Framework, Visual Studio, and Operating System Releases
.NET Release Date IDE Operating System Windows Server
1.0 2002-02-13 Visual Studio .NET
1.1 2003-04-24 Visual Studio .NET 2003 2003
2.0 2005-11-07 Visual Studio 2005 2003, 2008 SP2, 2008 R2 SP1
3.5 2007-11-19 Visual Studio 2008 7, 8, 8.1 2008 R2 SP1
4.0 2010-04-12 Visual Studio 2010
4.5 2012-08-15 Visual Studio 2012 8 2012
4.5.1 2013-10-17 Visual Studio 2013 8.1 2012 R2
4.6 2015-07-20 Visual Studio 2015 10 2016
.NET Core 1.0 2016-6-27 Visual Studio 2015 SP3, VIsual Studio 2017 10 2016


ASP.NET

The successor to ASP is ASP.NET. ASP.NET went through four years of development and a series of beta releases before being released in January 2002 as part of version 1.0 of the .NET Framework. While classic ASP is similar to PHP in functionality and design, the design of ASP.NET differs considerable. Some of the differences between ASP and ASP.NET are:

  1. Interpretation vs. Compilation

    ASP interprets weakly-typed scripting languages (VBScript, JScript), while ASP.NET uses compiled languages which are strongly-typed (C#, VB.NET, etc.). ASP.NET's compiled operation more efficient and secure than ASP's interpreted operation.

    ASP.NET's compilation model also allows the use of more advanced debugging technologies, such as those used in desktop applications. ASP and PHP have limited debugging capabilities. Several advanced (and actually functional) debugging environments exist for ASP.NET, with Visual Studio being an exceptional choice. An additional benefit is the fact that many errors could be found at compile-time instead of at run-time. The strongly typed languages used in ASP.NET also allows for much better intellisense to help during code development.

  2. More Complete Support for Object-Oriented Programming

    ASP.NET is a fully-featured OOP environment and contains more rigorous OOP features (inheritance, encapsulation, reflection, full encapsulation, full polymorphism) than does classic ASP or PHP. Unlike ASP and PHP, the ASP.NET framework is built from the ground up on OOP concepts. Development in ASP.NET involves constructing classes and building hierarchies. Each ASP.NET web page is a new class derived from the System.Web.UI.Page class. The downside of this more complete implementation of OOP is that ASP.NET has a steeper learning curve that ASP or PHP. The upside is ASP.NET applications have a better design with a clear separation of content, logic, and data which makes them more scalable, more robust, and easier to support over the application's life cycle.

  3. Built-In Functionality

    Supportive frameworks exist to extend the functionality of ASP and PHP (e.g. CLASP, ZEND), but they do not have the vast amount of functionality which is built into the .NET framework. Even with supportive frameworks, ASP and PHP developers still create "home-grown infrastructures" to include user controls, validation, and data access. This is not needed with ASP.NET because of its extensive .NET library. The .NET framework provides a simple way to create custom server-side user controls (i.e. without using client-side code). ASP.NET's validation controls are used to perform both server-side and client-side validation. ASP.NET also makes it very easy to use AJAX by wrapping the XAML code in Update Panels and including a script manager.

    Visual Studio contains many built in templates for creating various types of components and applications. For example, when creating an MVC application using Visual Studio 2013, the template includes a number of popular JavaScript libraries:

    1. jQuery
    2. Modernizr
    3. bootstrap
    4. respond

    Integrated into Visual Studio is the NuGet package manager which allows you to search and download packages into your project from a vast repository of libraries. A few of the popular packages include:

    1. iTextSharp (create PDF documents)
    2. NLog/ELMAH (application logging)
    3. Entity Framework/NHibernate (Object-Rational Mapper)
    4. PostSharp (Aspect-Oriented Programming)
    5. DataTables (interaction controls for HTML tables)
    6. ExcelDataReader/NPOI (working with Excel files)
    7. Math.NET (numerical computations)
    8. Glimpse (web debugging and diagnostic tool)
    9. Xamarin.Forms (native UIs for iOS and Android)
    10. AutoPoco (test generation framework)
    11. CKEditor (puts word processing functions into page)
  4. Process Isolation

    ASP is run under the IIS Web Server process called "inetinfo.exe" which can make the ASP application crash when IIS is stopped or restarted. While ASP.NET uses a distinct worker process which is isolated from the IIS Web Server process. This provides ASP.NET with added stability and security for its web applications. Key concepts to ASP.NET's process isolation are:

    • Worker Process - Worker Process (w3wp.exe) runs the ASP.Net application in IIS. Process manages all request and responses from client system. All the functionality of an ASP.NET Web Application runs under the scope of a worker process, which runs on IIS.

    • Application Pool - The Application Pool is the container for worker processes. The application pool separate sets of IIS worker processes that share the same configuration. Application pools enable better security, reliability, and availability for web applications. The worker process provides isolation so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools.
  5. Other

    Classic ASP will continue to be supported for many years, however Microsoft is no longer enhancing Classic ASP. Instead all of the new technology and enhancements are being put into ASP.NET. ASP.NET continues to evolve very quickly with more powerful elements, new design patterns, new communications methods, improved developer environments, new hosting technologies, and increased support for mobile devices and various operating systems. ASP.NET is now open source and is the clear direction Microsoft has chosen for future web development.

Evolution of ASP.NET

There have been several major releases of ASP.NET. Each major release introduces significant changes which can impact the designing, developing, deploying, and hosting ASP.NET of web applications. It would be ideal if a programmer could always develop with the latest version of ASP.NET. However programmers typically find themselves having to target a specific version of .NET. This requires an understanding of the capabilities and functionality of the different .NET versions ... sometimes even down the Service Pack level. An example of this is the fundamental difference is the way ASP.NET web applications are structured. In current Microsoft terminology this is called Web Site Projects vs Web Application Projects.

Visual Studio .NET 2003 had a "Web Project" model for ASP.NET development which was similar to the other existing types of projects existing in Visual Studio. A project file was used to group all the files which made up the web site. The initial release of Visual Studio 2005 replaced the "Web Project" model with a "Web Site" model which worked by simply grouping all the files making up the web site into one folder. After several developers explained to Microsoft the difficulties they were having with the new "Web Site" model, Microsoft released the "Web Application" project as an add-in to Visual Studio 2005. The new "Web Application" project was similar to the older "Web Project". All subsequent releases have both the Web Site and Web Application models built in to Visual Studio. The two types of development models differ significantly, especially when considering how the applications are deployed. Microsoft recommends careful consideration before deciding on a particular model. For more details about how these two development methods differ, see the ASP.NET Web Site vs Web Application article.

ASP.NET currently has three prominent web development models:

  1. Web Forms - Was the first ASP.NET development model. It features an environment similar to desktop development, with events, drag-and-drop server controls, and an artificial state built into the model. The model provides for separation of the HTML interface from the application logic by using a "code-behind" file. Web Forms contains a rich set of server-side controls with automatic browser adaptations and data binding capabilities. This model is very popular for rapid development. This model is currently heavily in use and will continue to be supported for many years.

  2. MVC - Is based on the Model-View-Controller architectural pattern which features inherent separation of concerns (Model = Data, View = UI, Controller = User Interaction and Rendering UI). This development model works at a more direct level with HTTP and offers more control over the web application while maintaining greater isolation between its components. For those with a development background with only event-driven coding, learning MVC is not as intuitive as Web Forms. Several versions of MVC have been released in quick succession and the MVC model is very popular and is acquiring wide usage. This model allows for automated testing, which is very difficult in an event-based model. The MVC components are also loosely coupled which allows them to be constructed and tested independently.

  3. Web Pages - Is a recent simplified model containing both old and new aspects of ASP. Web Pages a lightweight development approach which still provides all the benefits of the .NET framework, including a managed environment, type safety, and inheritance. Web Pages embed server-side code to create macaroni code (HTML, CSS, JavaScript, Server Code), much like PHP or Classic ASP, but uses a newer "Razor" markup syntax with either C# or Visual Basic. The Web pages model supports event-driven development similar to Web Forms. Also similar to Web Forms is the way Web Pages creates an implicit artificial state.

Web Forms

Web Forms was the first ASP.NET development model. Web Forms abstracted the web development environment to be similar to the desktop development environment (Windows Forms). Web Forms is an event-driven model containing an underlying state management system with controls similar to those used in Windows Forms. Programmers experienced in desktop application development found the Web Forms model to be intuitive and easy to learn. Web Forms allows programmers to work at a higher-level of abstraction and simplifies many everyday tasks. Web Forms is all about productivity and rapid development through its use of server controls, events, automated state management, forms authentication, and numerous intrinsic objects.

Web Forms Solution

Classic ASP embedded the server code inside an HTML file. Web Forms still support this "macaroni code" method, but also allows the server-code to be put into a separate file from the UI declaration. The way the server code and UI declaration has changed within different versions of ASP.NET. The first separation method called Code Behind and used inheritance. A second method was created later when partial types where introduced into the .NET languages. It used partial classes and was simpler and more stable. Initially, the second method was called, by some, Code Beside to distinguish it from the first method. However it became common to use the term Code Behind to refer to the second method as well. The old macaroni code method is also called by various names, such as Code Inside or In-line code A recent MSDN article refers to the two models as The Single-File Page Model and The Code-Behind Page Model. Code Behind is now the default model for Web Form applications. Code Behind is not only simpler for the programmer, but also simplifies the work for intellisense, the web server, and the compiler.

Processing Web Forms

In Web Forms, each request for a web page goes to the web server and is handed over to the ASP.NET HTTP pipeline. The HTTP pipeline is a chain of objects which sequentially process the request and makes the translation to HTML. The entry point of the HTTP pipeline is the HttpRuntime class. The HttpRuntime class allocates an HttpApplication object from an internal pool. The main task of the HTTP application manager is to determine which handler class will process the request. The base class for the HTTP handler is the Page class. However when a Code Behind file is used, the a new partial class is created which inherits from the Page class. It which case the derived class is used for the HTTP handler. The HTTP handler can also be overridden by specifiying the PageBaseType attribute in the Web.config file.

Once the page handler class is identified, the ASP.NET run time calls the handler's ProcessRequest method to process the request. This method is defined in the Page class and typically there is no reason for it to be overridden. ProcessRequest processed the page in various stages: initialization, loading of view state information and postback data, loading of the page's user code and execution of postback server-side events. Then the page goes through rendering stages: the updated view state is collected; the HTML code is generated and then sent to the output console. The final stage is when the page is unloaded from processing.

Various events are triggered as the page goes through the processing stages. Some of can be intercepted and handled by user code. A page that wants to handle a certain event needs to explicitly register an appropriate handler. However ASP.NET also supports a form of implicit event hooking in which the page tries to match method names with events. The method names: Page_Init, Page_Load, Page_DataBind, Page_PreRender, and Page_Unload are treated as handlers for the corresponding events. The HTTP run time will automatically bind these methods to page events saving developers from having to write the explicit code. The automatic recognition of special method names is a behavior under the control of the AutoEventWireup attribute of the @Page directive. If the attribute is set to false, any applications that wish to handle an event need to connect explicitly to the page event. Pages that don't use automatic event wire-up will get a slight performance boost by not having to do the extra work of matching names and events. However, the default setting for the AutoEventWireup attribute is true.

,Page Life Cycle Stages


Web Forms
Web Page Life Cycle

Features of Web Forms

Web Forms contain a number of controls which can be used in web pages. Many controls have events which can be accessed programmatically to trigger the execution of code. Web Form controls can be categorized as:

  1. Security - Login, ChangePassword, PasswordRecovery, CreateUserWizard.
  2. Data Input/Display - GridView, DataList, Chart, standard program controls (buttons, drop down lists, etc).
  3. Data Source - SqlDataSource, XmlDataSource, EntityDatSource, ObjectDataSource, LinqDataSource.
  4. Navigation - breadcrumb trails (SiteMapPath), TreeView, Menu.
  5. Validation - RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, CustomValidator.
  6. User - .ascx file, custom reusable controls to be used across pages (e.g. for headers, footers, menus).
  7. AJAX - ScriptManager, UpdatePanel, UpdateProgress, Timer.

Web Forms contain a features available for web pages:

  1. Master Pages - page template that provides consistent look and functionality across web pages.
  2. Themes/Skins - using CSS to create a custom look for a set of components.
  3. Localization - support for multiple languages.
  4. Adaptive UI - controls are dynamically generated based on the features of particular browsers.

Web Forms contain several application services:

  1. Membership - authenticate users, login, logout users.
  2. Role Manager - show or hide parts of application or page based on a user's role.
  3. Personalization - track personal settings for user.
  4. Site Navigation - besides navigation controls, can also store navigation in a database.
  5. Caching - very important for high availability sites. Caching levels of pages: parts of page, data objects.
  6. Management - monitoring of website performance and usage.

The default for Web Forms is to generate two files (.aspx and .aspx.cs (C#) or aspx.vb (VB) to separate out the server-code from the UI declaration. However it is still possible to combine both into one .aspx file as was done in classic ASP, but this is not recommended for typical usage.

Elements inside a .aspx.cs or .aspx.vb file (Code Behind File):

  1. Program Code - code which will be executed on the server.

Elements inside a .aspx file:

  1. Directives - page directives set specifications at the page level, including:
    1. Turn On/Off Tracing (Trace="true")
    2. Coding Language
    3. Compiler Options
    4. Declare Page Title for Browser's Title Bar
    5. Automatic Event Wireup
    6. Define Code Behind Page to Inherit
    7. Enable View State
    8. Enable View State Encryption
    9. Set ClientIDMode at page level (important for JavaScript)
    10. Compile with Debug Information
    11. Master Pages or Themes
    12. Maintain Scrollbar Position
    13. Redirection for Custom Error Page
    14. Validate Request, all input data checked against list of dangerous values
    Page Directive
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>


  2. Code Blocks - allows code to be embedded with UI declaration. (Not recommended)
  3. Server Controls - Microsoft controls start with asp: and contain runat="server" inside tag.
  4. User Controls - headers, footers, things that repeat across pages.
  5. Render Blocks - <%@ %> short cut for Respose.Write. Displays value of variable.
  6. Expression - <%$ %> get connection strings from Web.config.
  7. Data Binding - <%# Eval %> - bind data to control

Postbacks

Classic ASP and PHP frequently used a two-page form processing technique. The first page would present the HTML for the form, which contained the user input fields. The form's "ACTION" parameter would contain the name of a second page which would process the values entered into the controls. However, another approach in Classic ASP and PHP is to post the input data back to the same page by putting name of the script containing the user input fields into the form's "ACTION" parameter. The page then needs to detect if it is posting the input data back to the same page by checking if the request method is a "POST" and checking if the name of the referring script is the same as the name of the current script.

Web Forms development was designed to implement the second method, of posting the input data back to the same page, as its default method. Web Forms uses the "IsPostBack property of the Page class to indicate if the page is being submitted back to itself. The first method, of posting input data back to a different page, is called "Cross-Page Posting" in Web Forms. This is useful when you are creating a multi-page form that collects information on each page. However, Web Forms has a "Wizard" class that simplified the implementation of a multi-page form, and is frequently used instead of Cross-Page Posting.

The IsPostBack property is frequently used, along with Web Forms automated state management, to perform initializations a single time. For example, if a database query is executed and returns a result set that is bound to a GridView, thanks to the underlying "Control State", the GridView only needs to be bound to the data on the first post. So the database query and data binding can be put inside a conditional statement so it is only performed when the page is not being posted back to itself (which is typically the first time the page is loaded).

The Web Forms post back mechanism contains two hidden fields and a JavaScript function (__doPostBack). All the server controls, except Button and ImageButton, call the JavaScript function to perform postbacks. This can be seen by looking at the generated HTML code when using a Drop Down List control that has its AutoPostBack property set to True, as shown below:

__doPostBack
  1. <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
  2. <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
  3.  
  4. <select name="ccPerson1$ddlAge" id="ccPerson1_ddlAge" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;ccPerson1$ddlAge\&#39;,\&#39;\&#39;)&#39;, 0)">
  5.     <option value="A">0-30</option>
  6.     <option value="B">31-60</option>
  7.     <option value="C">61-90</option>
  8. </select>
  9.  
  10. <script type="text/javascript">
  11.     function __doPostBack(eventTarget, eventArgument) {
  12.         if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
  13.             theForm.__EVENTTARGET.value = eventTarget;
  14.             theForm.__EVENTARGUMENT.value = eventArgument;
  15.             theForm.submit();
  16.         }
  17.     }
  18. </script>

Web Forms will only insert the __doPostBack() function into your page automatically when there is a control that can initiate a post back. I have seen pages where the developer has hard coded the __doPostBack() function into the page because it was not being generated automatically. Microsoft discourages this practice and instead recommends using the "GetPostBackEventReference" method to have the definition of the __doPostBack method generated into the web page. ASP.NET contains a security feature that verifies that arguments to a post back originate from the rendering server control So if a post back is being called in response to some business logic, the "RegisterForEventValidation" method will need to be used to tell the server to allow the post back.

,Fiddler Web Proxy


Fiddler Web Proxy
Viewing Cookie Data

State Management

A State Machine is a computation model used to design certain types of software (among many other things). A Finite State Machine (FSM) progresses through a number of stages. Events arise which cause the progression to transition from one stage to the next based on a limited amount of data associated with the particular stage and deterministic logical functions. At each stage of the progression, the associated data is referred to as its "State". State is important in modern computers where processes are being constantly switched in-and-out of the CPU. A process needs a record of its data values and stage of execution (i.e. its State) when it is returned to the CPU to continue processing for its next allocated time-slice.

In web applications, State refers to the current value of controls and variables at a particular instance in time. The underlying communication protocol (HTTP) for web applications is intrinsically stateless. HTTP consists of independent pairs of Requests (to a server) and Responses (back to the client). Using HTTP, the server and client are aware of each other only during the current request-response cycle for a page. Afterwards, all information associated with the page is lost HTTP can not retain information between the request-response cycles.

Web programming uses several techniques to persist data beyond the current request-response cycle and overcome this inherent limitation of HTTP. The duration of the persistence, the time required to retrieve the data, and the security of the data vary with the different techniques. The persisted data can reside on either the client or the server. However it is possible to lose the persisted data using either client-side technique or server-side techniques. Only persisted data stored in permanent medium, such as a database, can survive a reboot of both the client and the server. However this type of permanent data persistence makes the applications slow.

Storing the persisted data on the client side requires the data to travel back-and-forth with the web page. While this saves memory on the server, it requires more proportionally more bandwidth related to the amount of data persisted. The data traveling back-and-forth is also vulnerable to interception making it less secure.

Storing the persisted data on the server side is more secure and requires less bandwidth, but consumes more server memory which can negatively affect scalability. Many times the solution for persisting data uses a mixture of client-side and server-side techniques to protect sensitive data but still promote responsiveness and scalability.

Part of the abstraction created by Web Forms is the persistence of data. A hidden input field named __VIEWSTATE can automatically sent the data associated with a page's properties and controls to the server with the HTTP request. View State can grow very large when persisting controls which are bound to large amounts of data such as GridViews or DataGrids. By default View State is turned on, but it can be turned off at various levels: application, program, control. Serializing and deserializing the View State data is part of the page life cycle. View State is not encrypted by default. If you turn on View State encryption for one control, the entire page's View State is encrypted. You can not encrypt just part of a page's View State.

View State data uses Base64 encoding which is a straight translation of binary encoded data to textual data (A-Z,a-z,0-9,+,/). If the View State is not encrypted, anyone can view the HTML source of the page and copy the View State to a View State Decoder and see the data stored in the fields and controls of a page. However to prevent Evil Mike from tampering with the View State in transit, by default ASP.NET performs a Machine Authentication Check (MAC) which appends a hash to the end of the data, and checks it on the receiving end to verify authenticity. Below is a sample of unencrypted View State which is not secure as it can easily be decoded.

__VIEWSTATE
  1. <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUIMzUzOTgwOTAPZBYCAgMPZBYGAgcPDxYCHgRUZXh0BTdQZXJzb24gMTogTmFtZSBpczogS2V2aW4gSGFycmlzIEFnZSBHcm91cDogQiBPcHQgSW46IE5vZGQCCQ8PFgIfAAU4UGVyc29uIDI6IE5hbWUgaXM6IENhdGh5IEhhcnJpcyBBZ2UgR3JvdXA6IEEgT3B0IEluOiBZZXNkZAIODw8WAh8ABTBQZXJzb24gMzogTmFtZSBpczogU3V6eUEgT3B0IEluOiAgQWdlIEdyb3VwOiBZZXNkZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WCQUPY2NQZXJzb24xJHJiWWVzBQ9jY1BlcnNvbjEkcmJZZXMFDmNjUGVyc29uMSRyYk5vBQ9jY1BlcnNvbjIkcmJZZXMFDmNjUGVyc29uMiRyYk5vBQ5jY1BlcnNvbjIkcmJObwURY2NQZXJzb24zSUQkcmJZZXMFEGNjUGVyc29uM0lEJHJiTm8FEGNjUGVyc29uM0lEJHJiTm+0n0a1oHnF/6A0MFxjkDFdWKgQ2xDDRLCeHnSglDZC1Q==" />

In addition to the automatic storage of control data in View State, a programmer can also code the storage of particular items or collections of data be stored in View State. This is discussed future in the next section.

The techniques for persisting data in ASP.NET web applications can be categorized by whether the data is persisted on the client or the server:

  1. Client Side State Management
    1. Cookies - Browser Cookies are dependent upon a Web browser and are typically referred to as simply "cookies". There are however Browser-Independent Cookies (e.g. Flash and Silverlight Cookies) which have different characteristics. Cookies (i.e. Browser Cookies) are small pieces of data stored by the web browser. A cookie stored by one type of browser (e.g. IE) is not accessible by a different browser (e.g. Firefox). Browsers generally enforce the same-origin policy (SOP) and won't accept or send cookies set for a different domain than the request itself. Some browsers contain high-trust zones which circumvent this policy.

      Browser-Independent (BI) Cookies, such as those associated with the browser plugins Flash and Silverlight, are a larger cookie designed to store information about games or online movies. BI cookies do not contain an expiration date and (by default) are not deleted by browsers. Although there are some browser plugins which will allow you to delete BI cookies. Flash and Silverlight have their own interface for removing BI cookies. BI Cookies also do not enforce the SOP policy, so they are also used outside of their designed context and provide a way for advertisers to track the pages being browsed.

      There are third-party cookie schemes which can also allow cookies to be shared across domains, such as Google's DoubleClick (i.e. search for "lawn mower" on Google and then visit various other sites and notice how many advertisements show up for lawn mowers). Another scheme known as "ever cookie" or "zombie cookies" will use a Browser-Independent Cookie (or some other data file), to recreated Browser Cookies after they have been deleted. "Super Cookies" can use various methods to hide themselves, prevent themselves from being deleted, and track users across domains.

      The first browser to use cookies was Mosaic Netscape in 1994 with support for cookies integrated in Internet Explorer in 1995. Those browsers accepted cookies by default and it wasn't until the 1996 Financial Times article that the general public learned about the use of cookies. The public expressed concerns about the privacy and security of cookies, leading to U.S. Federal Trade Commission hearings in 1996 and 1997. Over the years the Internet Engineering Task Force (IETF) has created various specifications for the implementation of cookies. However these specifications have not always been followed. There is a great variation in the support of cookies on mobile devices. In the UK 94% of wireless devices support cookies where in the US only 47% support them. Some gateways (Verizon, Alltel) strip out cookies.

      A cookie is created by a script which sends a response with cookie headers. Then the browser stores that cookie data and sends it back to the server, in the headers, on every request. Typical uses of cookies are:

      1. Persistent or Tracking Cookies - store user preferences or pages visited. On E-commerce sites can be used to implement shopping carts or quick-checkout options.

      2. Session Cookies - store information about page activities so server knows where to pick up an existing session.

      3. Authentication Cookies - an encrypted token indicating that the user has already been authenticated in your application.

      Advantages: simple implementation, configurable expiration, most durable form of data persistence on the client, no server resources required.

      Disadvantages: size limitations imposed by browser (4096/8192 bytes), users can set their browser to disable cookies, can be tampered with.

      Recommended Use: Use when you need to store small amounts of information on the client and security is not an issue (cookies are vulnerable to the man-in-the-middle exploit).

      The following code writes and reads a simple browser cookie which has a 5 minute expiration date.

      WriteCookie.aspx.cs
      1. using System;
      2. using System.Collections.Generic;
      3. using System.Linq;
      4. using System.Web;
      5. using System.Web.UI;
      6. using System.Web.UI.WebControls;
      7.  
      8. namespace Cookie
      9. {
      10. public partial class WriteCookie : System.Web.UI.Page
      11. {
      12. protected void Page_Load(object sender, EventArgs e)
      13. {
      14. if (IsPostBack)
      15. {
      16. lnkReadCookie.Visible = true;
      17. lnkReadCookie.NavigateUrl = "ReadCookie.aspx?cookieName=" + tbxCookieName.Text.ToString();
      18. }
      19. }
      20.  
      21. protected void btnWriteCookie_Click(object sender, EventArgs e)
      22. {
      23. HttpCookie theCookie = new HttpCookie(tbxCookieName.Text);
      24. theCookie.Value = tbxCookieValue.Text;
      25.  
      26. DateTime dtCurrent = DateTime.Now;
      27. TimeSpan tsMinutes = new TimeSpan(0, 0, 5, 0);
      28. theCookie.Expires = dtCurrent + tsMinutes;
      29.  
      30. Response.Cookies.Add(theCookie);
      31. Response.Write("Cookie: " + tbxCookieName.Text + " was written. <br>");
      32. }
      33. }
      34. }


      ReadCookie.aspx.cs
      1. using System;
      2. using System.Collections.Generic;
      3. using System.Linq;
      4. using System.Web;
      5. using System.Web.UI;
      6. using System.Web.UI.WebControls;
      7.  
      8. namespace Cookie
      9. {
      10. public partial class ReadCookie : System.Web.UI.Page
      11. {
      12. protected void Page_Load(object sender, EventArgs e)
      13. {
      14. String cookieName = Request.QueryString["cookieName"].ToString();
      15.  
      16. HttpCookie theCookie = Request.Cookies[cookieName];
      17.  
      18. if (theCookie == null)
      19. {
      20. lblCookieValue.Text = "No Cookie Found";
      21. }
      22. else
      23. {
      24. lblCookieValue.Text = "Cookie Value is: " + theCookie.Value.ToString();
      25. }
      26. }
      27. }
      28. }


    2. Hidden Fields - hidden input fields are HTML <input> elements with their type set to "hidden". The data in the hidden fields are not rendered to the screen, but it can be seen by viewing the source code after the page is rendered. Hidden fields are not secure for storing sensitive data and can easily be manipulated by man-in-the-middle exploits. However, unlike View State, Session State, and Cookies, hidden fields are always available, even when cookies have been turned off at the browser.

      By default, view state is actually stored in a hidden field. However, when rendered, the view state is shown in the source code as base64 encoded text. Further view state can be encrypted. In addition, view state has built in protections to detect data tampering. A hash of the view state data is created from the data by using a machine authentication code (MAC) key. The hash value is added to the encoded view state data and the resulting string is stored in the page. When the page is posted back to the server, the ASP.NET page framework re-computes the hash value and compares it with the value stored in view state. If the hash values do not match, an exception is raised that indicates that view state data might be invalid.

      ASP.NET contains supports the HTML hidden field HtmlControls.HtmlInputHidden and the Server Control hidden field WebControls.HiddenField. They both render to a similar <input> html element. However unlike the HTML control, the server control can be easily accessed in the code behind by using its ID. Web.UI.HtmlControls (HTML controls) are just a thin wrapper around actual HTML controls. The Web.UI.WebControls (Web Controls) namespace contains classes, which execute on the server, to create HTML server controls on a Web Forms page. Web Controls can be more powerful, be browser aware, and may actually map to several HTML elements with JavaScript.

      Advantages: simple implementation, widely supported, no server resources required.

      Disadvantages: easily tampered with, does not support rich data types, proxies and firewalls may impose a limit to the amount of data stored in hidden fields.

      Below is a comparison of the hidden field elements for the HTML and Web controls, and how they are rendered in the HTML source code.

      Code Snippet
      1. <%--Web Control Hidden Field--%>
      2. <asp:HiddenField ID="ASPHiddenField" runat="server" Value="AA" />
      3.  
      4. <%--Renders AS--%>
      5. <input type="hidden" id="Hidden1" name="ASPHiddenField" value="AA" />
      6.  
      7.  
      8.  
      9. <%--Standard HTML Hidden Field--%>
      10. <input id="HTMLHiddenField" type="hidden" value="BB"/>
      11.  
      12. <%--Renders AS--%>        
      13. <input type="hidden" id="Hidden2" value="BB"/>


    3. Query Strings - information that is appended to the end of a page URL.
    4. Advantages: simple implementation, wide support, no server resources required.
      Disadvantages: directly viewable by users, subject to tampering, limited capacity (2083 characters).
      Recommended Use: Use when you are transferring small amounts of information from one page to another and security is not an issue.

    5. View State -
    6. Recommended Use: Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.

    7. Control State - stores custom control data between server trips.
    8. Recommended Use: Use when you need to store small amounts of state information for a control between round trips to the server.

  2. Server Side State Management
    1. Session State - servers have the concept of a "session," which is a collection of data associated with a single user's interactions with the site.
      Advantages: simple implementation, limited to session managed events, data can be preserved during IIS restarts and worker-process restarts (because session data is stored in another process space), scalability, can be supported even when cookies or turned off on the browser (although typically configured to require cookies), can be modified and extended to create custom session-state providers.

      Disadvantages: session-state variables stay in server memory until removed or replaced, so they can degrade server performance. Session-state variables with large amounts of data (e.g datasets) can adversely affect web server performance.

    2. Application State -

      Advantages: simple implementation, persists data during entire execution of application.

      Disadvantages: act a global variables which can be accessed by any part of application, can be lost if server process is disturbed, consumes server memory.


AJAX

Asynchronous JavaScript and XML (AJAX) is a group of technologies used together to allow selected portions of the web page to be refreshed (partial-page rendering), instead of requiring a full screen refresh. Even though the "X" in AJAX stands for XML, it is now more common to use JavaScript Object Notation (JSON) as part of partial page updates than it is XML. Two common optional technologies used as part of AJAX to identify resources on the server, and retrieve data from the server back to the client are Representational State Transfer (REST) or Web Services. Both REST and Web services can serve up JSON or XML data.

AJAX depends upon the XMLHttpRequest JavaScript object which allows browsers to make asynchronous calls back-and-forth between the browser and the server. JavaScript is needed to trigger the request for data, and to get the data back and work with it. The partial-page data is typically transferred in JSON or XML format. The following is a quote from the Mozilla Developer Network site:

XMLHttpRequest is a JavaScript object that was designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now being standardized in the W3C. It provides an easy way to retrieve data from a URL without having to do a full page refresh. A Web page can update just a part of the page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming. Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).

In ASP.NET the built-in AJAX controls are:

  1. ScriptManager - a required control whose primary purpose is to load the scripts needed to allow AJAX to work with a page. It must be added before any other AJAX controls in the page. It is needed to load both Microsoft's scripts that are needed for AJAX to function and custom scripts which the developer may create (as an alternative to the standard script tag). It supports debug and release version (i.e. minified versions) of scripts. The ScriptManager coordinates all the various AJAX calls on a page. To differentiate between a full page post back (Page.IsPostBack), the ScriptManager contains the IsInAsyncPostBack property. It is sometimes useful to temporarily turn off partial page post backs when debugging by setting the ScriptManager's property EnablePartialRendering to false.

  2. UpdatePanel - is the control you wrap around the portion of the page you wish to be part of a partial update.
    Placing controls inside an UpdatePanel control enables you to refresh selected parts of the webpage instead of refreshing the entire page with a postback to the webserver. UpdatePanel controls can be nested (with child-parent relationships) and there is no limit to the number of UpdatePanel controls that can be on a page. Each UpdatePanel is updated individually (and asynchronously) without affecting other UpdatePanels or any other page elements. When a controls is inside an UpdatePanel, it will by default cause the partial-page rendering. If you wish to have controls outside the UpdatePanel cause the partial-page rendering, the Triggers tag of the UpdatePanel can be used to specify the control and its event. Triggers are also useful in scenarios where the selection in one GridView updates the data in another GridView.

  3. UpdateProgress - is useful to provide text or a graphic visual that shows that an asynchronous partial-page rendering is occurring. Put the UpdateProgress control inside the UpdatePanel and it will display during the update. UpdateProgress controls can be associated with a different UpdatePanel controls or one UpdateProgress control can be associated with all the UpdatePanel controls on a page. Properties of the UpdateProgress control include DisplayAfter which specifies the number of milliseconds to wait before displaying the inidicator, and DynamicLayout which specifies if the indicator should take up screen space even when not visible. The site ajaxload.info allows you to generate a number of custom animated .gif files to use as progress indicators.

  4. ScriptManagerProxy - useful when you have a ScriptManager in a master page, but then in the individual content page you wish to load separate scripts. When AJAX is used extensively throughout a site, the ScriptManager may be added to the master page(s) so it does not have to be added individually on each page which used AJAX.

  5. Timer - used to trigger AJAX calls on a timed based. The Timer control enables you to perform postbacks at a specified interval. It can be used to trigger automatic updates to an area of the page that is wrapped with an UpdatePanel.

The AJAX Control Toolkit is an ASP.NET open-source project built on top of the ASP.NET AJAX framework. The Ajax Control Toolkit contains many controls which provide for a highly responsive and interactive Web application. The AJAX Control Toolkit can be downloaded into a project using Visual Studio's integrated NuGet Package Manager. One of the popular controls is the Accordion Control which manages content into expandable panes which can be clicked to show the content of one pane while hiding the content of all the other panes. A few of the other popular controls from the AJAX Control Toolkit include:

  1. ModalPopup
  2. AsyncFileUpload
  3. ConfirmButton
  4. CollapsiblePanel
  5. CascadingDropDown
  6. CalendarExtender
  7. AutoComplete
  8. HTML Editor Extender
  9. ColorPicker
  10. Slider
  11. ListSearch
  12. MaskedEdit
  13. SlideShow
  14. Watermark

Data Validation in Web Forms

Web Forms contain data validation controls which create the JavaScript to validate data on the client side and also can also perform the same validation on the server side. Validation on the client side can easily be bypassed by a malicious user, so security requires validation be performed on the server side. Client side validation is turn on by default, but it can be turned off at the control level by setting the property EnableClientScript="false". To use server-side validation only requires using the Page.Validate() method. The Web Forms data validation control include:

  1. RequiredFieldValidator - checks for a required entry.
  2. CompareValidator - compares control values and data types (e.g. valid date).
  3. RangeValidator - checks a value is within a certain range.
  4. RegularExpressionValidator - uses pattern matching to validate value.
  5. CustomValidator - uses custom JavaScript to have control perform validation.
  6. ValidationSummary - consolidates all the validation messages into one area.

The following example uses both client side and server side validation. It also set the default button in the form tag. The default focus can be set either in the form tag or in program code.

WebForm1.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7. <title></title>
  8. <style type="text/css">
  9. .style1
  10. {
  11. width: 100%;
  12. }
  13. .style2
  14. {
  15. width: 89px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <form id="form1" defaultButton = "btnSubmit" defaultFocus="tbxName" runat="server">
  21. <div>
  22. <table class="style1">
  23. <tr>
  24. <td class="style2">
  25. Name:</td>
  26. <td>
  27. <asp:TextBox ID="tbxName" runat="server" ValidationGroup="t1" Width="128px"></asp:TextBox>
  28. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  29. ControlToValidate="tbxName" ErrorMessage="Name is required."
  30. ValidationGroup="t1" SetFocusOnError="True">*</asp:RequiredFieldValidator>
  31. </td>
  32. </tr>
  33. <tr>
  34. <td class="style2">
  35. Date:</td>
  36. <td>
  37. <asp:TextBox ID="tbxDate" runat="server" ValidationGroup="t1"></asp:TextBox>
  38. <asp:CompareValidator ID="CompareValidator1" runat="server"
  39. ControlToValidate="tbxDate" ErrorMessage="Enter a valid date."
  40. Operator="DataTypeCheck" Type="Date" ValidationGroup="t1"
  41. SetFocusOnError="True">*</asp:CompareValidator>
  42. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
  43. ControlToValidate="tbxDate" ErrorMessage="Please enter a date."
  44. ValidationGroup="t1" SetFocusOnError="True">*</asp:RequiredFieldValidator>
  45. </td>
  46. </tr>
  47. <tr>
  48. <td class="style2">
  49. Email:</td>
  50. <td>
  51. <asp:TextBox ID="tbxEmail" runat="server" ValidationGroup="t1"></asp:TextBox>
  52. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
  53. ControlToValidate="tbxEmail" ErrorMessage="Enter a valid email address."
  54. ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
  55. ValidationGroup="t1" SetFocusOnError="True">*</asp:RegularExpressionValidator>
  56. </td>
  57. </tr>
  58. <tr>
  59. <td class="style2">
  60. &nbsp;</td>
  61. <td>
  62. <asp:ValidationSummary ID="ValidationSummary1" runat="server"
  63. ValidationGroup="t1" />
  64. <br />
  65. <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
  66. Text="Click Me" ValidationGroup="t1" />
  67. </td>
  68. </tr>
  69. <tr>
  70. <td class="style2">
  71. &nbsp;</td>
  72. <td>
  73. <asp:Label ID="lblOutput" runat="server" Text=" "></asp:Label>
  74. </td>
  75. </tr>
  76. </table>
  77. </div>
  78. </form>
  79. </body>
  80. </html>


WebForm1.aspx.cs
  1. using System;
  2.  
  3. namespace WebApplication4
  4. {
  5. public partial class WebForm1 : System.Web.UI.Page
  6. {
  7. protected void Page_Load(object sender, EventArgs e)
  8. {
  9. }
  10.  
  11. protected void btnSubmit_Click(object sender, EventArgs e)
  12. {
  13. Page.Validate(); // Perform server side validation
  14. if (Page.IsValid)
  15. {
  16. lblOutput.Text = "Name is: " + tbxName.Text + " Date is: " + tbxDate.Text;
  17. }
  18. }
  19. }
  20. }


User Controls

User Controls are custom, reusable, composite controls you can create to embed in an ASP.NET Web page. User Controls can contain properties and methods in such a way that the individual controls within a user control act as a unit. User controls have the following characteristics:

  • The UI declaration of a user control is created in a file with an .ascx extension while the code portion of a user control is created in a file with an .ascx.cs (for C#) extension.
  • User controls are added to .aspx pages by using the $lt;%@ Register %$gt; directive.
  • You can define properties and methods for a user control the same way you do for a page. By defining a property for a user control, you make it possible to set its properties declaratively and in code.
  • When a user control contains Web server controls, you can write code in the user control to handle the events raised by the child controls. For example, if your user control contains a Button control, you can create a handler in the user control for the button's Click event. By default, events raised by child controls in a user control are not available to the host page. However, you can define events for your user control and raise them so that the host page is notified of the event. You do this in the same way that you define events for any class.

The following code creates a custom control with two static declarations and one dynamic declaration.

MyCustomControl.ascx
  1. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyCustomControl.ascx.cs" Inherits="WebApplication4.UserControls.MyCustomControl" %>
  2. <style type="text/css">
  3. .style1
  4. {
  5. width: 100%;
  6. }
  7. .style2
  8. {
  9. width: 96px;
  10. }
  11. </style>
  12.  
  13. <table class="style1">
  14. <tr>
  15. <td class="style2">
  16. Name:</td>
  17. <td>
  18. <asp:TextBox ID="tbxName" runat="server"></asp:TextBox>
  19. </td>
  20. </tr>
  21. <tr>
  22. <td class="style2">
  23. Age Group:</td>
  24. <td>
  25. <asp:DropDownList ID="ddlAge" runat="server">
  26. <asp:ListItem Value="A">0-30</asp:ListItem>
  27. <asp:ListItem Value="B">31-60</asp:ListItem>
  28. <asp:ListItem Value="C">61-90</asp:ListItem>
  29. </asp:DropDownList>
  30. </td>
  31. </tr>
  32. <tr>
  33. <td class="style2">
  34. Opt In:</td>
  35. <td>
  36. <asp:RadioButton ID="rbYes" runat="server" GroupName="yesno" Text="Yes" />
  37. <asp:RadioButton ID="rbNo" runat="server" GroupName="yesno" Text="No" />
  38. </td>
  39. </tr>
  40. </table>


MyCustomControl.ascx.cs
  1. using System;
  2. using System.Web.UI.WebControls;
  3.  
  4. namespace WebApplication4.UserControls
  5. {
  6. public partial class MyCustomControl : System.Web.UI.UserControl
  7. {
  8.  
  9. public TextBox FirstName
  10. {
  11. get { return tbxName; }
  12. set { tbxName = value; }
  13. }
  14.  
  15. protected void Page_Load(object sender, EventArgs e)
  16. {
  17.  
  18. }
  19. }
  20. }


WebForm1.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
  2.  
  3. <%@ Register src="UserControls/MyCustomControl.ascx" tagname="MyCustomControl" tagprefix="uc1" %>
  4.  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6.  
  7. <html xmlns="http://www.w3.org/1999/xhtml">
  8. <head runat="server">
  9. <title></title>
  10. <style type="text/css">
  11. .style1
  12. {
  13. width: 100%;
  14. }
  15. .style2
  16. {
  17. width: 89px;
  18. }
  19. .style5
  20. {
  21. width: 14px;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <form id="form1" defaultButton = "btnSubmit" defaultFocus="tbxName" runat="server">
  27. <div>
  28. <table class="style1">
  29. <tr>
  30. <td class="style5">
  31. &nbsp;</td>
  32. <td>
  33. Person 1</td>
  34. </tr>
  35. <tr>
  36. <td class="style5">
  37. &nbsp;</td>
  38. <td>
  39. <uc1:MyCustomControl ID="ccPerson1" runat="server" />
  40. </td>
  41. </tr>
  42. <tr>
  43. <td class="style5">
  44. &nbsp;</td>
  45. <td>
  46. Person 2</td>
  47. </tr>
  48. <tr>
  49. <td class="style5">
  50. &nbsp;</td>
  51. <td>
  52. <uc1:MyCustomControl ID="ccPerson2" runat="server" />
  53. </td>
  54. </tr>
  55. <tr>
  56. <td class="style5">
  57. &nbsp;</td>
  58. <td>
  59. <asp:Button ID="btnSubmit" runat="server" Text="Submit"
  60. onclick="btnSubmit_Click" />
  61. </td>
  62. </tr>
  63. <tr>
  64. <td class="style5">
  65. &nbsp;</td>
  66. <td rowspan="1">
  67. <asp:Label ID="lblOutput1" runat="server" Text=" "></asp:Label>
  68. </td>
  69. </tr>
  70. <tr>
  71. <td class="style5">
  72. &nbsp;</td>
  73. <td rowspan="1">
  74. <asp:Label ID="lblOutput2" runat="server" Text=" "></asp:Label>
  75. </td>
  76. </tr>
  77.  
  78. </table>
  79.  
  80. <%--Place Holder for Dynamically Adding User Control--%>
  81. <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
  82. <br />
  83. <asp:Label ID="lblOutput3" runat="server" Text=""></asp:Label>
  84. </div>
  85. </form>
  86. </body>
  87. </html>


WebForm1.aspx.cs
  1. using System;
  2. using System.Web.UI.WebControls;
  3. using WebApplication4.UserControls;
  4.  
  5. namespace WebApplication4
  6. {
  7. public partial class WebForm1 : System.Web.UI.Page
  8. {
  9. protected void Page_Load(object sender, EventArgs e)
  10. {
  11. // Dynamically Load User Control
  12. var ccPerson3 = Page.LoadControl("~/UserControls/MyCustomControl.ascx");
  13. ccPerson3.ID = "ccPerson3ID";
  14. PlaceHolder1.Controls.Add(ccPerson3);
  15. }
  16.  
  17. protected void btnSubmit_Click(object sender, EventArgs e)
  18. {
  19. TextBox theTextBox1 = (TextBox)ccPerson1.FindControl("tbxName");
  20. DropDownList theDropDownList1 = (DropDownList) ccPerson1.FindControl("ddlAge");
  21. RadioButton theRadioButton1 = (RadioButton) ccPerson1.FindControl("rbYes");
  22. lblOutput1.Text = "Person 1: Name is: " + theTextBox1.Text + " Age Group: " +
  23. theDropDownList1.SelectedValue + " Opt In: " +
  24. (theRadioButton1.Checked ? "Yes" : "No");
  25.  
  26. TextBox theTextBox2 = (TextBox)ccPerson2.FindControl("tbxName");
  27. DropDownList theDropDownList2 = (DropDownList)ccPerson2.FindControl("ddlAge");
  28. RadioButton theRadioButton2 = (RadioButton)ccPerson2.FindControl("rbYes");
  29. lblOutput2.Text = "Person 2: Name is: " + theTextBox2.Text + " Age Group: " +
  30. theDropDownList2.SelectedValue + " Opt In: " +
  31. (theRadioButton2.Checked ? "Yes" : "No");
  32.  
  33. if (PlaceHolder1.HasControls())
  34. {
  35. TextBox theTextBox3 = (TextBox)PlaceHolder1.FindControl("ccPerson3ID").FindControl("tbxName");
  36. DropDownList theDropDownList3 = (DropDownList)PlaceHolder1.FindControl("ccPerson3ID").FindControl("ddlAge");
  37. RadioButton theRadioButton3 = (RadioButton)PlaceHolder1.FindControl("ccPerson3ID").FindControl("rbYes");
  38. //lblOutput3.Text = "Person 3: Name is: " + theTextBox3.Text + " Age Group: " +
  39. // theDropDownList3.SelectedValue + " Opt In: " +
  40. // (theRadioButton3.Checked ? "Yes" : "No");
  41. lblOutput3.Text = "Person 3: Name is: " + theTextBox3.Text +
  42. theDropDownList3.SelectedValue + " Opt In: " + " Age Group: " +
  43. (theRadioButton3.Checked ? "Yes" : "No");
  44. }
  45. }
  46. }
  47. }


MVC

ASP.NET MVC is an implementation of the Model-View-Controller pattern for ASP.NET. MVC is an alternative to Web Forms for creating Web applications. MVC is an architectural pattern which separates an application into three main components: the model, the view, and the controller. MVC provides a separation of concerns which provides loose coupling between the input logic, business logic, and UI logic. MVC does not use view state or server-based controls. MVC provides for routing ,better support for test-driven development, and support for the existing ASP.NET features (authentication, caching, session state management, health monitoring, etc.).

Web Pages

Web Pages are just small php-like (with Razor) script files which turn out html ASP.NET Web Pages is a (currently) the latest flavor that is targeted at smaller project and beginner devs (at least in my opinion). It is good for developing smaller projects with ~ 10 pages. Most of the logic is written in a single file per page in what I call "Basic PHP style". It uses the Razor syntax for injecting the server-side code.

One ASP.NET

In ASP.NET, one is a crowd. One ASP.NET was introduced in Visual Studio 2013 as an integration of multiple ASP.NET technologies in a single project. The unified project system allows the building of an application using a combination of ASP.NET technologies in one project. Prior versions of Visual Studio required you pick one technology, such as either Web Forms or MVC, and use only that one technology throughout the project.

Versions of Visual Studio prior to 2013 contained various types of ASP.NET technologies such as Web Forms, MVC, Web Site Projects, and Web Application Projects. Visual Studio 2013 has only one type of Web project called: ASP.NET Web Application. When creating this type of project you select a template and then select multiple core references (Web Forms, MVC, and Web API). You do not have to select the core reference when creating the project. For example, you can start a project using Web Forms and then add MVC at a later time.

,One ASP.NET


Visual Studio 2013
Integration of Multiple ASP.NET Technologies in a Single Project Type.

Deployment of Web Applications

There are different versions of the IIS (Internet Information Services) web server which are used by developers. Production web servers run the version of IIS associated with the server operating system. Development environments run versions which can differ from the production server, in order of least difference:

  1. Local IIS - IIS installed on local computer. (Requires admin permissions).
  2. IIS Express - Default development web server for Visual Studio 2015, 2013, 2012, 2010 SP1.
    IIS Express is more similar to IIS than previous development web servers. IIS Express is installed automatically when you install Visual Studio 2012, 2013, 2015.
  3. Cassini - Default development web server for Visual Studio and Visual Web Developer 2010, 2008. Option in VS 2012. Removed from VS 2013.

VS 2010 SP1 supports both IIS Express and Cassini (VS 2010 supports only cassini). You can configure your project to use IIS Express or Cassini. By default VS 2010 SP1 uses Cassini and to change right click on your web site/web application and select "use iis express". When IIS Express is running, these is an IIS Express tray icon which will show all the running sites.

Internet Information Services Releases and Windows Versions
Windows Version IIS Version
Windows Server 2016
Windows 10
IIS 10
Windows Server 2012 R2
Windows 8.1
IIS 8.5
Windows Server 2012
Windows 8
IIS 8.0
Windows Server 2008 R2
Windows 7 (Home Premium, Professional, Enterprise, and Ultimate editions)
IIS 7.5
Windows Server 2008
Windows Vista (Home Premium, Business, Enterprise, and Ultimate editions)
IIS 7.0
Windows Server 2003
Windows XP Professional x64
IIS 6.0

Installing and Running Internet Information Services

  1. Prepare local web server IIS (Internet Information Services) and deploy web site to local server.
    1. In Control Panel, under "Windows Features" turn on "Internet Information Services". Be sure that under "Application Development Features" that "ASP.NET" is checked.
    2. Once IIS is installed, type: "http://localhost/" and verify the IIS banner screen displays.
  2. Integrate IIS with versions of Visual Studios installed prior to the IIS installations.
    1. If running installing a version of IIS prior to 8.0, after Visual Studio was already installed, run the ASP.NET Administration Utility to install the .NET framework under IIS by entering "aspnet_regiis.exe -I" in a command shell. Note, the ASoft .NET Version Detector utility will show the installed versions of the .NET Framework on the computer (instead of the traditional method of looking the registry with regedit).
  3. Manually deploy a project to local web server (this copies more files than is really needed, such as the source code files).
    1. Copy your project folder into the "inetpub\wwwroot" folder. Copy project folder a level above the solution file. Projects can be set up under other folders, but the "inetpub\wwwroot" folder has permissions set up correctly, so other folders may require permission updates.
    2. Next build an application on top of the folder just copied. right-click on folder and "Add Application" or "Convert to an Application". Check contents of website folder in IIS, then browser website in IIS.
    3. It may be necessary to configure other setting, such as the application pool, to view site. The application pools are a mapping onto worker processes in IIS that determine the identity and security rights of a particular application. One example is, if using a local database server, to change the "Load User Profile" setting of the application pool to "True" to grant the necessary permissions.
  4. Alternative Deployment Method - Automated Deployment (Preferred Deployment Method)
    1. For IIS versions less than 8.0i nside IIS, right click on web server in the connections tree view and select "Deploy".
    2. For IIS versions 8.0 and greater, user the "Microsoft Web Platform Installer" tool.
    3. Inside Visual Studio, go to project properties, then Package/Publish Web.
,.Net Version Detector Utility


.NET Versions Installed
ASoft .Net Version Detector Utility

Error | ASP.NET Developer

Error

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/common.inc:2748) in drupal_send_headers() (line 1232 of /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/bootstrap.inc).
  • PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user '1218369_b2cf'@'185.176.40.58' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => cron [:db_insert_placeholder_2] => Attempting to re-run cron while it is already running. [:db_insert_placeholder_3] => a:0:{} [:db_insert_placeholder_4] => 4 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.kcshadow.net/aspnet/ [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 54.198.41.76 [:db_insert_placeholder_9] => 1534839433 ) in dblog_watchdog() (line 160 of /srv/disk9/1218369/www/kcshadow.net/aspnet/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.