Saturday, October 27, 2007

AutoEventWireup.

Introduction
ASP.NET supports two methods to author pages:
In-line code
Code-behind
In-line code is code that is embedded directly within the ASP.NET page. Code-behind refers to code for your ASP.NET page that is contained within a separate class file. This allows a clean separation of your HTML from your presentation logic.
When we use Microsoft Visual Studio .NET to create ASP.NET Web Forms, code-behind pages are the default method. In addition, Visual Studio .NET automatically performs precompilation for us when we build our solution.
A little bit of background
Directives in ASP.NET control the settings and properties of page and user control compilers. They can be included anywhere on a page, although it is standard to place them at the beginning. Directives are used in both .aspx files (ASP.NET pages) and .ascx files (user control pages). ASP.NET pages actually support eight different directives.
@ Page
@ Control
@ Import
@ Implements
@ Register
@ Assembly
@ OutputCache
@ Reference
Page directives are the most commonly used directives, and are used to edit a wide variety of settings that control how the page parser and page compiler work. The following is a list of some of the more commonly used page directive attributes in ASP.NET.@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="TestWebApp.WebForm1"
Language indicates the language in which the inline script code within the ASP.NET page is written (the code between <% %> tags). The value of this attribute can be C#, VB, or JS.
Codebehind indicates the name of the file being used as the code supporting this ASP.NET page. This file should reflect the Language setting; that is, if the language being used is C#, the CodeBehind file should have a .cs extension and be written in C#.
Inherits indicates a qualified class from which this ASP.NET page should inherit. Generally, this will be the name of the class described in the code-behind file.
AutoEventWireup is a Boolean attribute that indicates whether the ASP.NET pages events are auto-wired.
Note: In the above case, ASP.NET compiles the code-behind page on the fly. We have to note that this compilation step only occurs when the code-behind file is updated. Whether the file has been updated or not, well this is detected through a timestamp change.
To get to the Real Thing
The AutoEventWireup attribute may have a value of true or false. When an ASP.NET Web Application is created by using Microsoft Visual Studio .NET, the value of the AutoEventWireup attribute is set as false.
We can specify the default value of the AutoEventWireup attribute in the following locations:
The Machine.config file.
The Web.config file.
Individual Web Forms (.aspx files).
Web User Controls (.ascx files)
The value of the AutoEventWireup attribute can be declared in the section in the Machine.config file or the Web.config file, as follows:
If you make these changes in the Machine.config file, the changes affect all ASP.NET Web Forms on the computer. If you make these changes in the Web.config file, the changes affect only the application that the file belongs to. However, to make changes in the individual Web Form Only, we have to add the AutoEventWireup attribute to the @ Page directive, as shown above.
Check out the Code
When we create a new ASP.NET Web Application in Visual Studio .NET, as mentioned earlier, by default, the value of the AutoEventWireup attribute is set to false in the .aspx page and event handlers are automatically created. We can find this in the InitializeComponent method:this.Load += new System.EventHandler(this.Page_Load);
The best way to see the working of this attribute would be:
Declare a string variable msg as public in WebForm1.aspx.cs.
In the HTML section of WebForm1.aspx, enter the following code in the section: <% Response.Write(msg); %>
In the Page_Load, you could enter a value for the variable msg declared.msg= "We are in Page_Load()";
On running the application, you will get the message We are in Page_Load() [hereafter referred to as message]. Note: this is in the default case where the attribute is set to false.
Now try commenting the event handler code for the Page_Load in the aspx.cs file; and set the AutoEventWireup attribute to false in the .aspx page. On running the application this time, you will not get the message.
Now with the event handler code for the Page_Load in the aspx.cs file still commented; set the AutoEventWireup attribute to true in the .aspx page. On running the application this time, you will get the message.
Reason: In the case where AutoEventWireup attribute is set to false (by default), event handlers are automatically required for Page_Load or Page_Init. However, when we set the value of the AutoEventWireup attribute to true, the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.
A thing to be kept in mind is that the AutoEventWireup attribute of the Page directive is set to true by default for the machine (check out the value of this attribute in the machine.config) but set to false by default for a .aspx page). So if it is missing, since by default it is true (i.e., at the machine level), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.
Performance Issues
We must not set the value of the AutoEventWireup attribute to true if performance is a key consideration. If we set the value of the AutoEventWireup attribute to true, the ASP.NET page framework must make a call to the CreateDelegate method for every Web Form (.aspx page), and instead of relying on the automatic hookup, manually override the events from the page.
Credits
The whole thing was really simple but I just thought of posting it online; hope it helps someone. To give credit to where it is due. Most of the information was garnered from different places on the net. I've just complied them together and added a bit of my own to help folks along their way. I was also able to find an article related to this in MSDN Online (Article ID: 317690) but for VB.NET.
About Aby Thomas Varghese

Assembly

What is a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

Assembly

An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or as accessible by code outside that unit. .NET Assembly contains all the metadata about the modules, types, and other elements it contains in the form of a “manifest.” The CLR loves assemblies because differing programming languages are just perfect for creating certain kinds of applications. For example, COBOL stands for Common Business-Oriented Language because it’s tailor-made for creating
business apps. However, it’s not much good for creating drafting programs. Regardless of what language you used to create your modules, they can all work together within one Portable Executable Assembly. There’s a hierarchy to the structure of .NET code. That hierarchy is “Assembly -> Module -> Type -> Method."Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

Manifest
An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE (Portable Executable) file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a standalone PE (Portable Executable) file that contains only assembly manifest information.The following table shows the information contained in the assembly manifest. The first four items — the assembly name, version number, culture, and strong name information — make up the assembly's identity.Assembly name: A text string specifying the assembly's name.Version number: A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy.Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.)Strong name information: The public key from the publisher if the assembly has been given a strong name.List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
(A) What is Manifest?
Assembly metadata is stored in Manifest.
Manifest contains all the metadata needed to do the following things( See Figure Manifest View for more details) :
√ Version of assembly
√ Security identity
√ Scope of the assembly
√ resolve references to resources and classes.
√ The assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a stand-alone PE file that
contains only assembly manifest information.

Asp

ASP.NET provides a programming model and infrastructure that offers the necessary services for programmers to develop web-based applications. Because ASP.NET is part of the .NET Framework, programmers can use the managed Common Language Runtime (CLR) environment, type safety, inheritance, etc. to create web-based applications. You can develop your ASP.NET web-based applications in any .NET-compliant language, such as Visual Basic, Visual C#, or JScript.NET. ASP.NET code is compiled rather than interpreted, which permits early binding, strong typing, and just-in-time (JIT) compiling to native code.
In ASP.NET, deployment is as simple as copying a component assembly to its desired location. ASP.NET configuration settings are stored in XML-based files, which are human-readable and -writable. ASP.NET automatically applies new configuration settings to web resources whenever it finds any changes to configuration files, without rebooting the server.

There are two core programming models when developing an ASP.NET application:
· Web forms
· Web Services

Web forms allow you to develop programmable forms-based web pages. A web forms page consists of two parts:
· Visual elements: HTML elements and web forms controls.
· User interface logic: Code that contains logic for interacting with the visual elements.
In ASP.NET, business logic code (functional code) is separated from presentation code (HTML code). The visual elements are created in an .aspx file. The code is in a separate class file, called the code-behind class file (.aspx.vb or .aspx.cs), which consists of event handlers, initialization code, and other supporting code for the user interface in the aspx file.
Web services provide the capability to exchange messages in a loosely coupled environment using standard data formats and protocols such as HTTP, XML, and SOAP. A web service is nothing but a programmable application component that provides some serviceable, useful functionality such as application logic, and is available to any number of potentially incongruent systems through the use of Internet standards such as XML and HTTP.
ASP.NET provides solutions to some of the drawbacks that exist in ASP and offers a lot of additional benefits such as performance, scalability, deployment, security, output cache control, and web services infrastructure. Both ASP.NET and ASP run agreeably on an Internet Information Services (IIS) web server without interruption. Newly created ASP.NET pages with the file extension .aspx won't corrupt any existing ASP application. Files with an .aspx extension are processed by the ASP.NET runtime and files with an .asp extension are processed as usual by the ASP engine. ASP.NET offers total syntax and processing compatibility with ASP applications. The two systems have completely separate processing engines.

Access Modifiers

Introduction
Access modifiers decide accessibility of your class or class member. There are five accessibility levels in VB.NET. They are:
Private
Protected
Friend (internal in C#)
Protected friend (protected internal in C#)
Public
This article examines all them with examples. Even though the examples are in VB.NET, they can be easily ported to C# as most of the keywords are same.
Public Access
Many
programmers have habit of making everything public in their applications. This is fine for test applications but when you are developing real life applications you should expose only the data or functionality that is necessary by the user of your class. Classes and class members marked with Public access modifier are available in the same class, all the classes from the same project and to all other projects as well. This access specifier is least restrictive. Following is an example of public access specifier.
Public Class Book
Public Title As String
End Class
Public Class BookUser
Public Sub SomeMethod()
Dim x as
new Book()
x.Title="VB.NET Programming"
End Sub
End Class
Restricting access to classes and class members is not only a good programming practice but is also necessary to avoid any accidental misuse of your classes. Let us now discuss each of the remaining access modifiers in detail

Private Access
Private access modifier is applicable only to the members of a type. It restricts access to the members within the type itself. Consider following class:
Public Class Book
Private strTitle As String
Public Property Title()
Get
Return strTitle
End Get
Set(ByVal Value)
strTitle = Value
End Set
End Property
End Class
Here, the member variable strTitle is declared as private inside a class Book. Hence, it cannot be accessed from outside the class Book. Remember that private access modifier is applicable only to type members not to the type itself. This means you cannot declare a class as private but if your class is a nested then it can be declared as private. For example following declaration is invalid:
Namespace n1
Private Class Book
End Class
End Namespace
However, following declaration of nested class is valid:
Namespace n1
Public Class Book
Private Class NestedBook
End Class
End Class
End Namespace

Protected Access
Private access modifier allows us to hide members from others but what if some one is inheriting from your class? In many cases you want that members of
base class should be available in derived class. This cannot be achieved with private modifier. Protected access specifier provide such access. The members marked with protected access modifier can be accessed in the same class and all the classes inherited from it but they are not available to other classes. Following is an example of using protected access specifier:
Public Class Class1
Protected age As Integer '... other code
End Class
Public Class Class2
Inherits Class1
Public Sub SomeMethod()
age = 99 'OK
End Sub
End Class
Public Class Class3
Public Sub SomeMethod()
Dim x As New Class1()
x.age = 99 'ERROR
End Sub End Class
Friend Access
Now going one step further let us assume that you want that all the classes from your project should be able to access to your class members but classes external to your project should not be able to do so. In this case neither private nor protected can help. Only your Friend can help you out. You guessed it! The friend access modifier is used to declare your class members such that any class from the same project will be able to access them but external classes cannot. Note that this access modifier is applicable to class definitions also. Following are the examples of using Friend members and classes.
Assembly1.dll
Public Class Class1
Friend age As Integer '... other code
End Class
Public Class Class2
Public Sub SomeMethod()
Dim x As New Class1()
x.age = 99 'OK
End Sub
End Class
Assembly2.dll
Public Class Class3
Public Sub SomeOtherMethod()
Dim x As New Class1()
x.age = 99 'ERROR
End Sub
End Class
When applied to class the class will be available only in the project in which it is declared.
Assembly1.dll
Friend Class Class3
Public Sub SomeMethod()
End Sub
End Class
Public Class Class4
Public Sub SomeOtherMethod()
Dim x As Class3 'OK
End Sub
End Class
Assembly2.dll
Dim x As TestComp1.n1.Class3 'ERROR
Note: In C# internal keyword serves the same purpose as Friend keyword in VB.NET.
Protected Friend Access
Protected Friend access modifier is a combination of protected and friend access modifiers and allows access to class members in the same project and all the inherited types.

Abstract class

à Abstract class defines functionality that is implemented by one or more subclass.
à Abstract class states “what” to do, rather than “how” to do.
à Abstract class cannot be instantiated.
à Abstract method “must” be overridden in derived class.
à Abstract classes can provide all, some, or none of the actual implementation of a class.
It provides a default code or stub for their child class.à It is useful while creating Component.
Eg:abstract class shape{void draw() { }}
class circle : shape

{
void draw()
{
Console.WriteLine(“Circle”);
}
}
class rectangle : shape

{
void draw()
{
Console.WriteLine(“rectangle”);
}
}
class triangle : shape

{
void draw()
{
Console.WriteLine(“triangle”);
}
}
static void main()

{
shape s;
s = new circle();
s.draw();s = new rectangle();
s.draw();s = new triangle();
s.draw();
}
//Outputcirclerectangletriangle

3-TierIntroduction

Introduction:
Application Architecture is the most important process of developing a good application. Some people tends to jump into coding without any architecture laid. Later we see those people changing the architecture and finally the
application had to be developed from the scratch with the correct architecture.
In this article I will describe some details about how you can improve the architecture of you application. This article is targeted to the beginner's audience.
Three layered approach:
Three layered approach is the most common approach taken to build a
web application. In this approach application is divided into three layers.
1) Database layer:
The
database layer contains the tables, views and stored procedures which deals with the database. Usually this layer is created before making the other layers. Database layer is also the most important layer in the application architecture that's why most of the time is spent making the database layer solid so, the pillars of the application are strong and scalable.
2) Business logic layer:
Business logic layer contains the logic of the application. Like the database layer this layer is not exposed to the users directly but a user interface is provided to do so.
3)
Presentation layer:
The presentation layer is what the user actually sees. The html pages with some animation, the textboxes to take input and message boxes to alarm the user of the operation of his action. Presentation layer must be developed in such a way that it can be changed without doing any changes to the business or the database layer. This means that the presentation layer must be independent of the database and the business layers. Also the presentation layer should be made in such a way that changing the presentation to the user will take less time and effort.
Tips about the database layer:
1) Database layer as I pointed out earlier consists of a database, stored procedures and tables etc. Its always good to use stored procedures instead of Ad-Hoc queries. Ad-Hoc queries have the danger of SQL injections. Stored procedures on the other hand are more fast to execute and gives the performance boost. Since those procedures used often are executed from the cache.
2) It's very important that you normalize the database design. You should carefully map out the one-one, one-many, many-many
relationships. If normalization of the database is not handled carefully at the right time it can destroy the whole application and you may have to start from scratch.
Tips about the Business layer:
Business layer is where all the cool stuff happens. Usually for each subject (noun) in our specification we make a class for it. Suppose we are making an application where users and
sends emails and receive messages depending on if their email is sent or not.
Some users tends to keep all the business logic in the presentation layer. This approach is very dangerous since user has a direct interaction with the business logic and it becomes easily hackable. That's why business logic is always kept in the class libraries this approach makes the separation of the user interaction with business logic and also makes the libraries portable so, it can be used by some other same type of application.
Sometimes its also a good idea to map the class fields to the database column names. Suppose our application stored articles so, our mapping class will look something like this:
public class ArticleDetails{
public string Title;public string Url;public string Description;
}
The advantage of using this approach is that if you make changes in the Title, Url, Description than you will only need to send the object of the ArticleDetails class. This is also a good approach since if later you decide to add one field to your database due to bad design you can just add the same field to this class without having to play around with the business logic methods.
Data Access Application Block:
I also explicitly use
Microsoft.NET Data Access Application Block. Application Blocks makes the code simpler to understand and modify. Another good reason to use the application block is that it makes the code more readable if many coders are using the same block instead you find yourself reading every line of code written by the developer and trying to understand his coding style of accessing the database.
Messages Class:
Just like the
Data Access Application Block every frequently used operation should be converted into a class for easier access. This includes Cache Block, Exception Handling Block etc. I will talk about the Messages class whose purpose is to alarm the user with a message about the operation that he has performed.
Sometimes you want to print a message "Data has been successfully entered" if the transaction was successful and "
Data not entered" when, the transaction was a failure.
Most of the developers perform this task by simply adding the if-else block in the presentation layer.
bool isDataInserted = code.AddCodeSample(txtTitle,txtDescription);
if(isDataInserted){
// Data inserted successfully
}else{
// Data not inserted
}
This is a common approach used by developers to alarm the user of his operation. The problem with this approach is we are repeating code, meaning that each of the event that is inserted, deleted, updated, selecting, editing will have the same kind operation with a different message and we will be writing same 4-5 lines everywhere. Hence, its a good idea to make a class whose main purpose is to return messages. You can call this class DBMessages.
// message returned after the insert operation
public static string InsertMessages(bool isAdded){
if(isAdded){
return "Inserted";
}else{
return "Not Inserted";
}
}
// message returned after the Update Operation
public static string UpdateMessages(bool isUpdated){
if(isUpdated){
return "Updated";
}else{
return "Not Updated";
}
}

As you see now you only have to write a single line of code to get the message. Here lblMessage is a label control.
lblMessage.Text = DBMessages.InsertMessages(isAdded);
Using this approach you can also modify your message in one place and it will be changed everywhere.
Tips for the Presentation Layer:
Presentation layer design should always be consistent since this layer will be the one that will change often. Consistent design can come in the form of the Cascading Style Sheets and User Controls. By using Cascading Style Sheets your page has a consistent look and feel. A simple change in the Cascading Style Sheet will bring changes to all the pages without even touching them.
User controls is another way for making sections that are easily changed. If on the other hand if they are not marked as a user controls we will have to go to each page and manually change it which, is a pain.
Conclusion:
If the architecture of the application is made correct. The rest of the coding (Implementation Phase) becomes really easy.

Application Domains

When we launch the Notepad program in Windows, the program executes inside of a container known as a process. We can launch multiple instances of Notepad, and each instance will run in a dedicated process. Using the Task Manager application, we can see a list of all processes currently executing in the system.
A process contains the executable code and data of a program inside memory it has reserved from the operating system. There will be at least one thread executing instructions inside of the process, and in most cases there are multiple threads. If the program opens any files or other resources, those resources will belong to the process.
A process is also boundary. Erroneous code inside of a process cannot corrupt areas outside of the current process. It is easy to communicate inside of a process, but special techniques are required to communicate from one process to another. Each process also runs under a specific security context which can dictate what the process can do on the machine and network.
A process is the smallest unit of isolation available on the Windows operating system. This could pose a problem for an ISP who wants to host hundreds of ASP.NET applications on a single server. The ISP will want to isolate each ASP.NET application to prevent one application from interfering with another company’s application on the same server, but the relative cost of launching and executing a process for hundreds of applications may be prohibitive.
Introducing the Application Domain
.NET introduces the concept of an application domain, or AppDomain. Like a process, the AppDomain is both a container and a boundary. The .NET runtime uses an AppDomain as a container for code and data, just like the operating system uses a process as a container for code and data. As the operating system uses a process to isolate misbehaving code, the .NET runtime uses an AppDomain to isolate code inside of a secure boundary.
Note, however, that the application domain is not a secure boundary when the application runs with full trust. Applications running with full trust can execute native code and circumvent all security checks by the .NET runtime. ASP.NET applications run with full trust by default.
An AppDomain belongs to only a single process, but single process can hold multiple AppDomains. An AppDomain is relatively cheap to create (compared to a process), and has relatively less overhead to maintain than a process. For these reasons, an AppDomain is a great solution for the ISP who is hosting hundreds of applications. Each application can exist inside an isolated AppDomain, and many of these AppDomains can exist inside of a single process – a cost savings.
AppDomains And You
You’ve created two ASP.NET applications on the same server, and have not done any special configuration. What is happening?
A single ASP.NET worker process will host both of the ASP.NET applications. On Windows XP and Windows 2000 this process is named aspnet_wp.exe, and the process runs under the security context of the local ASPNET account. On Windows 2003 the worker process has the name w3wp.exe and runs under the NETWORK SERVICE account by default.
An object lives in one AppDomain. Each ASP.NET application will have it’s own set of global variables: Cache, Application, and Session objects are not shared. Even though the code for both of the applications resides inside the same process, the unit of isolation is the .NET AppDomain. If there are classes with shared or static members, and those classes exist in both applications, each AppDomain will have it’s own copy of the static fields – the data is not shared. The code and data for each application is safely isolated and inside of a boundary provided by the AppDomain
In order to communicate or pass objects between AppDomains, you’ll need to look at techniques in .NET for communication across boundaries, such as .NET remoting or web services.
Note again: the one caveat to the idea of an AppDomain as a boundary is that ASP.NET applications will run with full trust by default. Fully trusted code can execute native code, and native code can essentially have access to anything inside the process. You’ll need to run applications with partial trust to restrict access to unmanged code and verify all managed code to secure AppDomains.
Shadow Copies and Restarts
Once an assembly is loaded into an AppDomain, there is no way to remove the assembly from the AppDomain. It is possible, however, to remove an AppDomain from a process.
If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain , it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests.
Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk.
The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline.
Master Of Your Domain
Application domains replace the OS process as the unit of isolation for .NET code. An understanding of application domains will give you an idea of the work taking place behind the scenes of an ASP.NET application. Using the CurrentDomain property of the AppDomain class you can inspect properties about the AppDomain your code is executing in, including the Shadow Copy settings we discussed in this article