Thursday, February 19, 2009

Windows Presentation Foundation

he architecture of Windows Presentation Foundation spans across both managed code and native code components. However, the public API exposed is only available via managed code. While the majority of WPF is in managed code, the composition engine which renders the WPF applications is a native component. It is named Media Integration Layer (MIL) and resides in milcore.dll. It interfaces directly with DirectX and provides basic support for 2D and 3D surfaces, timer-controlled manipulation of contents of a surface with a view to exposing animation constructs at a higher level, and compositing the individual elements of a WPF application into a final 3D "scene" that represents the UI of the application and renders it to the screen.[5][6] The media codecs are also implemented in unmanaged code, and are shipped as windowscodecs.dll.[5] In the managed world, PresentationCore (presentationcore.dll) provides a managed wrapper for MIL and implements the core services for WPF,[5] including a property system that is aware of the dependencies between the setters and consumers of the property, a message dispatching system by means of a Dispatcher object to implement a specialized event system and services which can implement a layout system such as measurement for UI elements.[6] PresentationFramework (presentationframework.dll) implements the end-user presentational features, including layouts, time-dependent, story-board based animations, and data binding.[6]

WPF exposes a property system for objects which inherit from DependencyObject, that is aware of the dependencies between the consumers of the property, and can trigger actions based on changes in properties. Properties can be either hard coded values or expressions, which are specific expressions that evaluate to a result. In the initial release, however, the set of expressions supported is closed.[6] The value of the properties can be inherited from parent objects as well. WPF properties support change notifications, which invoke bound behaviors whenever some property of some element is changed. Custom behaviors can be used to propagate a property change notification across a set of WPF objects. This is used by the layout system to trigger a recalculation of the layout on property-changes, thus exposing a declarative programming style for WPF, whereby almost everything, from setting colors and positions to animating elements can be achieved by setting properties.[6] This allows WPF applications to be written in XAML, which is a declarative mark-up language, by binding the keywords and attributes directly to WPF classes and properties.

The UI elements of an WPF application are maintained as a class of Visual objects. Visual objects provide a managed interface to a composition tree which is maintained by Media Integration Layer (MIL). Each element of WPF creates and adds one or more composition nodes to the tree. The composition nodes contain rendering instructions, such as clipping and transformation instructions, along with other visual attributes. Thus the entire application is represented as a collection of composition nodes, which are stored in a buffer in the system memory. Periodically, MIL walks the tree and executes the rendering instructions in each node, thus compositing each element on to a DirectX surface, which is then rendered on screen. MIL uses the painter's algorithm, where all the components are rendered from back of the screen to the front, which allows complex effects like transparencies to be easily achieved. This rendering process is hardware accelerated using the GPU.[6] The composition tree is cached by MIL, creating a retained mode graphics, so that any changes to the composition tree needs only to be incrementally communicated to MIL. This also frees the applications of managing repainting the screen, MIL can do that itself as it has all the information necessary. Animations can be implemented as time-triggered changes to the composition tree. On the user visible side, animations are specified declaratively, by setting some animation effect to some element via a property and specifying the duration. The code-behind updates the specific nodes of the tree, via Visual objects, to represent both the intermediate states at specified time intervals as well as the final state of the element. MIL will render the changes to the element automatically.

All WPF applications start with two threads: one for managing the UI and another background thread for handling rendering and repainting.[7] Rendering and repainting is managed by WPF itself, without any developer intervention. The UI thread houses the Dispatcher (via an instance of DispatcherObject), which maintains a queue of UI operations that need to be performed (as a tree of Visual objects), sorted by priority. UI events, including changing a property that affects the layout, and user interaction events raised are queued up in the dispatcher, which invokes the handlers for the events. Microsoft recommends that the event handlers only update the properties to reflect new content for application responsiveness; the new content be generated or retrieved in a background thread.[7] The render thread picks up a copy of the visual tree and walks the tree calculating which components will be visible and renders them to Direct3D surfaces. The render thread also caches the visual tree, so only changes to the tree need to be communicated, which will result in updating only the changed pixels. WPF supports an extensible layout model. Layout is divided into two phases: Measure and Arrange. The Measure phase recursively calls all elements and determine the size they will take. In the Arrange phase, the child elements are recursively arranged by their parents, invoking the layout algorithm of the layout module in use.[6][8]

Features

The following is a partial list of WPF features.

Graphical Services

* All graphics (including desktop items like windows) are Direct3D applications.
o This aims to provide a unified avenue for displaying graphics, as well as more advanced graphical features.
o Routing the graphics through Direct3D allows Windows to offload some graphics tasks to the Graphics Processing Unit found on the computer's graphics card. This can reduce the workload on the computer's Central processing unit.
o Supports vector-based graphics, which allow lossless scaling.
o Supports 3D model rendering and interaction in 2D applications.
o Interactive 2D content can be overlaid on 3D surfaces, natively.[9]

Interoperability

* WPF provides interoperability with the Windows API: Via hosting, one can use Windows Presentation Foundation inside existing Win32 code, or one can use existing Win32 code inside Windows Presentation Foundation.[10]
* Interoperability with Windows Forms is also possible through the use of the ElementHost and WindowsFormsHost classes.

Media Services

* WPF provides shape primitives for 2D graphics along with a built-in set of brushes, pens, geometries, and transforms.
* The 3D capabilities in WPF are a subset of the full feature set provided by Direct3D. However, WPF provides tighter integration with other features like user interface (UI), documents, and media. This makes it possible to have 3D UI, 3D documents, and 3D media.
* There is support for most common image formats.
* WPF supports the video formats WMV, MPEG and some AVI files by default, but since it is Windows Media Player running beneath, WPF can use all the codecs installed for it.
* WPF supports time-based animations, in contrast to the frame-based approach. This decouples the speed of the animation from how the system is performing.

Animations

* Time-based animation. Scene redraws are time triggered.[11]
* Presentation timers are initialized and managed by WPF.[11]
* Scene changes co-ordinated by using a storyboard.[11]. An example of animating a storyboard from C# is here.
* Animations can be triggered by other external events, including user action.[11]
* Animation effects can be defined on a per-object basis, which can be accessed directly from XAML markup.[11]
* Ships with a set of predefined effects, such as fade out for all controls.[11]

Data binding

* WPF has a built-in set of data services to enable application developers to bind and manipulate data within applications. There exists support for three types of data binding:
o one time: where the client ignores updates on the server.
o one way: where the client has read-only access to data.
o two way: where client can read from and write data to the server.
* LINQ queries, specifically LINQ to XML, can also act as data sources for data binding.[9]
* Binding of data has no bearing on its presentation. WPF provides data templates to control presentation of data.

* A set of built-in controls is provided as part of WPF, containing items such as button, menu, grids and list box.
* A powerful concept in the WPF is the logical separation of a control from its appearance.
o A control's template can be overridden to completely change its visual appearance.
o A control can contain any other control or layout, allowing for unprecedented control over composition.
* Features retained mode graphics, so that applications do not have to be bothered with repainting the display.



* Annotations can be applied on a per-object basis, for objects in a Document or FlowDocument.
* WPF only provides the capability for creating, storing and managing annotations; each application must expose the UI on their own.



* WPF can natively access Windows Imaging Component (WIC) code and APIs allowing developers to write image codecs for their specific image file formats.



* WPF provides for bitmap effects, however, they are rendered in hardware only in .NET Framework 3.5 SP1 or newer. GPU features like pixel shaders are not used for bitmap effects.
* Special effects such as dropshadows and blurring are built in.



* WPF natively supports paginated documents. It provides the DocumentReader class, which is for reading fixed layout documents. The FlowDocumentReader class offers different view modes such as per-page or scrollable and also reflows text if the viewing area is re sized.
* Natively supports XML Paper Specification documents.
* Supports reading and writing paginated documents using Open Packaging Convention.



WPF includes a number of typographic and text rendering features that were not available in GDI. This is the first Windows programming interface to expose OpenType features to software developers, supporting both OpenType, TrueType, and OpenType CFF (Compact Font Format) fonts.

Support for OpenType typographic features includes:

* Ligatures
* Old-style numerals (for example, parts of the glyph hang below the text baseline)
* Swash variants
* Fractions
* Superscript and Subscript
* Small caps
* Line-level justification
* Ruby characters.
* Glyph substitution
* Multiple baselines
* Contextual and Stylistic Alternates
* Kerning

WPF handles texts in Unicode, and handles texts independent of global settings, such as system locale. In addition, fallback mechanisms are provided to allow writing direction (horizontal versus vertical) handled independent of font name; building international fonts from composite fonts, using a group of single-language fonts; composite fonts embedding. Font linking and font fallback information is stored in a portable XML file, using composite font technology.[12] The XML file has extension .CompositeFont.

The WPF text engine also supports built-in spell checking. It also supports such features as automatic line spacing, enhanced international text, language-guided line breaking, hyphenation, and justification, bitmap effects, transforms, and text effects such as shadows, blur, glow, rotation etc. Animated text is also supported; this refers to animated glyphs, as well as real-time changes in position, size, color, and opacity of the text.

WPF text rendering takes advantage of advances in ClearType technology, such as sub-pixel positioning, natural advance widths, Y-direction anti-aliasing, hardware-accelerated text rendering, as well as aggressive caching of pre-rendered text in video memory.[13] ClearType cannot be turned off in WPF applications.[14] Unlike the ClearType in GDI or GDI+, WPF ClearType does not snap glyphs to pixels horizontally, leading to a loss of contrast disliked by some users. [15]

The extent to which glyphs are cached is dependent on the video card. DirectX 10 cards are able to cache the font glyphs in video memory, then perform the composition (assembling of character glyphs in the correct order, with the correct spacing), alpha-blending (application of anti-aliasing), and RGB blending (ClearType's sub-pixel color calculations), entirely in hardware. This means that only the original glyphs need to be stored in video memory once per font (Microsoft estimates that this would require 2 MB of video memory per font), and other operations such as the display of anti-aliased text on top of other graphics—including video—can also be done with no computation effort on the part of the CPU. DirectX 9 cards are only able to cache the alpha-blended glyphs in memory, thus requiring the CPU to handle glyph composition and alpha-blending before passing this to the video card. Caching these partially-rendered glyphs requires significantly more memory (Microsoft estimates 5 MB per process). Cards that don't support DirectX 9 have no hardware-accelerated text rendering capabilities.

Alternative input

WPF supports digital ink-related functionality.

Accessibility

WPF supports Microsoft UI Automation to allow developers to create accessible interfaces.

XAML

Main article: Extensible Application Markup Language

Following the success of markup languages for web development, WPF introduces a new language known as eXtensible Application Markup Language (XAML) (pronounced as "Zammel"), which is based on XML. XAML is designed as a more efficient method of developing application user interfaces[citation needed].

The specific advantage that XAML brings to WPF is that XAML is a completely declarative language. In a declarative programming language, the developer (or designer) describes the behavior and integration of components without the use of procedural programming. This allows someone with little or no traditional programming experience to create an entire working application with no programming. Although it is rare that an entire application will be built completely in XAML, the introduction of XAML allows application designers to more effectively contribute to the application development cycle. Using XAML to develop user interfaces also allows for separation of model and view; which is considered a good architectural principle. In XAML, elements and attributes map to classes and properties in the underlying APIs.

As in web development, both layouts and specific themes are well suited to markup, but XAML is not required for either. Indeed, all elements of WPF may be coded in a .NET language (C#, VB.NET). The XAML code can ultimately be compiled into a managed assembly in the same way all .NET languages are, which means that the use of XAML for development does not incur a performance cost. XAML can also be compiled and run "on demand" similar to an HTML web-page.

Although XAML has been introduced as an integral part of WPF, the XAML standard itself is not specific to WPF (or even .NET). XAML can also be used to develop applications using any programming API and is in itself language independent. Nevertheless, special care has been taken in developing the WPF APIs to maximize interoperability with the declarative model that XAML introduces.

It is likely that many applications, such as Microsoft PowerPoint and Word, will support exporting their content to XAML.

There are several subsets (or profiles) of XAML, such as:

* XAML Presentation (XAML-P) - incorporates all items encompassing WPF v1.0
* XML Paper Specification (XPS) - a subset of XAML-P for representing fixed format documents and used as the spool format for the printing subsystem in Windows Vista

There are also profiles specific to Workflow Foundation, and other domain specific subsets will likely emerge in the future.

Tools

There are a number of development tools available for developing Windows Presentation Foundation applications, most currently of beta quality, some commercially released.

* Microsoft Cider is the XAML designer in the form of an add-in for the Visual Studio 2005 IDE for building Windows Presentation Foundation applications. It is available in CTP form for Visual Studio 2005, there are no plans for an RTM version for Visual Studio 2005. Cider is integrated into Visual Studio 2008.[16]
* Microsoft Expression Blend is a designer-oriented tool that provides a canvas for the creation of WPF applications with 2D and 3D graphics, text and forms content. It generates XAML that may be exported into other tools.
* Microsoft Expression Design is a bitmap and 2D-vector graphics tool that allows export to XAML.
* XAMLPad is a lightweight tool included in the .NET Framework SDK. It can create and render XAML files using a split screen UI layout. It also provides a tree view of the markup in a panel. An improved version, called XamlPadX v3, can be downloaded from the author's blog.
Deployment

* WPF isn't just for building traditional standalone applications. Its deployment model offers both standalone and XAML Browser Applications (XBAP) flavors. The programming model for building either flavor of application is similar.
o Standalone applications are those that have been locally installed on the computer using software such as ClickOnce or Windows Installer (MSI) and which run on the desktop. Standalone applications are considered full trust and have full access to a computer's resources.
o XAML Browser Applications (XBAPs) are programs that are hosted inside a web browser. Hosted applications run in a partial trust sandbox environment, and are not given full access to the computer's resources and not all WPF functionality is available. The hosted environment is intended to protect the computer from malicious applications. Starting an XBAP (pronounced "ex-bap") from an HTML page or vice versa is seamless (there is no security or installation prompt). Although one gets the perception of the application running in the browser, it actually runs in an out-of-process executable different from the browser. As of the release of .NET Framework 3.0, XBAPs only run in Internet Explorer. With the release of .NET Framework 3.5 SP1 they also run in Mozilla Firefox using the included XBAP extension.

Windows Presentation Foundation

Type
* Windows Presentation Foundation - Annotations
* Applications
* Windows Presentation Foundation - Controls
* Windows Presentation Foundation - Data Binding
* Windows Presentation Foundation - General



* Windows Presentation Foundation - Layout
* Windows Presentation Foundation - Styles
* Windows Presentation Foundation - Templates
* Windows Presentation Foundation - XAML

Friday, February 6, 2009

.Net Framework Diagram


.Net arcitecter Diagram

.NET Framework

The Microsoft .NET Framework is a software framework that is available with several Microsoft Windows operating systems. It includes a large library of coded solutions to prevent common programming problems and a virtual machine that manages the execution of programs written specifically for the framework. The .NET Framework is a key Microsoft offering and is intended to be used by most new applications created for the Windows platform.

The coded solutions that form the framework's Base Class Library cover a large range of programming needs in a number of areas, including user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. The class library is used by programmers, who combine it with their own code to produce applications.

Programs written for the .NET Framework execute in a software environment that manages the program's runtime requirements. Also part of the .NET Framework, this runtime environment is known as the Common Language Runtime (CLR). The CLR provides the appearance of an application virtual machine so that programmers need not consider the capabilities of the specific CPU that will execute the program. The CLR also provides other important services such as security, memory management, and exception handling. The class library and the CLR together compose the .NET Framework.

Principal design features

Interoperability
Because interaction between new and older applications is commonly required, the .NET Framework provides means to access functionality that is implemented in programs that execute outside the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and System.EnterpriseServices namespaces of the framework; access to other functionality is provided using the P/Invoke feature.
Common Runtime Engine
The Common Language Runtime (CLR) is the virtual machine component of the .NET framework. All .NET programs execute under the supervision of the CLR, guaranteeing certain properties and behaviors in the areas of memory management, security, and exception handling.
Language Independence
The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all possible datatypes and programming constructs supported by the CLR and how they may or may not interact with each other. Because of this feature, the .NET Framework supports the exchange of instances of types between programs written in any of the .NET languages. This is discussed in more detail in Microsoft .NET Languages.
Base Class Library
The Base Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions, including file reading and writing, graphic rendering, database interaction and XML document manipulation.
Simplified Deployment
Installation of computer software must be carefully managed to ensure that it does not interfere with previously installed software, and that it conforms to security requirements. The .NET framework includes design features and tools that help address these requirements.
Security
The design is meant to address some of the vulnerabilities, such as buffer overflows, that have been exploited by malicious software. Additionally, .NET provides a common security model for all applications.
Portability
The design of the .NET Framework allows it to theoretically be platform agnostic, and thus cross-platform compatible. That is, a program written to use the framework should run without change on any type of system for which the framework is implemented. Microsoft's commercial implementations of the framework cover Windows, Windows CE, and the Xbox 360.[3] In addition, Microsoft submits the specifications for the Common Language Infrastructure (which includes the core class libraries, Common Type System, and the Common Intermediate Language),[4][5][6] the C# language,[7] and the C++/CLI language[8] to both ECMA and the ISO, making them available as open standards. This makes it possible for third parties to create compatible implementations of the framework and its languages on other platforms.

Architecture
Visual overview of the Common Language Infrastructure

Common Language Infrastructure (CLI)

Common Language Infrastructure

The core aspects of the .NET framework lie within the Common Language Infrastructure, or CLI. The purpose of the CLI is to provide a language-neutral platform for application development and execution, including functions for exception handling, garbage collection, security, and interoperability. Microsoft's implementation of the CLI is called the Common Language Runtime or CLR.

Assemblies

.NET assembly

The intermediate CIL code is housed in .NET assemblies. As mandated by specification, assemblies are stored in the Portable Executable (PE) format, common on the Windows platform for all DLL and EXE files. The assembly consists of one or more files, one of which must contain the manifest, which has the metadata for the assembly. The complete name of an assembly (not to be confused with the filename on disk) contains its simple text name, version number, culture, and public key token. The public key token is a unique hash generated when the assembly is compiled, thus two assemblies with the same public key token are guaranteed to be identical from the point of view of the framework. A private key can also be specified known only to the creator of the assembly and can be used for strong naming and to guarantee that the assembly is from the same author when a new version of the assembly is compiled (required to add an assembly to the Global Assembly Cache).

Metadata

.NET metadata

All CLI is self-describing through .NET metadata. The CLR checks the metadata to ensure that the correct method is called. Metadata is usually generated by language compilers but developers can create their own metadata through custom attributes. Metadata contains information about the assembly, and is also used to implement the reflective programming capabilities of .NET Framework.

Security

.NET has its own security mechanism with two general features: Code Access Security (CAS), and validation and verification. Code Access Security is based on evidence that is associated with a specific assembly. Typically the evidence is the source of the assembly (whether it is installed on the local machine or has been downloaded from the intranet or Internet). Code Access Security uses evidence to determine the permissions granted to the code. Other code can demand that calling code is granted a specified permission. The demand causes the CLR to perform a call stack walk: every assembly of each method in the call stack is checked for the required permission; if any assembly is not granted the permission a security exception is thrown.

When an assembly is loaded the CLR performs various tests. Two such tests are validation and verification. During validation the CLR checks that the assembly contains valid metadata and CIL, and whether the internal tables are correct. Verification is not so exact. The verification mechanism checks to see if the code does anything that is 'unsafe'. The algorithm used is quite conservative; hence occasionally code that is 'safe' does not pass. Unsafe code will only be executed if the assembly has the 'skip verification' permission, which generally means code that is installed on the local machine.

.NET Framework uses appdomains as a mechanism for isolating code running in a process. Appdomains can be created and code loaded into or unloaded from them independent of other appdomains. This helps increase the fault tolerance of the application, as faults or crashes in one appdomain do not affect rest of the application. Appdomains can also be configured independently with different security privileges. This can help increase the security of the application by isolating potentially unsafe code. The developer, however, has to split the application into subdomains; it is not done by the CLR.

Class library
Namespaces in the BCL[9]
System
System. CodeDom
System. Collections
System. Diagnostics
System. Globalization
System. IO
System. Resources
System. Text
System. Text.RegularExpressions

Base Class Library and Framework Class Library

Microsoft .NET Framework includes a set of standard class libraries. The class library is organized in a hierarchy of namespaces. Most of the built in APIs are part of either System.* or Microsoft.* namespaces. It encapsulates a large number of common functions, such as file reading and writing, graphic rendering, database interaction, and XML document manipulation, among others. The .NET class libraries are available to all .NET languages. The .NET Framework class library is divided into two parts: the Base Class Library and the Framework Class Library.

The Base Class Library (BCL) includes a small subset of the entire class library and is the core set of classes that serve as the basic API of the Common Language Runtime.[9] The classes in mscorlib.dll and some of the classes in System.dll and System.core.dll are considered to be a part of the BCL. The BCL classes are available in both .NET Framework as well as its alternative implementations including .NET Compact Framework, Microsoft Silverlight and Mono.

The Framework Class Library (FCL) is a superset of the BCL classes and refers to the entire class library that ships with .NET Framework. It includes an expanded set of libraries, including WinForms, ADO.NET, ASP.NET, Language Integrated Query, Windows Presentation Foundation, Windows Communication Foundation among others. The FCL is much larger in scope than standard libraries for languages like C++, and comparable in scope to the standard libraries of Java.

Memory management

The .NET Framework CLR frees the developer from the burden of managing memory (allocating and freeing up when done); instead it does the memory management itself. To this end, the memory allocated to instantiations of .NET types (objects) is done contiguously[10] from the managed heap, a pool of memory managed by the CLR. As long as there exists a reference to an object, which might be either a direct reference to an object or via a graph of objects, the object is considered to be in use by the CLR. When there is no reference to an object, and it cannot be reached or used, it becomes garbage. However, it still holds on to the memory allocated to it. .NET Framework includes a garbage collector which runs periodically, on a separate thread from the application's thread, that enumerates all the unusable objects and reclaims the memory allocated to them.

The .NET Garbage Collector (GC) is a non-deterministic, compacting, mark-and-sweep garbage collector. The GC runs only when a certain amount of memory has been used or there is enough pressure for memory on the system. Since it is not guaranteed when the conditions to reclaim memory are reached, the GC runs are non-deterministic. Each .NET application has a set of roots, which are pointers to objects on the managed heap (managed objects). These include references to static objects and objects defined as local variables or method parameters currently in scope, as well as objects referred to by CPU registers.[10] When the GC runs, it pauses the application, and for each object referred to in the root, it recursively enumerates all the objects reachable from the root objects and marks them as reachable. It uses .NET metadata and reflection to discover the objects encapsulated by an object, and then recursively walk them. It then enumerates all the objects on the heap (which were initially allocated contiguously) using reflection. All objects not marked as reachable are garbage.[10] This is the mark phase.[11] Since the memory held by garbage is not of any consequence, it is considered free space. However, this leaves chunks of free space between objects which were initially contiguous. The objects are then compacted together, by using memcpy[11] to copy them over to the free space to make them contiguous again.[10] Any reference to an object invalidated by moving the object is updated to reflect the new location by the GC.[11] The application is resumed after the garbage collection is over.

The GC used by .NET Framework is actually generational.[12] Objects are assigned a generation; newly created objects belong to Generation 0. The objects that survive a garbage collection are tagged as Generation 1, and the Generation 1 objects that survive another collection are Generation 2 objects. The .NET Framework uses up to Generation 2 objects.[12] Higher generation objects are garbage collected less frequently than lower generation objects. This helps increase the efficiency of garbage collection, as older objects tend to have a larger lifetime than newer objects.[12] Thus, by removing older (and thus more likely to survive a collection) objects from the scope of a collection run, fewer objects need to be checked and compacted.[12]

Standardization and licensing

In August 2000, Microsoft, Hewlett-Packard, and Intel worked to standardize CLI and the C# programming language. By December 2001, both were ratified ECMA standards (ECMA 335 and ECMA 334). ISO followed in April 2003 - the current version of the ISO standards are ISO/IEC 23271:2006 and ISO/IEC 23270:2006.[13][14]

While Microsoft and their partners hold patents for the CLI and C#, ECMA and ISO require that all patents essential to implementation be made available under "reasonable and non-discriminatory terms". In addition to meeting these terms, the companies have agreed to make the patents available royalty-free.

However, this does not apply for the part of the .NET Framework which is not covered by the ECMA/ISO standard, which includes Windows Forms, ADO.NET, and ASP.NET. Patents that Microsoft holds in these areas may deter non-Microsoft implementations of the full framework.

On 3 October 2007, Microsoft announced that much of the source code for the .NET Framework Base Class Library (including ASP.NET, ADO.NET, and Windows Presentation Foundation) was to have been made available with the final release of Visual Studio 2008 towards the end of 2007 under the shared source Microsoft Reference License.[1] The source code for other libraries including Windows Communication Foundation (WCF), Windows Workflow Foundation (WF), and Language Integrated Query (LINQ) were to be added in future releases. Being released under the non Open-source Microsoft Reference License means this source code is made available for debugging purpose only, primarily to support integrated debugging of the BCL in Visual Studio.

Versions

Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released.[15]
The .NET Framework stack.
Version Version Number Release Date Visual Studio Default in Windows
1.0 1.0.3705.0 2002-02-13 Visual Studio .NET
1.1 1.1.4322.573 2003-04-24 Visual Studio .NET 2003 Windows Server 2003
2.0 2.0.50727.42 2005-11-07 Visual Studio 2005
3.0 3.0.4506.30 2006-11-06 Windows Vista, Windows Server 2008
3.5 3.5.21022.8 2007-11-19 Visual Studio 2008 Windows 7

A more complete listing of the releases of the .NET Framework may be found on the .NET Framework version list.

.NET Framework 1.0


This is the first release of the .NET Framework, released on 13 February 2002 and available for Windows 98, NT 4.0, 2000, and XP. Mainstream support by Microsoft for this version ended 10 July 2007, and extended support ends 14 July 2009.[16]


.NET Framework 1.1

This is the first major .NET Framework upgrade. It is available on its own as a redistributable package or in a software development kit, and was published on 3 April 2003. It is also part of the second release of Microsoft Visual Studio .NET (released as Visual Studio .NET 2003). This is the first version of the .NET Framework to be included as part of the Windows operating system, shipping with Windows Server 2003. Mainstream support for .NET Framework 1.1 ended on 14 October 2008, and extended support ends on 8 October 2013. Since .NET 1.1 is a component of Windows Server 2003, extended support for .NET 1.1 on Server 2003 will run out with that of the OS - currently 30 June 2013.

Changes in 1.1 on comparison with 1.0

* Built-in support for mobile ASP.NET controls. Previously available as an add-on for .NET Framework, now part of the framework.
* Security changes - enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet, and enable Code Access Security in ASP.NET applications.
* Built-in support for ODBC and Oracle databases. Previously available as an add-on for .NET Framework 1.0, now part of the framework.
* .NET Compact Framework - a version of the .NET Framework for small devices.
* Internet Protocol version 6 (IPv6) support.
* Numerous API changes.

.NET Framework 2.0

Released with Visual Studio 2005, Microsoft SQL Server 2005, and BizTalk 2006.

* The 2.0 Redistributable Package can be downloaded for free from Microsoft, and was published on 2006-01-22.
* The 2.0 Software Development Kit (SDK) can be downloaded for free from Microsoft.
* It is included as part of Visual Studio 2005 and Microsoft SQL Server 2005.
* Version 2.0 is the last version with support for Windows 2000, Windows 98 and Windows Me.
* It shipped with Windows Server 2003 R2 (not installed by default).

Changes in 2.0 in comparison with 1.1

* Numerous API changes.
* A new hosting API for native applications wishing to host an instance of the .NET runtime. The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more (detailed reference). It was initially developed to efficiently host the runtime in Microsoft SQL Server, which implements its own scheduler and memory manager.
* Full 64-bit support for both the x64 and the IA64 hardware platforms.
* Language support for generics built directly into the .NET CLR.
* Many additional and improved ASP.NET web controls.
* New data controls with declarative data binding.
* New personalization features for ASP.NET, such as support for themes, skins and webparts.
* .NET Micro Framework - a version of the .NET Framework related to the Smart Personal Objects Technology initiative.
* Partial classes
* Anonymous methods

.NET Framework 3.0

.NET Framework 3.0, formerly called WinFX,[17] includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems. It is also available for Windows XP SP2 and Windows Server 2003 as a download. There are no major architectural changes included with this release; .NET Framework 3.0 uses the Common Language Runtime of .NET Framework 2.0.[18] Unlike the previous major .NET releases there was no .NET Compact Framework release made as a counterpart of this version.

.NET Framework 3.0 consists of four major new components:

* Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
* Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
* Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
* Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.

.NET Framework 3.5


Version 3.5 of the .NET Framework was released on 19 November 2007, but it is not included with Windows Server 2008. As with .NET Framework 3.0, version 3.5 uses the CLR of version 2.0. In addition, it installs .NET Framework 2.0 SP1, .NET Framework 2.0 SP2 (with 3.5 SP1) and .NET Framework 3.0 SP1, which adds some methods and properties to the BCL classes in version 2.0 which are required for version 3.5 features such as Language Integrated Query (LINQ). These changes do not affect applications written for version 2.0, however.[19]

As with previous versions, a new .NET Compact Framework 3.5 was released in tandem with this update in order to provide support for additional features on Windows Mobile and Windows Embedded CE devices.

The source code of the Base Class Library in this version has been partially released (for debugging reference only) under the Microsoft Reference Source

Changes since version 3.0

* New language features in C# 3.0 and VB.NET 9.0 compiler
* Adds support for expression trees and lambda methods
* Extension methods
* Expression trees to represent high-level source code at runtime.[20]
* Anonymous types with static type inference
* Language Integrated Query (LINQ) along with its various providers
o LINQ to Objects
o LINQ to XML
o LINQ to SQL
* Paging support for ADO.NET
* ADO.NET synchronization API to synchronize local caches and server side datastores
* Asynchronous network I/O API[20]
* Peer-to-peer networking stack, including a managed PNRP resolver[21]
* Managed wrappers for Windows Management Instrumentation and Active Directory APIs[22]
* Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services.[23] WCF services can be made stateful using the WF persistence model.[20]
* Support for HTTP pipelining and syndication feeds.[23]
* ASP.NET AJAX is included
* New System.CodeDom namespace.

Service Pack 1

The .NET Framework 3.5 Service Pack 1 was released on August 11, 2008. This release adds new functionality and provides performance improvements under certain conditions,[24] especially with WPF where 20-45% improvements are expected. Two new data service components have been added, the ADO.NET Entity Framework and ADO.NET Data Services. Two new assemblies for web development, System.Web.Abstraction and System.Web.Routing, have been added; these are used in the upcoming ASP.NET MVC Framework and, reportedly, will be utilized in the future release of ASP.NET Forms applications. Service Pack 1 is included with SQL Server 2008 and Visual Studio 2008 Service Pack 1.

There is also a new variant of the .NET Framework, called the ".NET Framework Client Profile", which is 86% smaller than the full framework and only installs components relevant to desktop applications.[25]

.NET Framework 4.0
This article or section contains information about scheduled or expected future software.
The content may change as the software release approaches and more information becomes available.

Microsoft announced the .NET Framework 4.0 on September 29, 2008. While full details about its feature set have yet to be released, some general information regarding the company's plans have been made public. One focus of this release is to improve support for parallel computing, which target multi-core or distributed systems.[26] To this end, they plan to include technologies like PLINQ (Parallel LINQ),[27] a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls.[28] Microsoft has also stated that they plan to support a subset of the .NET Framework and ASP.NET with the "Server Core" variant of Windows Server 2008's successor.[29]

.NET vs. Java and Java EE

Comparison of the Java and .NET platforms and Comparison of C# and Java

The CLI and .NET languages such as C# and VB have many similarities to Sun's JVM and Java. They are strong competitors. Both are based on a virtual machine model that hides the details of the computer hardware on which their programs run. Both use their own intermediate byte-code, Microsoft calling theirs Common Intermediate Language (CIL; formerly MSIL) and Sun calling theirs Java bytecode. On .NET the byte-code is always compiled before execution, either Just In Time (JIT) or in advance of execution using the ngen.exe utility. With Java the byte-code is either interpreted, compiled in advance, or compiled JIT. Both provide extensive class libraries that address many common programming requirements and address many security issues that are present in other approaches. The namespaces provided in the .NET Framework closely resemble the platform packages in the Java EE API Specification in style and invocation.

.NET in its complete form (Microsoft's implementation) is only available on Windows platforms and partially available on Linux and Macintosh,[30][31][32] whereas Java is fully available on many platforms.[33] From its beginning .NET has supported multiple programming languages and at its core remains platform agnostic and standardized so that other vendors can implement it on other platforms (although Microsoft's implementation only targets Windows, Windows CE, and Xbox platforms). The Java platform was initially built to support only the Java language on many operating system platforms under the slogan "Write once, run anywhere." Other programming languages have been implemented on the Java Virtual Machine[34] but are less widely used (see JVM languages).

Sun's reference implementation of Java (including the class library, the compiler, the virtual machine, and the various tools associated with the Java Platform) is open source under the GNU GPL license with Classpath exception.[35] The source code for the .NET framework base class library is available under the Microsoft Reference License. [36] [37]

The third-party Mono Project, sponsored by Novell, has been developing an open source implementation of the ECMA standards that define the .NET Framework, as well as most of the other non-ECMA standardized libraries in Microsoft's .NET. The Mono implementation is meant to run on Linux, Solaris, Mac OS X, BSD, HP-UX, and Windows platforms. Mono includes the CLR, the class libraries, and compilers for C# and VB.NET. The current version supports all the APIs in version 2.0 of Microsoft's .NET. Full support exists for C# 3.0 LINQ to Objects and LINQ to Xml. [38]

Criticism

Some concerns and criticism relating to .NET include:

* Applications running in a managed environment tend to require more system resources than similar applications that access machine resources more directly. Some applications, however, have been shown to perform better in .NET than in their native version.[citation needed] This could be due to the runtime optimizations made possible by such an environment, the use of relatively well-performing functions in the .NET framework, just-in-time compilation of managed code, or other aspects of the CLR.[39][40]
* As JIT languages can be more easily reverse-engineered than native code to algorithms used by an application, there is concern over possible loss of trade secrets and the bypassing of license control mechanisms. Many obfuscation techniques already developed can help to prevent this; Microsoft's Visual Studio 2005 (and newer) includes such a tool.
* In a managed environment the regularly occurring garbage collection for reclaiming memory suspends execution of the application for an unpredictable lapse of time (typically no more than a few milliseconds, but in memory-constrained systems can be much longer). This makes such environments unsuitable for some applications such as those that must respond to events with predictable timing (see real-time computing).
* Since the framework is not pre-installed on older versions of Windows an application that requires it must verify that it is present, and if it is not, guide the user to install it. This requirement may deter some from using the application.
* Newer versions of the framework (3.5 and up) are not pre-installed on any versions of the Windows operating system. Some developers have expressed concerns about the large size (around 54 MB for end-users with .NET 3.0 and 197 MB with .NET 3.5) and reliability of .NET framework runtime installers for end-users. The first service pack for version 3.5 mitigates this concern by offering a lighter-weight client-only subset of the full .NET Framework.
* The .NET framework currently does not provide support for calling Streaming SIMD Extensions (SSE) via managed code. However, Mono has provided support for SIMD Extensions as of version 2.2 within the Mono.Simd namespace; Mono's lead developer Miguel de Icaza has expressed hope that this SIMD support will be adopted by the CLR ECMA standard.[41] Streaming SIMD Extensions have been available in CPUs since the introduction of the Pentium III.

Alternative implementations

The Microsoft .NET Framework is the predominant implementation of .NET technologies. Other implementations for parts of the framework exist. Since the runtime engine is described by an ECMA/ISO specification, other implementations of it are unencumbered by patent issues. It is more difficult to develop alternatives to the base class library (BCL), which is not described by an open standard and may be subject to copyright restrictions. Additionally, parts of the BCL have Windows-specific functionality and behavior, so implementation on non-Windows platforms can be problematic.

Some alternative implementations of parts of the framework are listed here.

* Microsoft's Shared Source Common Language Infrastructure is a non-free shared source implementation of the CLR component of the .NET Framework. However, the last version only runs on Microsoft Windows XP SP2, and does not contain all features of version 2.0 of the .NET Framework.
* Portable.NET (part of DotGNU) provides an implementation of the Common Language Infrastructure (CLI), portions of the .NET Base Class Library (BCL), and a C# compiler. It supports a variety of CPUs and operating systems.
* Microsoft's .NET Micro Framework is a .NET platform for extremely resource-constrained devices. It includes a small version of the .NET CLR and supports development in C# and debugging (in an emulator or on hardware), both using Microsoft Visual Studio. It also features a subset of the .NET base class libraries (about 70 classes with about 420 methods), a GUI framework loosely based on Windows Presentation Foundation, and additional libraries specific to embedded applications.
* Mono is an implementation of the CLI and portions of the .NET Base Class Library (BCL), and provides additional functionality. It is dual-licensed under free software and proprietary software licenses. Mono is being developed by Novell, Inc. It includes support for ASP.NET, ADO.NET, and evolving support for Windows Forms libraries. It also includes a C# compiler, and a VB.NET compiler is in pre-beta form.
* CrossNet is an implementation of the CLI and portions of the .NET Base Class Library (BCL). It is free software. It parses .NET assemblies and generates unmanaged C++ code that can be compiled and linked within any ANSI C++ application on any platform

Thursday, February 5, 2009

code for Global.asax

Global.asax Page - This uses the Application_OnError event to capture stuff if an error happens
C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception LastError = Server.GetLastError();
string ErrMessage = LastError.ToString();
string LogName = "MyLog";
string Message = "Url " + Request.Path + " Error: " + ErrMessage;
// Create Event Log if It Doesn't Exist
if (!EventLog.SourceExists(LogName))
{
EventLog.CreateEventSource(LogName, LogName);
}

EventLog Log=new EventLog() ;
Log.Source = LogName;
//These are the five options that will display a different icon
Log.WriteEntry(Message, EventLogEntryType.Information, 1);
Log.WriteEntry(Message, EventLogEntryType.Error, 2);
Log.WriteEntry(Message, EventLogEntryType.Warning, 3);
Log.WriteEntry(Message, EventLogEntryType.SuccessAudit, 4);
Log.WriteEntry(Message, EventLogEntryType.FailureAudit, 5);
}


VB.NET
Public Sub Application_OnError(Sender as Object, E as EventArgs)
'Captures the error and converts to a string
dim LastError as Exception = Server.GetLastError()
Dim ErrMessage as String = LastError.toString()

Dim LogName As String = "MyLog"
Dim Message As String = "Url " & Request.Path & " Error: " & ErrMessage

' Create Event Log if It Doesn't Exist
If (Not EventLog.SourceExists(LogName)) Then
EventLog.CreateEventSource(LogName, LogName)
End if

Dim Log as New EventLog
Log.Source = LogName

'These are the five options that will display a different icon.
'The numbers are just to show the order. These aren't required
Log.WriteEntry(Message, EventLogEntryType.Information, 1)
' Log.WriteEntry(Message, EventLogEntryType.Error, 2)
' Log.WriteEntry(Message, EventLogEntryType.Warning, 3)
' Log.WriteEntry(Message, EventLogEntryType.SuccessAudit, 4)
' Log.WriteEntry(Message, EventLogEntryType.FailureAudit, 5)
End Sub

Default.aspx page

Sub Page_Load(Sender As Object, E As EventArgs)
If IsPostBack Then
'Declare all variables
dim x as integer
dim y as integer
dim z as integer

'set x and y to values to be divided by zero
x = 1
y = 0

'perform the division by zero to raise the error
z = x/y
End Sub

write script

form method="post" action="eventlog.aspx" name="form1" id="number"
asp:Button id="abutton" type="submit" text="Click Me to generate an error" runat="server"

Complete example using custom errors and write errors to the Event log

Writing to the Windows 2000 Event Log is a powerful feature of the ASP.NET and .NET framework. For those individuals who work in a large company and want to make track application errors, writing to the event log is a must!Writing to the Windows 2000 Event Log is a powerful feature of the ASP.NET and .NET framework. For those individuals who work in a large company and want to make track application errors, writing to the event log is a must! There wasn't any complete demos actually showing from A - Z how this was setup for the novice/common developer like me. Most novice developers need to be spoon fed how things are done the first time, once they see a simple example, they'll understand how the process works! This example is my reference how to make a complete application from A - Z setup and fail to understand how it works.

Step 1
First of all the steps I followed was to create a simple web called eventlog. I also created the application root so the global.asax file would fire. Here is how to setup an application root:
1.Open Internet Service Manager MMC (Start button, Control Panel, Administrative Tools, Internet Service Manager)
2.Located on the left side of the MMC, locate the Default Web and click the + button to expand the list of webs.
3.Right-click on the web your going to make an application root and choose properties.
4.Click the Create button.
5.After your done, the folder picture will appear like a box that is open. The application root is now created.

Step 2
I opened the global web.config file and turned on custom errors. Path to this is c:\winnt\microsoft.net\framework\.. There are 3 choices available currently On, Off and RemoteOnly. From attending the conference, the recommended was RemoteOnly. This means anyone not on the console of the machine will see a friendly error and not the real thing. For this example I chose On. You also could leave the global web.config file custom errors turned off and configure at application level's web.config Either way works just fine. web.config -- this file is placed in the root of the \eventlog application root.








Step 3 The next few items are just to create sample pages to make the application complete. I created a web.config, global.asax, Default.aspx page, and three sample error pages. 404page.aspx, 403page.aspx and customerrorpage.aspx page. Here are those pages code for all pages.
Global.asax Page - This uses the Application_OnError event to capture stuff if an error happens
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Diagnostics" %>

Default.aspx page


<% @Language="VB" %>







Customerrorpage.aspx

custom error page



404page.aspx --Capture all 404(Not Found pages)
403page.aspx --Capture all 403(Restricted pages)

Step 4
After all webs are created, web.config files in place. It was time to test out the application to see if it works. Type in http://localhost/eventlog/default.aspx file, this will display a button. Click it and see if this actually creates the log and writes the information to the event log. Actually only the custom error page will be displayed, the eventlog.aspx page will error and be transfered to the customerrorpage.aspx. The URL will be something like this. http://localhost/eventlog/customerrorpage.aspx?aspxerrorpath=/eventlog/eventlog.aspx

Step 5
Verify the log was created and entry was placed in that log. Below is five possible types of Event log messages:
Error An error event. This indicates a significant problem the user should know about; usually a loss of functionality or data.
FailureAudit A failure audit event. This indicates a security event that occurs when an audited access attempt fails; for example, a failed attempt to open a file.
Information An information event. This indicates a significant, successful operation.
SuccessAudit A success audit event. This indicates a security event that occurs when an audited access attempt is successful; for example, logging on successfully.
Warning A warning event. This indicates a problem that is not immediately significant, but that may signify conditions that could cause future problems. Thats it! This was a high-level example with examples but hopefully helps in understanding how a sample application and using the new Error-handling features of ASP.NET... Enjoy!!

Working with the ASP.NET Global.asax file

Have you ever felt the need of writing logic at the application level; precisely a location or a file where you could handle events or errors at the application level? Well if yes, then enter the Global.asax. Using this file, you can define event handlers with application-wide or session-wide scope. In this article, we will explore the application and session level events exposed in the Global.asax file and how we can utilize these events in our applications.

The Global.asax, also known as the ASP.NET application file, is located in the root directory of an ASP.NET application. This file contains code that is executed in response to application-level and session-level events raised by ASP.NET or by HTTP modules. You can also define ‘objects’ with application-wide or session-wide scope in the Global.asax file. These events and objects declared in the Global.asax are applied to all resources in that web application.
Note 1: The Global.asax is an optional file. Use it only when there is a need for it.
Note 2: If a user requests the Global.asax file, the request is rejected. External users cannot view the file.
The Global.asax file is parsed and dynamically compiled by ASP.NET. You can deploy this file as an assembly in the \bin directory of an ASP.NET application.
How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
Open Visual Studio 2005 or 2008 > Create a new website > Go to the Solution Explorer > Add New Item > Global Application Class > Add.
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events. The first set which gets invoked on each request and the second set which does not get invoked on each request. Let us explore these methods.
Methods corresponding to events that fire on each request
Application_BeginRequest() – fired when a request for the web application comes in.
Application_AuthenticateRequest –fired just before the user credentials are authenticated. You can specify your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful authentication of user’s credentials. You can use this method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful completion of an authorization request.
Application_AcquireRequestState() – fired just before the session state is retrieved for the current request.
Application_PreRequestHandlerExecute() - fired before the page framework begins before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the request.
Application_ReleaseRequestState() – fired before current state data kept in the session collection is serialized.
Application_UpdateRequestCache() – fired before information is added to output cache of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from the web server and the web application starts.
Session_Start() – fired when session starts on each new user requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Show me an example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();
}
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()
End Sub


Here we make use of the Application_Error() method to capture the error using the Server.GetLastError().

A common use of some of these events is security. The following C# example demonstrates various Global.asax events with the Application_Authenticate event used to facilitate forms-based authentication via a cookie. In addition, the Application_Start event populates an application variable, while Session_Start populates a session variable. The Application_Error event displays a simple message stating an error has occurred.

protected void Application_Start(Object sender, EventArgs e) {
Application["Title"] = "Builder.com Sample";
}
protected void Session_Start(Object sender, EventArgs e) {
Session["startValue"] = 0;
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie) {
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try {
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
} catch(Exception ex) {
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket) {
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned
// a pipe delimited string of role names.
string[2] roles
roles[0] = "One"
roles[1] = "Two"
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
protected void Application_Error(Object sender, EventArgs e) {
Response.Write("Error encountered.");
}


This example provides a peek at the usefulness of the events contained in the Global.asax file; it's important to realize that these events are related to the entire application. Consequently, any methods placed in it are available through the application's code, hence the Global name.

Here's the VB.NET equivalent of the previous code:

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("Title") = "Builder.com Sample"
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session("startValue") = 0
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
EventArgs)
' Extract the forms authentication cookie
Dim cookieName As String
cookieName = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie
authCookie = Context.Request.Cookies(cookieName)
If (authCookie Is Nothing) Then
' There is no authentication cookie.
Return
End If
Dim authTicket As FormsAuthenticationTicket
authTicket = Nothing
Try
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
Catch ex As Exception
' Log exception details (omitted for simplicity)
Return
End Try
Dim roles(2) As String
roles(0) = "One"
roles(1) = "Two"
Dim id As FormsIdentity
id = New FormsIdentity(authTicket)
Dim principal As GenericPrincipal
principal = New GenericPrincipal(id, roles)
' Attach the new principal object to the current HttpContext object
Context.User = principal
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Response.Write("Error encountered.")
End Sub


Conclusion:
In this article, we learnt that Global.asax is a file used to declare application-level events and objects. The file is responsible for handling higher-level application events such as Application_Start, Application_End, Session_Start, Session_End, and so on. I would encourage you to explore the methods corresponding to the events and analyze the best possible methods to use them in your application, if needed.
I hope you liked the article and I thank you for viewing it

Sunday, February 1, 2009

Improve Web Application Performance

Mukesh Pandey shows some tricks and tips to improve the performance of web applications.
Introduction
In the IT world, software applications are being rapidly developed. Clients, and so employers, are just looking for those teams/individuals who can build up applications rapidly, just bothering to make their application live; but what often happens after an application goes live is that users start to use the application and it doesn’t respond well. At this point, clients start to lose users and business.
To code an application is not a big deal; I believe it can be done by virtually anyone, meaning it is not necessary to have great knowledge or experience. Improving performance of an existing application (especially an one put together rapidly) could be quite risky and could cause many ripple effects. Things must be planned first to avoid horrible results.
The following are a few points that can make a site scalable and reliable; but which may initially slow down development. I believe that overall, when maintenance and future changes are taken into account, total development time would be reduced.
1. Minimize HTTP based Requestss
Problem 1: Serving images - no matter if they are of less than 1 KB - as separate web resources, cause separate web requests to the server, which impact performance.
Solutions:
Use Image Maps to merge up images, though image Maps could only merge up those images which are in sequence, like navigation images, so it depends upon your web site/page design.
Use Inline images. Inline images could increase your HTML page size but would cause fewer requests to the server.
CSS Sprites can also be used to merge up images and setting their position and backgrounds.
Problem 2: Using CSS is very good practice but serving stylesheets as separate resources, thus causing separate requests, should be considered very carefully.
Solutions:
Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.
.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.
Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.
Problem 3: JavaScript is an awesome scripting language which can be quite powerful to play with. Nonetheless, it should be used carefully not only for request size issues; but also because it can have a way of causing unpredictable performance issues.
Solution: Inline JavaScript could make the HTML page heavy, so it’s preferred to serve separate .js files or a single JavaScript file to keep all JavaScript-based scripts in a single place.
JavaScript files also get cached automatically by browsers, so they usually aren’t requested each time the page is loaded by the browsers.
2. HTTP Compression
HTTP Compression is used to compress contents from the web server. HTTP requests and responses could be compressed, which can result in great performance gains. Through HTTP compression, the size of the payload can be reduced by about 50%, which is great. Isn’t it?
HTTP Compression is now widely supported by browsers and web servers.
If HTTP compression is enabled on the web server, and if the request header includes an Accept-Encoding: gzip, deflate header, the browser supports gzip and deflate compression mechanisms, so the response can be compressed in any of the given formats by the web server in order to reduce the payload size. This leads to an increase in performance. Latter that compressed response is decompressed by the browser and rendered normally.
Following are very good links which detail HTTP Compression and their implementations:
Click here to get detailed knowledge on HTTP compression.
Click here to learn how to enable HTTP compression in IIS.
3. Correct Formatted Images at the Right Place
Problem: Normally designers use JPG or GIF formats quite randomly and ignore some other good formats to compress images.
Solution: Correct format should be used for right purpose like
If you have to place a background image, some large image or a screenshot then the suggested format is JPG/JPEG.
If you have to use small graphics like button images, header images, footer images, navigation bar images or clip arts, then the suggested format is PNG.
If an image is not required to be in high or true colors and 256 colors are enough, then GIF is preferred.
4. Compress CSS, JavaScript and Images
CSS files (.css), images and JavaScript (.js) files can be compressed, as normally .css and .js files contain unnecessary spaces, comments, unnecessary code and such other things. A number of high quality (and free) utilities are available to help you pre-compress your files.
Following are a few good links for such utilities:
Compress PNG images by clicking here
Compress JPG images by clicking here
Compress .CSS files by clicking here and here and here
Compress .Js files by clicking here and here and here
I have used these utilities and seen compression results of about 50% in file size reduction after using such loss-less compression, so I recommend them.
5. CSS at Top
The recommended approach is to put CSS links on top of the web page, as it makes the page render progressively efficient. Since users want to see the contents of a page whilst it’s loading rather than white spaces, contents/formats should be given on top. HTML Specifications clearly say to declare style sheets in the head section of a web page.
6. Javascript at Bottom
When scripts are defined on top of the page they can take unnecessary time to load; they don’t show the contents that users are expecting after making any request to an HTTP web server. It's better to display a the HTML contents of a page, then load any scripting code (when possible, of course).
Preferably use/link up JavaScript-based scripts at the bottom of a web page. Alternatively you can use the defer attribute, which runs the script at the end of page loading, but that is not the preferable approach as it is not browser independent. For example, Firefox doesn’t support it and could mess up with document.write, so only use it once you fully understand the implications.
7. Content Delivery Network: (CDN)
When a browser makes a request to any web page – that is, he types a URL/URI of any web page or web site, a request goes through many hops (routers and computers) and then finally reaches its final destination. This happens both for requests and responses. This operation affects performance and can severely effect load time.
A Content Delivery Network implies a collection of computers, distributed all over the world, which deliver data (contents). Through a CDN you can have your website data on multiple servers distributed in different locations around the world. Distribute web application data in different places around the world so request can be served from the nearest location and save time (which means performance and money as well).
8. Ajax
Problemm: Ajax is being increasingly used to improve usability, but oftentimes in a way which increases overall server load.
Solutions:
Preferably use the GET method for Ajax based Requests, because if you use POST method then the request header would be sent first, followed by the data, which basically splits the request in two steps. A single-step request can be achieved with GET if a cookie is not too long and the URL is not larger than 2k.
When using ASP.NET AJAX and the UpdatePanel control for partial page rendering, use the maximum number of update panels to update small chunks of page, but use them wisely. Don’t set the Update property to Always unless needed. Instead, set the update mode to Conditional, otherwise all the partial chunks would be sent together after each asynchronous postback.
Ajax based requests can also be cached when using the GET method. If the URL is the same, then cached data can be used from the client, and a round trip to the server can be avoided.
9. Ajax vs. Callback
Problem: Ajax is a great solution for asynchronous communication between client (web browser) and HTTP servers, but one solution can't be applied to every problem. This means that Ajax is great mechanism for sending requests to the server without making a full page postback, but what if you need to send a request to the server and don’t even need partial rendering?
Solution: best solution is Callback.
For example, if you need to check whether a user exists or not, or if a user has forgotten his/her password and you just need to send a request to the server to check if user name exist, there is no need for client-side render - just a server side operation.
Following are a couple of great links which explain callbacks: Please click here and here.
10. Reduce Cookie size
Cookies are stored on the client side to keep information about users (authentication and personalization). Since HTTP is a stateless protocol, cookies are common in web development to maintain information and state. Cookies are sent with every HTTP requests, so try to keep them low in size to minimize effects on the HTTP response.
Cookie’s size should be minimized as much as possible.
Cookies shouldn’t contain secret information. If really needed, that information should be either encrypted or encoded.
Try to minimize the number of cookies by removing unnecessary cookies.
Cookies should expire as soon as they become useless for an application.
11. Use Cache appropriately
Cache mechanism is a great way to save server round trips - and also database server round trips - as both round trips are expensive processes. By caching data we can avoid hitting them when unnecessary. Following are few guidelines for implementing caching::
Static contents should be cached, like “Contact us” and “About us” pages, and such other pages which contain static information.
If a page is not fully static, it contains some dynamic information. Such pages can leverage the ASP.NET technology, which supports partial page caching.
If data is dynamically accessed and used in web pages - like data being accessed from some file or database - and even if data is consistently or regularly changed, then that data could be cached by using ASP.NET 2.0 cache dependency features. As soon as data changes from the back-end by some other means, the cache would be updated.
Now that web technologies such ASP.NET have matured and offer such great caching capabilities, there's really no reason not to make extensive use of them.
Following are few very good links to implement caching for different types of data (static and dynamic):
Click here to cache Full page (static page caching).
Click here and here to cache partial page caching.
Click here to cache dynamic data with dependency.
12. Upload compiled code rather than source code
Pre-compiled ASP.NET pages perform much better than source code versions. Actually pre-compilation give web sites a performance boost especially when the first request is made to a folder containing that resource.
Uploading a pre-compiled version boosts up performance since the server doesn’t need to compile a page at request-time.
13. Conclusions
Following are few good practices to gain better performance::
For HTTP compression, GZip is considered the most effective and most popular by means of browsers and HTTP server. It can reduce file size up to 70% in size.
Always keep JavaScript and CSS in external files.
Avoid redirects until needed. Server.Transfer is also provided so consider that as well since it performs better in some conditions.
Minimize use of Iframes as it's costly.
Avoid try-catch blocks for control-flow as they perform poorly. Exceptions should be used only in truly exceptional situations.
Minimize Cookie/CSS sizes.
Minimize DOM objects on page as they are heavy weight.
Use link tags rather than @import to use/link up CSS.
Favicon, being a static image displayed in the browser’s address bar, should be cacheable and compressed.
Always prefer a cache-friendly folder structure. For example, create specific folders for static contents, like /static for static images/static pages…
SSL can never be cached so minimize its usage. Keep it for those pages which need to be secure, rather than using it for all the pages.
HTTP Post requests can’t be cached, so choose the HTTP method appropriately.
Prevent Denial of Service (Dos) attacks. Recommended article here.
Prevent SQL Injection. Recommended article here.
Prevent Cross Site Scripting (XSS). Recommended article here.
I hope you have learned some very good approaches and techniques to keep your web application in good shape on an HTTP server. I personally don’t think any are flat-out ignorable nor is any too difficult to implement.
As performance is a vital part of success for any web application, I have tried to be as general as possible, so every web technology (ASP.NET, asp, php, jsp, jsf and so on) can follow these tips.

Sunday, January 18, 2009

Page.RegisterStartupScript not firing properly in Ajax Extensions


Page.RegisterStartupScript not firing properly in Ajax Extensions
.code {
word-wrap:break-word;
margin:10px;
padding:10px;
border:2px ridge white;
background-color:#eeeeee;
font-family:Courier New;
font-size:10pt;
}

Recently, we were working on a AJAX Enabled site, and there was a functionality to fire a script in the page load event of a certain page. This page had ajax relevant controls in the .aspx page, along with the Update panel and ScriptManager Control.
We coded the below given method in the .aspx.cs page, for firing the script call:
Page.RegisterStartupScript("strScript5", strScript5);This code is supposed to fire the clientscript in the startup of the page, but it didn't. Something was wrong somewhere, since we had always trusted this method for the script method calls. We then tried using the following method:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "strScript5", strScript5);
Even this was not of any use. Then we started to check the MSDN and ASP.NET Forums for answer....
The actual problem was that since we used the ScriptManager and other AJAX Controls like Update panel, the firing of page event were only partial callbacks, so the code that otherwise would execute properly, didn't execute.We later came to the solution given below
ScriptManager.RegisterStartupScript(UP, UP.GetType(), strGridKey, strScript4, false);
Explanation :
Registers a startup script block for every asynchronous postback with the ScriptManager control and adds the script block to the page.
public static void RegisterStartupScript( Page page, Type type, string key, string script, bool addScriptTags)