csharpwithdj.blogspot.com
Delegates in C#
Most programmers are used to passing data in methods as input and output parameters.
Imagine a scenario where you wish to pass methods around to other methods instead of data. Amazed! Read further.
Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time.
In this case you need to pass the unknown method as a parameter. The method that you are passing in is known as a Callback function. Call back functions are pointers to methods.
.NET implements the concept of function pointers using delegates.
• Delegate wraps a method. Calling delegate results in calling the method.
• Delegate is a type of object very similar to classes.
• Delegate gives a name to a method signature.
Where are Delegates used?
The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.
This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.
Starting Threads/Parallel Processing:
You defined several methods and you wish to execute them simultaneously and in parallel to whatever else the application is doing. This can be achieved by starting new threads. To start a new thread for your method you pass your method details to a delegate.
Generic Classes: Delegates are also used for generic class libraries which have generic functionality defined. However the generic class may need to call certain functions defined by the end user implementing the generic class. This can be done by passing the user defined functions to delegates.
Creating and Using Delegates:
Using delegates is a two step process-
..........1) Define the delegate to be used
..........2) Create one or more instances of the delegate
Syntax for defining a delegate:
delegate string reviewStatusofARegion();
to define a delegate we use a key word delegate followed by the method signature the delegate represents. In the above example string reviewStatusofARegion(); represents any method that returns a string and takes no parameters.
Syntax for creating an instance of the delegate:
reviewStatusofARegion = new reviewStatusofARegion(myClass.getEurope)
private string getEurope()
{
return “Doing Great in Europe”;
}
To create an instance of the delegate you call its constructor. The delegate constructor takes one parameter which is the method name.
The method signature should exactly match the original definition of the delegate. If it does not match the compiler would raise an Error.
Multicast Delegate:
Delegate wraps a method. Calling delegate results in calling the method. It is possible to wrap more than one method in a delegate. This is known as a multicast delegate.
If you make a call to a multicast delegate it will call all the functions it wraps in the order specified. Please note that functions in this case should not return any values.
Syntax for defining a delegate:
delegate void deleteRowsinTable( int Year)
Syntax for instantiating the delegate:
deleteRowsinTable Cleanup = new deleteRowsinTable(archiveCompletedTasks)
Cleanup += new deleteRowsinTable(purgeCompletedTasks)
Using Delegates in Event Handling
Events could be visualized as following:
Hence you need a class/object that creates and fires an event
You need a mechanism to notify all
You need a method to listen for the notification
Finally, you need a method that does something when the notification is received.
Another example
Here is how you code for it
Create a class called Mylist
1) Declare an Event public event System.EventHandler EventName;
2) Declare a method that creates the event protected virtual void OnEventName(System.EventArgs e) 3) Fire the Event when appropriate conditions are met by calling the above method
If (condition met) {protected virtual void OnEventName(System.EventArgs e);}
This blog help you to understand the basics of OPPs, Design,.Net and Sql Server. It also contain interview question.
Sunday, October 25, 2009
Difference in Sql Server
Basic difference between Temp Tables and Table Variables
There are two types of temporary tables
A.) Local declared with one # Sign (#)
B.) Global declared with two # Sign (##)
Both of these tables created by simple CREATE TABLE (BOL) syntax except that # is used for Local Temporary Tables declaration and ## is used for Global Temporary Tables.
The Major difference between these two are Local Temporary tables (#) are visible in current connection and Global Temporary Table (##) are visible to all sessions or to the entire instance. You should always check for existence of global temporary table before creating it.
Let see with an example..
Open SSMS connect it and now create a Local Temporary table like this.
-- Creating Local Temporary Table
CREATE TABLE #LOCALTEST(C1 INT, C2 VARCHAR(50))
This will create a temporary table named LOCALTEST now open other SSMS connect it and again retry to create another table with same name but using the new connection and check if it created or not so here it is ….
-- Create Temporary Table with same name
CREATE TABLE #LOCALTEST(C1 INT, C2 VARCHAR(50))
-- Try to find out table with 'LOCALTEST' name in TempDb
USE TEMPDB
GO
SELECT Table_Catalog, Table_Name FROM information_schema.tables
WHERE table_name like '%LOCALTEST%'
GO
So here is the result set for the above query
So its very clear from the result set that there are two Local Temporary Tables with the same name.
In order to identify which table is created by which user (in case of same temporary table name), SQL Server suffixes it with the number, you can see that in this image.
But when you try the same thing with Global Temporary Tables then it will result into an error.
So here is some points about Temporary tables
1. Can be create by simple Create Table Syntax use # for Local Temporary Table and ## for Global Temporary table.
2. Local temporary tables will be dropped at the end of current session but if it is created inside a store procedure, it will be dropped when store procedure is finished.
3. Its name is limited to 116 characters.
4. Foreign Key constraints can’t be applied to primary tables.
Now we know a little about Table Variables :
Table Variables (@) introduced first in SQL Server 2000 and onwards as name suggest its a variable of type table. Its definition’s include column definition, names, data type and constraint(Foreign Key Constraint are not allowed). They are more flexible and and always stay in memory well this is not true that table Variables stay always in memory this is a MYTH as table variables may be stored as in same way in TempDb as temporary tables we will look at some example for this. They are created with the Declare @variable syntax. There are some properties for Table Variables
1. They have well defined limited scope and are not part of persistent database.
2. Transactional rollbacks doesn’t affect on them.
3. They have very limited scope like current batch of statements so they can be deleted automatically after the completion of statements.
4. You don’t use them in nested procedures.
5. You not able to truncate a table variable.
So these are the some of basics for Table Variables and Temporary Tables but our Aim is to be find out which one is best in terms of performance, Advantages & Disadvantages for each and some considerations so we try to understand things why one is better then another and why not so
A.) Table Variables have a limited scope and are not part of persistent database, transaction rollback do not affect them.
Let’s understand what does it mean by transaction rollback do not affect them just take a simple example for this..
-- Create Tempoarary Table
CREATE TABLE #LOCALTEST(C1 INT, C2 VARCHAR(50))
-- Declare Table Variable
DECLARE @LOCALTEST TABLE(C1 INT, C2 VARCHAR(50))
-- Insert Values into both
Insert into #LOCALTEST SELECT 1 ,'Ashish'
Insert into @LOCALTEST SELECT 1 ,'Ashish'
-- Begin Transaction (Update both Temp table & Table Var)
BEGIN TRAN
UPDATE #LOCALTEST SET C2='ASHISH GILHOTRA'
UPDATE @LOCALTEST SET C2='ASHISH GILHOTRA'
-- Rollback Tran
ROLLBACK TRAN
-- Check data
SELECT * FROM #LOCALTEST
SELECT * FROM @LOCALTEST
and here is the result set
From this it’s very clear that Table Variables doesn’t take part in rollback transactions.So it may be or may not be useful for developers depends on the developers.
B.) There is less locking and logging on table variables then temporary tables so what does it means so we take an another example to understand this ..
USE tempdb
GO
-- Drop table #LOCALTEST
-- Drop table DUMMYDATA
-- Create a dummy table
CREATE TABLE DUMMYDATA (A int, B varchar(100))
-- Populate Data in it
Declare @i int
set @i=1
while @i<1001
BEGIN
INSERT into DUMMYDATA SELECT @i,REPLICATE('A',100)
SET @i=@i+1
END
--select * from DUMMYDATA
--Using #LOCALTEST
CREATE TABLE #LOCALTEST(C1 INT, C2 VARCHAR(100))
GO
BEGIN TRAN
INSERT INTO #LOCALTEST(C1,C2)
SELECT A,B FROM DUMMYDATA
-- Using @LOCALTEST
DECLARE @LOCALTEST TABLE(C1 INT, C2 VARCHAR(100))
BEGIN TRAN
INSERT INTO @LOCALTEST(C1,C2)
SELECT A,B FROM DUMMYDATA
-- Now check for locks
select request_session_id, resource_type, db_name(resource_database_id),(case resource_type
WHEN 'OBJECT' then object_name(resource_associated_entity_id)
WHEN 'DATABASE' then ' '
ELSE (select object_name(object_id)
from sys.partitions
where hobt_id=resource_associated_entity_id)
END) as objname,
resource_description,
request_mode,
request_status
from sys.dm_tran_locks
--Rollback tran
So if you going to run this query batch you will see lock acquire by “#LOCALTEST” not by @LOCALTEST so yes that true that Table Variables takes less locking then temporary tables.
for logging purpose just populate temp Table and Table Variable with same data as shown above and now use fn_dblog(Un Documented) to see what happen like this..
So here is a way to find logging
First of all see logging for Table Variables
-- Table Variable
DECLARE @LOCALTEST TABLE(C1 INT, C2 VARCHAR(100))
INSERT INTO @LOCALTEST(C1,C2)
SELECT A,B FROM DUMMYDATA
-- update all the rows
update @LOCALTEST set C2 = replicate ('AB', 50)
-- Look at the top 10 log records.
select top 10 operation, AllocUnitName
from fn_dblog(null, null)
where AllocUnitName like '%LOCALTEST%'
order by [Log Record Length] Desc
For this i don’t get any records of update log in this and try same for Temporary Tables you will get update logs in this..
-- Temp Table
--drop table #localtest
CREATE TABLE #LOCALTEST(C1 INT, C2 VARCHAR(100))
GO
INSERT INTO #LOCALTEST(C1,C2)
SELECT A,B FROM DUMMYDATA
-- update all the rows
update #LOCALTEST set C2 = replicate ('ab', 50)
-- Look at the log records. Here you get log records for update
select operation,AllocUnitName
from fn_dblog(null, null)
where AllocUnitName like '%LOCALTEST%'
order by [Log Record Length] Desc
(1)Temp Tables are created in the SQL Server TEMPDB database and therefore require more IO resources and locking. Table Variables and Derived Tables are created in memory.
(2)Temp Tables will generally perform better for large amounts of data that can be worked on using parallelism whereas Table Variables are best used for small amounts of data (I use a rule of thumb of 100 or less rows) where parallelism would not provide a significant performance improvement.
(3)You cannot use a stored procedure to insert data into a Table Variable or Derived Table. For example, the following will work: INSERT INTO #MyTempTable EXEC dbo.GetPolicies_sp whereas the following will generate an error: INSERT INTO @MyTableVariable EXEC dbo.GetPolicies_sp.
(4)Derived Tables can only be created from a SELECT statement but can be used within an Insert, Update, or Delete statement.
(5) In order of scope endurance, Temp Tables extend the furthest in scope, followed by Table Variables, and finally Derived Tables.
What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.
TRUNCATE
TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE can not be Rolled back using logs.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table.
DELETE
DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE Can be Rolled back using logs.
DELETE is DML Command.
DELETE does not reset identity of the table.
Difference between Function and Stored Procedure?
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. HAVING criteria is applied after the the grouping of rows has occurred.
What is the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.
What is the difference between a local and a global variable?
A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.
A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection are closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.
What is the difference between a CHAR and a VARCHAR datatype?
CHAR and VARCHAR data types are both non-Unicode character data types with a maximum length of 8,000 characters. The main difference between these 2 data types is that a CHAR data type is fixed-length while a VARCHAR is variable-length. If the number of characters entered in a CHAR data type column is less than the declared column length, spaces are appended to it to fill up the whole length.
Another difference is in the storage size wherein the storage size for CHAR is n bytes while for VARCHAR is the actual length in bytes of the data entered (and not n bytes).
You should use CHAR data type when the data values in a column are expected to be consistently close to the same size. On the other hand, you should use VARCHAR when the data values in a column are expected to vary considerably in size.
What is difference between OSQL and Query Analyzer
Both are same for functioning but there is a little difference OSQL is command line tool which execute query and display the result same a Query Analyzer do but Query Analyzer is graphical.OSQL have not ability like Query Analyzer to analyze queries and show statistics on speed of execution .And other useful thing about OSQL is that its helps in scheduling which is done in Query Analyzer with the help of JOB.
.Net FrameWork Basics and Basics of MultiThreading
Net Framework basics
When we speak about .Net, we mean by .NET framework. .NET Framework is made up of the Common Language Runtime (CLR), the Base Class Library (System Classes). This allows us to build our own services (Web Services or Windows Services) and Web Applications (Web forms Or Asp .Net), and Windows applications (Windows forms). We can see how this is all put together.?
Above Picture shows overall picture, demonstrating how the .NET languages follows rules provided by the Common Language Specifications (CLS). These languages can all be used?Independently to build application and can all be used with built-in data describers (XML) and data assessors (ADO .NET and SQL). Every component of the .NET Framework can take advantage of the large pre- built library of classes called the Framework Class Library (FCL). Once everything is put together, the code that is created is executed in the Common Language Runtime. Common Language Runtime is designed to allow any .NET-compliant language to execute its code. At the time of writing, these languages included VB .Net, C# and C++ .NET, but any language can become .NET- compliant, if they follow CLS rules. The following sections will address each of the parts of the architecture.
.Net Common Language Specifications (CLS):
In an object-oriented environment, everything is considered as an object. (This point is explained in this article and the more advanced features are explained in other articles.) You create a template for an object (this is called the class file), and this class file is used to create multiple objects.
TIP: Consider a Rectangle. You may want to create many Rectangle in your lifetime; but each Rectangle will have certain characteristics and certain functions. For example, each rectangle will have a specific width and color. So now, suppose your friend also wants to create a Rectangle. Why reinvent the Rectangle? You can create a common template and share it with others. They create the Rectangle based on your template. This is the heart of object-oriented programming?the template is the class file, and the Rectangle is the objects built from that class. Once you have created an object, your object needs to communicate with many other Objects.
Even if it is created in another .NET language doesn?t matter, because each language follows the rules of the CLS. The CLS defines the necessary things as common variable types (this is called the Common Type System CTS ), common visibility like when and where can one see these variables, common method specifications, and so on. It doesn?t have one rule which tells how C# composes its objects and another rule tells how VB .Net does the same thing . To steal a phrase, there is now ?One rule to bind them all.? One thing to note here is that the CLS simply provides the bare rules. Languages can adhere to their own specification. In this case, the actual compilers do not need to be as powerful as those that support the full CLS.
The Common Language Runtime (CLR):
The heart of .net Framework is Common Language Runtime (CLR). All .NET-compliant languages run in a common, managed runtime execution environment. With the CLR, you can rely on code that is accessed from different languages. This is a huge benefit. One coder can write one module in C#, and another can access and use it from VB .Net. Automatic object management, the .NET languages take care of memory issues automatically. These are the few listed?benefits which you get from CLR.
Microsoft Intermediate Language (MSIL):
So how can many different languages be brought together and executed together??Microsoft Intermediate Language (MSIL) or, as it?s more commonly known, Intermediate Language (IL). In its simplest terms, IL is a programming language.?If you wanted to, you could write IL directly, compile it, and run it. But why would want to write such low level code? Microsoft has provided with higher-level languages, such as C#, that one can use. Before the code is executed, the MSIL must be converted into platform
-specific code. The CLR includes something called a JIT compiler in which the compiler order is as follows.
Source Code => Compiler => Assembley =>Class Loader =>Jit Compiler =>Manged Native Code=>Execution.
The above is the order of compilation and execution of programs. Once a program is written in a .Net compliant language, the rest all is the responsibility of the frame work.
Note:-- MSIL is become CIL(Common Intermediate language) in .net framework and above.
The Basics of .NET Framework Interoperability
Platform Interoperability
This article gives an overview of the platform invoke service in order to show how managed code calls a native function contained in a DLL. Assume your application might need to take control of Microsoft Office Excel and perform a processing routine. Because the Excel library is not written in .NET, you would need to access it through the Component Object Model (COM). COM is a set of specifications meant to form a programming discipline for writing resuable software components that can be inserted into an operating system as a binary entity. The topic of COM and .NET interop is out of the scope of this paper. But the only way to share libraries is through interop. The platform service is an internal call mechansim that enables interoperation because the System.Runtime.InteropSevices namespace contains classes where some of which define the methods that enable a C# program to call raw C DLL.
The Platform Invoke Service Platform Invoke is a service that enables managed code to call an unmanaged function contained in raw C DLLs, functions that are implemented in dynamically-linked libraries, such as those found in the win32 API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed. The CLR used together with certain base classes of defined in the System.Runtime.InteropServices namespace the .NET Framework allows managed code to directly call functions in native code. These base classes are defined in the System.Runtime.InteropServices namespace.
To call a function from a DLL export from a C# program you must declare this function within a C#:
• Declare the method by using the static and extern keywords.
• Attach the DLL import attribute to the method
• The DLLImport attribute allows you to specify the name of the method contained in the DLL.
This example shows you how to use the DllImport attribute to create a message box by calling MessageBoxA from user32.dll. To examine the functions contained insystem component, use the dumpbin.exe tool that ships with the Microsoft Windows SDK:dumbin.exe user32.dll /all > user.txt
Example
/***** File: example.cs *****/
using System;
using System.Runtime.InteropServices;
// import the namespaceclass PlatformInvokeTest
// declare the class {[DllImport("user32.dll")]
//the Dllmport attribute public static extern int MessageBoxA(
// methods int h, string m, string c, int type);public static int Main()
// entry point {return MessageBoxA(0, "This is a Windows object!", "My MessageBox", 0);
// end of method}
// end of class}
/****************************************************************/
To compile:
c:\%windir%\Microsoft.NET\Framework\v2.0.50727>csc.exe example.cs
A Closer Look at Platform Invoke
There are two ways that C# code can directly call unmanaged code:
• Directly call a function exported from a DLL.
• Call an interface method on a COM object.
For both techniques, you must provide the C# compiler with a declaration of the unmanaged function, and you may also need to provide the C# compiler with a description of how to marshal the parameters andreturn value to and from the unmanaged code.
This section tutorial consists of the following topics:
• Calling a DLL Export Directly from C#.
• Default Marshaling and Specifying Custom Marshaling for Parameters to Unmanaged Methods
The sction includes the following examples:
• Example 1 Using DllImport
• Example 2 Overriding Default Marshaling
To declare a method as having an implementation from a DLL export, do the following:
• Declare the method with the static and extern C# keywords.
• Attach the DllImport attribute to the method. The DllImport attribute allows you to specify the name of the DLL that contains the method. The common practice is to name the C# method the same as the exported method, but you can also use a different name for the C# method. DLLs contain export tables of semantically related functions.
• Optionally, specify custom marshaling information for the method's parameters and return value, which will override the .NET Framework default marshaling.
Example 1
This example shows you how to use the DllImport attribute to output a message by calling puts frommsvcrt.dll.
// PInvokeTest.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts(string c);
[DllImport("msvcrt.dll")]
internal static extern int _flushall(); public static void Main() { puts("Test"); _flushall(); }
}
OutputTest
How it works:
The preceding example shows the minimum requirements for declaring a C# method that is implemented in an unmanaged DLL. The method PlatformInvokeTest.puts is declared with the static and extern modifiers and has the DllImport attribute which tells the compiler that the implementation comes from msvcrt.dll, using the default name of puts. To use a different name for the C# method such as putstring, you must use the EntryPoint option in the DllImport attribute, that is: [DllImport("msvcrt.dll", EntryPoint="puts")].
Default Marshaling and Specifying Custom Marshaling for Parameters toUnmanaged Methods When calling an unmanaged function from C# code, the common language runtime must marshal the parameters and return values. For every .NET Framework type there is a default unmanaged type, which the common language runtime will use to marshal data across a managed to unmanaged function call. For example, the default marshaling for C# string values is to the type LPTSTR (pointer to TCHAR char buffer). You can override the default marshaling using the MarshalAs attribute in the C# declaration of the unmanaged function.
Example 2
This example uses the DllImport attribute to output a string. It also shows you how to override the default marshaling of the function parameters by using the MarshalAs attribute.
// Marshal.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts([MarshalAs(UnmanagedType.LPStr)] string m);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Main()
{
puts("Hello World!"); _flushall();
}
}
Output
When you run this example, the string,
Hello World!
will display on console output.
To illustrate the .NET assembly a unit of deployment:
C:\Widows\Microsoft.NET\Framework\v2.0.50727>ildasm.exe /metadata=validate /out:Marshal.il Marshal.exe
C:\Widows\MicrosoftNET\Framework\v2.05072>ilasm.exe Marshal.il
Microsoft (R) .NET Framework IL Assembler. Version 2.0.50727.1433
Copyright (c) Microsoft Corporation. All rights reserved.
Assembling 'Marshal.il' to EXE --> 'Marshal.exe'
Source file is ANSIAssembled method PlatformInvokeTest::Main
Assembled method PlatformInvokeTest::.ctor
Creating PE file
Emitting classes:
Class 1: PlatformInvokeTestEmitting fields and methods:
Global
Class 1 Methods: 4;
Resolving local member refs: 2 -> 2 defs, 0 refs, 0 unresolved
Emitting events and properties:
Global
Class 1
Resolving local member refs: 0 -> 0 defs, 0 refs, 0 unresolved
Writing PE file
Operation completed successfully
C:\Windows\Microsoft.NET\Framework\v2.0.50727>ngen Marshal.exe
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.1433
Installing assembly C:\Windows\Microsoft.NET\Framework\v2.0.50727\Marshal.exe
Compiling assembly C:\Windows\Microsoft.NET\Framework\v2.0.50727\Marshal.exe
...
marshal, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
C:\Windows\Microsoft.NET\Framework\v2.0.50727>sn -k Marshal.key
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Key pair written to Marshal.key
C:\Windows\Microsoft.NET\Framework\v2.0.50727>sn -p Marshal.key Marshal.PublicKey
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Public key written to Marshal.PublicKey
C:\Windows\Microsoft.NET\Framework\v2.0.50727>sn -tp Marshal.PublicKey
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Public key is
0024000004800000940000000602000000240000525341310004000001000100d7eff35e758fb7
6027164c638288029538cc3c15588efb97c090dc6b45ecbf2dd3afd9ad5a13e26aa3698b9cdf87
905039c73174a4cd99a93f98e4e49a5dc4eaa62423f542056b058dd8ae69ac54b324ba76b5be29
487e8b3ad49f2be7896aa56478bfda857526ea69823dbceb019bd378a4ee607f060b7583fa9a3a
fdcfe3ae
Public key token is bbd777f8c6ef0f35
C:\Windows\Microsoft.NET\Framework\v2.0.50727>csc.exe /keyfile:Marshal.key Marshal.cs C:\Windows\Microsoft.NET\Framework\v2.0.50727>gacutil -i Marshal.exe
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Assembly successfully added to the cache
C:\Windows\Microsoft.NET\Framework\v2.0.50727>csc /doc:Marshal.xml Marshal.cs
C:\Windows\Microsoft.NET\Framework\v2.0.50727>notepad Marshal.xml
marsha
C:\Windows\Microsoft.NET\Framework\v2.0.50727>xsd.exe /c Marshal.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Writing file 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\Marshal.xsd'.
PInvoke provides a way for managd coe to all unmanaged functions implmented in aC DLL. The .NET devloper can avoid locating and invoking the corect function export. Current tehnical documentation states that many companies keep large code bases of legacy code. The need to become proficient with interop is evident.
Basics of .NET Framework multithreaded programming
Writing multithreaded .NET applications can be tough for beginning programmers. I'll show you how to create threads and how the syntax differs for VB.NET and C#.
Multithreaded programming can be a little daunting for novice programmers, but the .NET Framework has considerably simplified the process. In fact, almost any programmer can delve into it and master the fundamentals. I'll introduce you to the basics of multithreaded programming and provide some sample code you can use to start experimenting.
Creating threads
To get multithreaded programming running, you must first create an instance of a Thread. You don’t have much in the way of options, as there is only one constructor:
C#
public Thread( ThreadStart start );
The parameter ThreadStart is a delegate to the method that is the starting point of the thread. The signature of the delegate is a method with no parameters and returns nothing, as demonstrated below:
C#
public delegate void ThreadStart();
Starting threads
One thing that may not be obvious when you first start working with threads is that creating an instance of the Thread object does not cause the thread to start. To get the thread to start, you need to call the Thread class’s Start() method, like this:
C#
public void Start();
Getting a thread to sleep
When developing a thread, you may find that you don’t need it to continually run, or you might want to delay the thread while some other thread runs. To handle this, you could place a delay loop like a “do-nothing” for-loop. But that would waste CPU cycles. Instead, you should temporarily stop the thread or put it to sleep.
Doing this couldn’t be easier. Simply add the following static/shared Sleep() method:
C#
public static void Sleep(int);
This line causes the current thread to go to sleep for the interval specified either in an integer value of milliseconds, as the examples above show, or using a TimeSpan structure.
The Sleep() method also takes two special values: Infinite, which means sleep forever, and 0, meaning give up the rest of the thread’s current CPU time slice.
A neat thing to remember is that the main function is also a thread. This means you can use Sleep() to make any application sleep.
Aborting threads
You might, on occasion, require that a thread be terminated within another thread before it runs through to its normal end. In such a case, you would call the Abort() method. Normally, this method will permanently stop the execution of a specified thread:
C#
public void Abort();
Notice, I said normally. When a thread is requested to stop with the Abort() method, a ThreadAbortException is actually thrown within the thread. This exception, like any other, can be caught. But unlike most other exceptions, the ThreadAbortException is special: It gets rethrown at the end of the catch block unless the aborting thread’s ResetAbort() method is called. Calling the ResetAbort() method cancels the abort, which, in turn, prevents the ThreadAbortException from stopping the thread.
C#
public static void ResetAbort();
Be aware that an aborted thread can't be restarted. If you attempt to do so, a ThreadStateException exception is thrown instead.
Joining threads
What if you want to execute something immediately after the threads finish? Or more generally, how do you handle the scenario where one thread needs to wait for another thread to complete before continuing? You need to join the threads using the Join() method:
C#
public void Join();
You can join threads by using one of the three overloaded Join() methods. The first overloaded method, as shown above, takes no parameters and waits until the thread completes. The second takes an Integer/int/Int32 parameter and then waits the parameter’s specified number of milliseconds or for the thread to terminate, whichever is shorter. The third overload takes a TimeSpan and functions the same as the previous overload.
Interrupting threads
It's possible to take a worker thread that is waiting for something to happen and place it in a tight loop, waiting for that event to occur. But again, this would be a big waste of CPU cycles. It's better to let the worker thread sleep and then be woken up when the event occurs. We can do that using a combination of Sleep() and Interrupt() methods in conjunction with ThreadInterruptedException:
C#
public void Interrupt();
The basic idea is to put the worker thread to sleep using the Sleep() method and then to use the Interrupt() member method to interrupt the sleep of the worker thread when the required event occurs. Simple enough, except that the Interrupt() method throws a ThreadInterruptedException instead of just terminating the Sleep() method. Thus, you need to use exception handling and place the Sleep() method in a try block. Then, have the worker thread continue execution in the catch block.
For instance, in the worker thread, you'd have the following (pseudo) code:
Try
<< Wait for event to occur >>
catch << A ThreadInterruptedException >>
<>
You'd then have some other thread execute the Interrupt() method to get the above thread to continue.
Suspending and resuming threads
Interrupting will work fine if the worker thread knows when to go to sleep. You may also need to allow another thread to temporarily stop a different thread and then restart it again later.
For example, a worker thread could be doing some intense number crunching when along comes another thread that needs to put a large graphic up on the monitor ASAP. (User interface should almost always get priority.)
This scenario can be resolved in at least three ways. You could do nothing special and let the multithreading engine slowly display the graphic. You could raise the priority of the graphic display thread (or lower the priority of the worker thread), thus giving the graphic display more cycles. Or you could suspend the worker thread using the Suspend() method:
C#
public void Suspend();
Then, you could draw the graphic and resume the worker thread using the Resume() method:
C#
public void Resume();
Background and foreground threads
Two types of threads are available. The first is the foreground thread, which runs until it reaches its exit point or is aborted. The second is the background thread, which terminates upon the completion of the last foreground thread. When you create a thread using the Thread class’ constructor, you create a foreground thread by default. To change the thread to a background thread, you must change its IsBackground property to true. The IsBackground property can be toggled at any time while the thread is running.
As you start to play with threads, you'll come to realise that even though they're easy to code, they're not easy to work with. You will spend a lot of time just trying to get your threads to synchronise. Hence, the inordinate number of Sleep() and Join() method calls placed in the simple example.
Remember, these are just the basics.
When we speak about .Net, we mean by .NET framework. .NET Framework is made up of the Common Language Runtime (CLR), the Base Class Library (System Classes). This allows us to build our own services (Web Services or Windows Services) and Web Applications (Web forms Or Asp .Net), and Windows applications (Windows forms). We can see how this is all put together.?
Above Picture shows overall picture, demonstrating how the .NET languages follows rules provided by the Common Language Specifications (CLS). These languages can all be used?Independently to build application and can all be used with built-in data describers (XML) and data assessors (ADO .NET and SQL). Every component of the .NET Framework can take advantage of the large pre- built library of classes called the Framework Class Library (FCL). Once everything is put together, the code that is created is executed in the Common Language Runtime. Common Language Runtime is designed to allow any .NET-compliant language to execute its code. At the time of writing, these languages included VB .Net, C# and C++ .NET, but any language can become .NET- compliant, if they follow CLS rules. The following sections will address each of the parts of the architecture.
.Net Common Language Specifications (CLS):
In an object-oriented environment, everything is considered as an object. (This point is explained in this article and the more advanced features are explained in other articles.) You create a template for an object (this is called the class file), and this class file is used to create multiple objects.
TIP: Consider a Rectangle. You may want to create many Rectangle in your lifetime; but each Rectangle will have certain characteristics and certain functions. For example, each rectangle will have a specific width and color. So now, suppose your friend also wants to create a Rectangle. Why reinvent the Rectangle? You can create a common template and share it with others. They create the Rectangle based on your template. This is the heart of object-oriented programming?the template is the class file, and the Rectangle is the objects built from that class. Once you have created an object, your object needs to communicate with many other Objects.
Even if it is created in another .NET language doesn?t matter, because each language follows the rules of the CLS. The CLS defines the necessary things as common variable types (this is called the Common Type System CTS ), common visibility like when and where can one see these variables, common method specifications, and so on. It doesn?t have one rule which tells how C# composes its objects and another rule tells how VB .Net does the same thing . To steal a phrase, there is now ?One rule to bind them all.? One thing to note here is that the CLS simply provides the bare rules. Languages can adhere to their own specification. In this case, the actual compilers do not need to be as powerful as those that support the full CLS.
The Common Language Runtime (CLR):
The heart of .net Framework is Common Language Runtime (CLR). All .NET-compliant languages run in a common, managed runtime execution environment. With the CLR, you can rely on code that is accessed from different languages. This is a huge benefit. One coder can write one module in C#, and another can access and use it from VB .Net. Automatic object management, the .NET languages take care of memory issues automatically. These are the few listed?benefits which you get from CLR.
Microsoft Intermediate Language (MSIL):
So how can many different languages be brought together and executed together??Microsoft Intermediate Language (MSIL) or, as it?s more commonly known, Intermediate Language (IL). In its simplest terms, IL is a programming language.?If you wanted to, you could write IL directly, compile it, and run it. But why would want to write such low level code? Microsoft has provided with higher-level languages, such as C#, that one can use. Before the code is executed, the MSIL must be converted into platform
-specific code. The CLR includes something called a JIT compiler in which the compiler order is as follows.
Source Code => Compiler => Assembley =>Class Loader =>Jit Compiler =>Manged Native Code=>Execution.
The above is the order of compilation and execution of programs. Once a program is written in a .Net compliant language, the rest all is the responsibility of the frame work.
Note:-- MSIL is become CIL(Common Intermediate language) in .net framework and above.
The Basics of .NET Framework Interoperability
Platform Interoperability
This article gives an overview of the platform invoke service in order to show how managed code calls a native function contained in a DLL. Assume your application might need to take control of Microsoft Office Excel and perform a processing routine. Because the Excel library is not written in .NET, you would need to access it through the Component Object Model (COM). COM is a set of specifications meant to form a programming discipline for writing resuable software components that can be inserted into an operating system as a binary entity. The topic of COM and .NET interop is out of the scope of this paper. But the only way to share libraries is through interop. The platform service is an internal call mechansim that enables interoperation because the System.Runtime.InteropSevices namespace contains classes where some of which define the methods that enable a C# program to call raw C DLL.
The Platform Invoke Service Platform Invoke is a service that enables managed code to call an unmanaged function contained in raw C DLLs, functions that are implemented in dynamically-linked libraries, such as those found in the win32 API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed. The CLR used together with certain base classes of defined in the System.Runtime.InteropServices namespace the .NET Framework allows managed code to directly call functions in native code. These base classes are defined in the System.Runtime.InteropServices namespace.
To call a function from a DLL export from a C# program you must declare this function within a C#:
• Declare the method by using the static and extern keywords.
• Attach the DLL import attribute to the method
• The DLLImport attribute allows you to specify the name of the method contained in the DLL.
This example shows you how to use the DllImport attribute to create a message box by calling MessageBoxA from user32.dll. To examine the functions contained insystem component, use the dumpbin.exe tool that ships with the Microsoft Windows SDK:dumbin.exe user32.dll /all > user.txt
Example
/***** File: example.cs *****/
using System;
using System.Runtime.InteropServices;
// import the namespaceclass PlatformInvokeTest
// declare the class {[DllImport("user32.dll")]
//the Dllmport attribute public static extern int MessageBoxA(
// methods int h, string m, string c, int type);public static int Main()
// entry point {return MessageBoxA(0, "This is a Windows object!", "My MessageBox", 0);
// end of method}
// end of class}
/****************************************************************/
To compile:
c:\%windir%\Microsoft.NET\Framework\v2.0.50727>csc.exe example.cs
A Closer Look at Platform Invoke
There are two ways that C# code can directly call unmanaged code:
• Directly call a function exported from a DLL.
• Call an interface method on a COM object.
For both techniques, you must provide the C# compiler with a declaration of the unmanaged function, and you may also need to provide the C# compiler with a description of how to marshal the parameters andreturn value to and from the unmanaged code.
This section tutorial consists of the following topics:
• Calling a DLL Export Directly from C#.
• Default Marshaling and Specifying Custom Marshaling for Parameters to Unmanaged Methods
The sction includes the following examples:
• Example 1 Using DllImport
• Example 2 Overriding Default Marshaling
To declare a method as having an implementation from a DLL export, do the following:
• Declare the method with the static and extern C# keywords.
• Attach the DllImport attribute to the method. The DllImport attribute allows you to specify the name of the DLL that contains the method. The common practice is to name the C# method the same as the exported method, but you can also use a different name for the C# method. DLLs contain export tables of semantically related functions.
• Optionally, specify custom marshaling information for the method's parameters and return value, which will override the .NET Framework default marshaling.
Example 1
This example shows you how to use the DllImport attribute to output a message by calling puts frommsvcrt.dll.
// PInvokeTest.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts(string c);
[DllImport("msvcrt.dll")]
internal static extern int _flushall(); public static void Main() { puts("Test"); _flushall(); }
}
OutputTest
How it works:
The preceding example shows the minimum requirements for declaring a C# method that is implemented in an unmanaged DLL. The method PlatformInvokeTest.puts is declared with the static and extern modifiers and has the DllImport attribute which tells the compiler that the implementation comes from msvcrt.dll, using the default name of puts. To use a different name for the C# method such as putstring, you must use the EntryPoint option in the DllImport attribute, that is: [DllImport("msvcrt.dll", EntryPoint="puts")].
Default Marshaling and Specifying Custom Marshaling for Parameters toUnmanaged Methods When calling an unmanaged function from C# code, the common language runtime must marshal the parameters and return values. For every .NET Framework type there is a default unmanaged type, which the common language runtime will use to marshal data across a managed to unmanaged function call. For example, the default marshaling for C# string values is to the type LPTSTR (pointer to TCHAR char buffer). You can override the default marshaling using the MarshalAs attribute in the C# declaration of the unmanaged function.
Example 2
This example uses the DllImport attribute to output a string. It also shows you how to override the default marshaling of the function parameters by using the MarshalAs attribute.
// Marshal.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts([MarshalAs(UnmanagedType.LPStr)] string m);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Main()
{
puts("Hello World!"); _flushall();
}
}
Output
When you run this example, the string,
Hello World!
will display on console output.
To illustrate the .NET assembly a unit of deployment:
C:\Widows\Microsoft.NET\Framework\v2.0.50727>ildasm.exe /metadata=validate /out:Marshal.il Marshal.exe
C:\Widows\MicrosoftNET\Framework\v2.05072>ilasm.exe Marshal.il
Microsoft (R) .NET Framework IL Assembler. Version 2.0.50727.1433
Copyright (c) Microsoft Corporation. All rights reserved.
Assembling 'Marshal.il' to EXE --> 'Marshal.exe'
Source file is ANSIAssembled method PlatformInvokeTest::Main
Assembled method PlatformInvokeTest::.ctor
Creating PE file
Emitting classes:
Class 1: PlatformInvokeTestEmitting fields and methods:
Global
Class 1 Methods: 4;
Resolving local member refs: 2 -> 2 defs, 0 refs, 0 unresolved
Emitting events and properties:
Global
Class 1
Resolving local member refs: 0 -> 0 defs, 0 refs, 0 unresolved
Writing PE file
Operation completed successfully
C:\Windows\Microsoft.NET\Framework\v2.0.50727>ngen Marshal.exe
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.1433
Installing assembly C:\Windows\Microsoft.NET\Framework\v2.0.50727\Marshal.exe
Compiling assembly C:\Windows\Microsoft.NET\Framework\v2.0.50727\Marshal.exe
...
marshal, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
C:\Windows\Microsoft.NET\Framework\v2.0.50727>sn -k Marshal.key
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Key pair written to Marshal.key
C:\Windows\Microsoft.NET\Framework\v2.0.50727>sn -p Marshal.key Marshal.PublicKey
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Public key written to Marshal.PublicKey
C:\Windows\Microsoft.NET\Framework\v2.0.50727>sn -tp Marshal.PublicKey
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Public key is
0024000004800000940000000602000000240000525341310004000001000100d7eff35e758fb7
6027164c638288029538cc3c15588efb97c090dc6b45ecbf2dd3afd9ad5a13e26aa3698b9cdf87
905039c73174a4cd99a93f98e4e49a5dc4eaa62423f542056b058dd8ae69ac54b324ba76b5be29
487e8b3ad49f2be7896aa56478bfda857526ea69823dbceb019bd378a4ee607f060b7583fa9a3a
fdcfe3ae
Public key token is bbd777f8c6ef0f35
C:\Windows\Microsoft.NET\Framework\v2.0.50727>csc.exe /keyfile:Marshal.key Marshal.cs C:\Windows\Microsoft.NET\Framework\v2.0.50727>gacutil -i Marshal.exe
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Assembly successfully added to the cache
C:\Windows\Microsoft.NET\Framework\v2.0.50727>csc /doc:Marshal.xml Marshal.cs
C:\Windows\Microsoft.NET\Framework\v2.0.50727>notepad Marshal.xml
C:\Windows\Microsoft.NET\Framework\v2.0.50727>xsd.exe /c Marshal.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Writing file 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\Marshal.xsd'.
PInvoke provides a way for managd coe to all unmanaged functions implmented in aC DLL. The .NET devloper can avoid locating and invoking the corect function export. Current tehnical documentation states that many companies keep large code bases of legacy code. The need to become proficient with interop is evident.
Basics of .NET Framework multithreaded programming
Writing multithreaded .NET applications can be tough for beginning programmers. I'll show you how to create threads and how the syntax differs for VB.NET and C#.
Multithreaded programming can be a little daunting for novice programmers, but the .NET Framework has considerably simplified the process. In fact, almost any programmer can delve into it and master the fundamentals. I'll introduce you to the basics of multithreaded programming and provide some sample code you can use to start experimenting.
Creating threads
To get multithreaded programming running, you must first create an instance of a Thread. You don’t have much in the way of options, as there is only one constructor:
C#
public Thread( ThreadStart start );
The parameter ThreadStart is a delegate to the method that is the starting point of the thread. The signature of the delegate is a method with no parameters and returns nothing, as demonstrated below:
C#
public delegate void ThreadStart();
Starting threads
One thing that may not be obvious when you first start working with threads is that creating an instance of the Thread object does not cause the thread to start. To get the thread to start, you need to call the Thread class’s Start() method, like this:
C#
public void Start();
Getting a thread to sleep
When developing a thread, you may find that you don’t need it to continually run, or you might want to delay the thread while some other thread runs. To handle this, you could place a delay loop like a “do-nothing” for-loop. But that would waste CPU cycles. Instead, you should temporarily stop the thread or put it to sleep.
Doing this couldn’t be easier. Simply add the following static/shared Sleep() method:
C#
public static void Sleep(int);
This line causes the current thread to go to sleep for the interval specified either in an integer value of milliseconds, as the examples above show, or using a TimeSpan structure.
The Sleep() method also takes two special values: Infinite, which means sleep forever, and 0, meaning give up the rest of the thread’s current CPU time slice.
A neat thing to remember is that the main function is also a thread. This means you can use Sleep() to make any application sleep.
Aborting threads
You might, on occasion, require that a thread be terminated within another thread before it runs through to its normal end. In such a case, you would call the Abort() method. Normally, this method will permanently stop the execution of a specified thread:
C#
public void Abort();
Notice, I said normally. When a thread is requested to stop with the Abort() method, a ThreadAbortException is actually thrown within the thread. This exception, like any other, can be caught. But unlike most other exceptions, the ThreadAbortException is special: It gets rethrown at the end of the catch block unless the aborting thread’s ResetAbort() method is called. Calling the ResetAbort() method cancels the abort, which, in turn, prevents the ThreadAbortException from stopping the thread.
C#
public static void ResetAbort();
Be aware that an aborted thread can't be restarted. If you attempt to do so, a ThreadStateException exception is thrown instead.
Joining threads
What if you want to execute something immediately after the threads finish? Or more generally, how do you handle the scenario where one thread needs to wait for another thread to complete before continuing? You need to join the threads using the Join() method:
C#
public void Join();
You can join threads by using one of the three overloaded Join() methods. The first overloaded method, as shown above, takes no parameters and waits until the thread completes. The second takes an Integer/int/Int32 parameter and then waits the parameter’s specified number of milliseconds or for the thread to terminate, whichever is shorter. The third overload takes a TimeSpan and functions the same as the previous overload.
Interrupting threads
It's possible to take a worker thread that is waiting for something to happen and place it in a tight loop, waiting for that event to occur. But again, this would be a big waste of CPU cycles. It's better to let the worker thread sleep and then be woken up when the event occurs. We can do that using a combination of Sleep() and Interrupt() methods in conjunction with ThreadInterruptedException:
C#
public void Interrupt();
The basic idea is to put the worker thread to sleep using the Sleep() method and then to use the Interrupt() member method to interrupt the sleep of the worker thread when the required event occurs. Simple enough, except that the Interrupt() method throws a ThreadInterruptedException instead of just terminating the Sleep() method. Thus, you need to use exception handling and place the Sleep() method in a try block. Then, have the worker thread continue execution in the catch block.
For instance, in the worker thread, you'd have the following (pseudo) code:
Try
<< Wait for event to occur >>
catch << A ThreadInterruptedException >>
<
You'd then have some other thread execute the Interrupt() method to get the above thread to continue.
Suspending and resuming threads
Interrupting will work fine if the worker thread knows when to go to sleep. You may also need to allow another thread to temporarily stop a different thread and then restart it again later.
For example, a worker thread could be doing some intense number crunching when along comes another thread that needs to put a large graphic up on the monitor ASAP. (User interface should almost always get priority.)
This scenario can be resolved in at least three ways. You could do nothing special and let the multithreading engine slowly display the graphic. You could raise the priority of the graphic display thread (or lower the priority of the worker thread), thus giving the graphic display more cycles. Or you could suspend the worker thread using the Suspend() method:
C#
public void Suspend();
Then, you could draw the graphic and resume the worker thread using the Resume() method:
C#
public void Resume();
Background and foreground threads
Two types of threads are available. The first is the foreground thread, which runs until it reaches its exit point or is aborted. The second is the background thread, which terminates upon the completion of the last foreground thread. When you create a thread using the Thread class’ constructor, you create a foreground thread by default. To change the thread to a background thread, you must change its IsBackground property to true. The IsBackground property can be toggled at any time while the thread is running.
As you start to play with threads, you'll come to realise that even though they're easy to code, they're not easy to work with. You will spend a lot of time just trying to get your threads to synchronise. Hence, the inordinate number of Sleep() and Join() method calls placed in the simple example.
Remember, these are just the basics.
Page Lifecycle Methods in ASP.NET 2.0
csharpwithdj.blogspot.com
Understanding the lifecycle of a page/control in ASP.NET 1+ was paramount to writing good, clean code - not to mention the steep decline in frustrating programming sessions. If you do not learn the page lifecycle, including what the events do, as well as the sequence in which they occur, you will indeed get mad and sad. Crying may occur.
In ASP.NET 1+, there were about 8 methods/events that were important to understand (about 12+ if you are a control developer). In ASP.NET 2.0, this has been increased significantly to give the developer more opportunities to inject logic at different points of the page's life.
As I attempted to locate a good source for the new page lifecycle, I found incomplete and beta lists, which were typically out of date. I've compiled a list of events/methods that occur during a typical page request with as much data as I could find. Most of the method descriptions are from MSDN2.
Method Postback Control
Constructor Always All
Construct Always Page
TestDeviceFilter Page
Used to determine which device filter is in place, and use this information to decide how to display the page.
AddParsedSubObject Always All
Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object.
DeterminePostBackMode Always Page
Returns a NameValueCollection object that contains the data posted back to the page. The presence of the page hidden fields VIEWSTATE and EVENTTARGET is used to help determine whether a postback event has occurred. The IsPostBack property is set when the DeterminePostBackMode method is called.
OnPreInit Always Page
Called at the beginning of the page initialization stage. After the OnPreInit method is called, personalization information is loaded and the page theme, if any, is initialized. This is also the preferred stage to dynamically define a PageTheme or MasterPage for the Page.
OnInit Always All
Performs the initialization and setup steps required to create a Page instance. In this stage of the page's life cycle, declared server controls on the page are initialized to their default state; however, the view state of each control is not yet populated. A control on the page cannot access other server controls on the page during the Page_Init phase, regardless of whether the other controls are child or parent controls. Other server controls are not guaranteed to be created and ready for access.
OnInitComplete Always Page
Called after page initialization is complete. In this stage of the page's life cycle, all declared controls on the page are initialized, but the page's view state is not yet populated. You can access server controls, but they will not yet contain information returned from the user.
LoadPageStateFromPersistenceMedium Postback Page
Uses the Load method of the System.Web.UI.PageStatePersister object referenced by the PageStatePersister property to load any saved view-state information for the Page object.
LoadControlState Postback All
Restores control-state information from a previous page request that was saved by the SaveControlState method.
LoadViewState Postback All
Restores view-state information from a previous page request that was saved by the SaveViewState method.
OnPreLoad Always Page
Called after all postback data returned from the user is loaded. At this stage in the page's life cycle, view-state information and postback data for declared controls and controls created during the initialization stage are loaded into the page's controls. Controls created in the OnPreLoad method will also be loaded with view-state and postback data.
OnLoad Always All
Notifies the server control that it should perform actions common to each HTTP request for the page it is associated with, such as setting up a database query. At this stage in the page lifecycle, server controls in the hierarchy are created and initialized, view state is restored, and form controls reflect client-side data.
RaisePostBackEvent Postback All
Notifies the server control that caused the postback that it should handle an incoming postback event.
OnLoadComplete Always Page
At this point in the page life cycle, all postback data and view-state data is loaded into controls on the page.
OnPreRender Always All
Notifies the server control to perform any necessary prerendering steps prior to saving view state and rendering content.
OnPreRenderComplete Always Page
At this stage of the page life cycle, all controls are created and the page is ready to render the output. This is the last event called before the page's view state is saved.
SaveControlState Always All
Saves any server control state changes that have occurred since the time the page was posted back to the server. If there is no state associated with the control, this method returns a null reference. Custom controls using control state must call the RegisterRequiresControlState method on the Page before saving control state.
SaveViewState Always All
Saves any server control view-state changes that have occurred since the time the page was posted back to the server. If there is no view state associated with the control, this method returns a null reference.
SavePageStateToPersistenceMedium Always Page
Saves any view-state and control-state information for the page. The SavePageStateToPersistenceMedium method uses the Save method of the System.Web.UI.PageStatePersister object referenced by the PageStatePersister property to store view-state and control-state information for the page.
Render Always All
Initializes the HtmlTextWriter object and calls on the child controls of the Page to render. The Render method is responsible for creating the text and markup that is sent to the client browser. The default Render method calls RenderChildren to write the text and markup for the controls contained on the page.
OnUnload Always All
Used to do target-specific processing in the Unload stage of the control lifecycle. Typically, these are cleanup functions that precede disposition of the control.
If I'm missing any significant methods, please comment.
Understanding the lifecycle of a page/control in ASP.NET 1+ was paramount to writing good, clean code - not to mention the steep decline in frustrating programming sessions. If you do not learn the page lifecycle, including what the events do, as well as the sequence in which they occur, you will indeed get mad and sad. Crying may occur.
In ASP.NET 1+, there were about 8 methods/events that were important to understand (about 12+ if you are a control developer). In ASP.NET 2.0, this has been increased significantly to give the developer more opportunities to inject logic at different points of the page's life.
As I attempted to locate a good source for the new page lifecycle, I found incomplete and beta lists, which were typically out of date. I've compiled a list of events/methods that occur during a typical page request with as much data as I could find. Most of the method descriptions are from MSDN2.
Method Postback Control
Constructor Always All
Construct Always Page
TestDeviceFilter Page
Used to determine which device filter is in place, and use this information to decide how to display the page.
AddParsedSubObject Always All
Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object.
DeterminePostBackMode Always Page
Returns a NameValueCollection object that contains the data posted back to the page. The presence of the page hidden fields VIEWSTATE and EVENTTARGET is used to help determine whether a postback event has occurred. The IsPostBack property is set when the DeterminePostBackMode method is called.
OnPreInit Always Page
Called at the beginning of the page initialization stage. After the OnPreInit method is called, personalization information is loaded and the page theme, if any, is initialized. This is also the preferred stage to dynamically define a PageTheme or MasterPage for the Page.
OnInit Always All
Performs the initialization and setup steps required to create a Page instance. In this stage of the page's life cycle, declared server controls on the page are initialized to their default state; however, the view state of each control is not yet populated. A control on the page cannot access other server controls on the page during the Page_Init phase, regardless of whether the other controls are child or parent controls. Other server controls are not guaranteed to be created and ready for access.
OnInitComplete Always Page
Called after page initialization is complete. In this stage of the page's life cycle, all declared controls on the page are initialized, but the page's view state is not yet populated. You can access server controls, but they will not yet contain information returned from the user.
LoadPageStateFromPersistenceMedium Postback Page
Uses the Load method of the System.Web.UI.PageStatePersister object referenced by the PageStatePersister property to load any saved view-state information for the Page object.
LoadControlState Postback All
Restores control-state information from a previous page request that was saved by the SaveControlState method.
LoadViewState Postback All
Restores view-state information from a previous page request that was saved by the SaveViewState method.
OnPreLoad Always Page
Called after all postback data returned from the user is loaded. At this stage in the page's life cycle, view-state information and postback data for declared controls and controls created during the initialization stage are loaded into the page's controls. Controls created in the OnPreLoad method will also be loaded with view-state and postback data.
OnLoad Always All
Notifies the server control that it should perform actions common to each HTTP request for the page it is associated with, such as setting up a database query. At this stage in the page lifecycle, server controls in the hierarchy are created and initialized, view state is restored, and form controls reflect client-side data.
RaisePostBackEvent Postback All
Notifies the server control that caused the postback that it should handle an incoming postback event.
OnLoadComplete Always Page
At this point in the page life cycle, all postback data and view-state data is loaded into controls on the page.
OnPreRender Always All
Notifies the server control to perform any necessary prerendering steps prior to saving view state and rendering content.
OnPreRenderComplete Always Page
At this stage of the page life cycle, all controls are created and the page is ready to render the output. This is the last event called before the page's view state is saved.
SaveControlState Always All
Saves any server control state changes that have occurred since the time the page was posted back to the server. If there is no state associated with the control, this method returns a null reference. Custom controls using control state must call the RegisterRequiresControlState method on the Page before saving control state.
SaveViewState Always All
Saves any server control view-state changes that have occurred since the time the page was posted back to the server. If there is no view state associated with the control, this method returns a null reference.
SavePageStateToPersistenceMedium Always Page
Saves any view-state and control-state information for the page. The SavePageStateToPersistenceMedium method uses the Save method of the System.Web.UI.PageStatePersister object referenced by the PageStatePersister property to store view-state and control-state information for the page.
Render Always All
Initializes the HtmlTextWriter object and calls on the child controls of the Page to render. The Render method is responsible for creating the text and markup that is sent to the client browser. The default Render method calls RenderChildren to write the text and markup for the controls contained on the page.
OnUnload Always All
Used to do target-specific processing in the Unload stage of the control lifecycle. Typically, these are cleanup functions that precede disposition of the control.
If I'm missing any significant methods, please comment.
HTTP Handlers in ASP.NET
csharpwithdj.blogspot.com
Introduction
The low level Request and Response API to service incoming Http requests are Http Handlers in Asp.Net. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
In this article, I will explain how to extend the functionality of web server by using Http handlers and How to protect files using Http handlers.
Methods in Http Handler
The following are the methods in Http Handlers
Method Name Description
ProcessRequest Used to call Http Requests.
IsReusable To check the reusability of same instance handler with a new request of same type.
Configuring HTTP Handlers
Theconfiguration section handler is responsible for mapping incoming URLs to the IHttpHandler or IHttpHandlerFactory class. It can be declared at the computer, site, or application level. Subdirectories inherit these settings.
Administrators use thetag directive to configure the section. directives are interpreted and processed in a top-down sequential order. Use the following syntax for the section handler:
Creating HTTP Handlers
To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures:
void ProcessRequest(HttpContext);
bool IsReusable {get;}
Customized Http Handler
By customizing http handlers, new functionalities can be added to Web Server. Files with new extensions like .text for a text file can be handled by Web Server by using http handlers. The future of customization can lead to hosting .jsp pages in IIS by finding adequate ISAPI extensions. The following steps are involved to create customized http handler:
Create a C# class library as "Examplehandler"
Name class as "Handlerclass.cs"
using System;
using System.Web;
using System.Web.SessionState;
namespace ExampleHandler
{
///
/// Summary description for Examplehandler.
///
public class Handlerclass : IHttpHandler
{
public Handlerclass()
{
//
// TODO: Add constructor logic here
//
}
#region Implementation of IHttpHandler
public void ProcessRequest(System.Web.HttpContext context)
{
HttpResponse objResponse = context.Response ;
HttpSessionState objSession = context.Session ;
objResponse.Write("
Hello World from Handler") ;
Introduction
The low level Request and Response API to service incoming Http requests are Http Handlers in Asp.Net. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
In this article, I will explain how to extend the functionality of web server by using Http handlers and How to protect files using Http handlers.
Methods in Http Handler
The following are the methods in Http Handlers
Method Name Description
ProcessRequest Used to call Http Requests.
IsReusable To check the reusability of same instance handler with a new request of same type.
Configuring HTTP Handlers
The
Administrators use the
Creating HTTP Handlers
To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures:
void ProcessRequest(HttpContext);
bool IsReusable {get;}
Customized Http Handler
By customizing http handlers, new functionalities can be added to Web Server. Files with new extensions like .text for a text file can be handled by Web Server by using http handlers. The future of customization can lead to hosting .jsp pages in IIS by finding adequate ISAPI extensions. The following steps are involved to create customized http handler:
Create a C# class library as "Examplehandler"
Name class as "Handlerclass.cs"
using System;
using System.Web;
using System.Web.SessionState;
namespace ExampleHandler
{
///
/// Summary description for Examplehandler.
///
public class Handlerclass : IHttpHandler
{
public Handlerclass()
{
//
// TODO: Add constructor logic here
//
}
#region Implementation of IHttpHandler
public void ProcessRequest(System.Web.HttpContext context)
{
HttpResponse objResponse = context.Response ;
HttpSessionState objSession = context.Session ;
objResponse.Write("
Hello World from Handler") ;
objResponse.Write("") ;
}
public bool IsReusable
{
get
{
return true;
}
}
#endregion
}
}
Compile it and place it in the bin directory of TestApp project.
Step 2
Register this handler by adding the following text in the web.config file:
Step 3
Go to Internet Information Services and select Default Web Site. Right Click and Select Properties. Select Home Directory and click on Configuration. The Following Screen will appear:
Click on Add and give executable path and new extension and click OK.
Close IIS and Run TestApp website by using the URL
http://localhost/Testapp/hello.text
The output will be as follows:
HttpForbiddenHandler
The sensitive files can be protected by Http Forbidden Handler. The Database driven web sites using MS Access, the .mdb file has to be protected. To protect the .mdb files, we must follow the two steps given below:
Map .mdb file in IIS
Register the file extension in web.config with HttpForbiddenHandler.
In the Web.Config file, Add this Http handler section:
Conclusion
The Http Handlers are often useful when the services provided by the high-level page framework abstraction are not required for processing the HTTP request. Common uses of handlers include filters and CGI-like applications, especially those that return binary data.
Introduction to ASP.NET HTTP Module
csharpwithdj.blogspot.com
This article will help the users to examine the use of HTTP Modules and their use in extending the pipeline. The HTTP Pipeline is a series of extensible objects that are initiated by the ASP.NET runtime in order to process a request.
Summary
This article will help the users to examine the use of HTTP Modules and their use in extending the pipeline. The HTTP Pipeline is a series of extensible objects that are initiated by the ASP.NET runtime in order to process a request. Http Handlers and Http Modules are .NET components that serve as the main points of extensibility in the pipeline. This article, will demonstrate how to create an HTTP Module. Http modules are filters that can pre and post-process requests as they pass through the pipeline. As a matter of fact, many of the services provided by ASP.NET are implemented as HTTP Modules. Examples are modules which are used to implement ASP.NET security as well as ASP.NET session state.
At the most fundamental level, ASP.NET HTTP Modules are classes which implement the System.Web.IHttpModule interface, illustrated below:
public interface IHttpModule
{
void Dispose();
void Init(HttpApplication context);
}
In order to insure that your HttpHandler is hooked up to the HTTP pipeline requires an entry in the application's web config. or the machine.config file. The same holds true for HTTP modules. When an HTTP Module is added to the pipeline, the ASP.NET runtime will call the methods of the IHttpModule interface at the appropriate times. When the module is first created by the runtime, the Init method is called. As illustrated above, the parameter passed into the Init method allows your code to tie into the HttpApplication object.
The following table lists the key events exposed by the HttpApplication object. Note that all these events are implemented as multicast delegates so that numerous modules can register for each one.
Event
When It's Called
BeginRequest
Before request processing starts
AuthenticateRequest
To authenticate client
AuthorizeRequest
To perform access check
ResolveRequestCache
To get response from cache
AcquireRequestState
To load session state
PreRequestHandlerExecute
Before request sent to handler
PostRequestHandlerExecute
After request sent to handler
ReleaseRequestState
To store session state
UpdateRequestCache
To update response cache
EndRequest
After processing ends
PreSendRequestHeaders
Before buffered response headers sent
PreSendRequestContent
Before buffered response body sent
In addition to the above methods, we can also respond to the methods in the global.asax file for the HttpApplication object. These events include the session start and end events, as well as the start and end events for the application.
Let's create a simple HTTP module and hook it up to the pipeline. In the following example, the SampleModule class implements the IHttpModule interface. When the Init method is called by the runtime, the module "hooks up" to the events of the HttpApplication object. In this example, we have registered for the application's BeginRequest event as well as its EndRequest event. In our implementation of these methods, we simply record the time the request was sent in, and then we record the difference between times when the request is finished. In order to send the output to the response stream in some fashion, we add the result to the header of the HTTP response.
using System;
using System.Web;
namespace MikeModules
{
public class SampleModule : IHttpModule
{
DateTime beginrequest;
public void Init(HttpApplication app)
{
// register for events created by the pipeline
app.BeginRequest += new EventHandler(this.OnBeginRequest);
pp.EndRequest += new EventHandler(this.OnEndRequest);
}
public void Dispose() {}
public void OnBeginRequest(object o, EventArgs args)
{
// obtain the time of the current request
beginrequest = DateTime.Now;
}
public void OnEndRequest(object o, EventArgs args)
{
// get the time elapsed for the request
TimeSpan elapsedtime = DateTime.Now - beginrequest;
// get access to application object and the context object
HttpApplication app =(HttpApplication) o;
HttpContext ctx = app.Context;
// add header to HTTP response
ctx.Response.AppendHeader("ElapsedTime", elapsedtime.ToString());
}
}
}
Similar to ASP.NET HTTP Handlers, we need to notify the ASP.NET runtime that we wish to hook up our module to the pipeline. Once the module has been built and deployed to the application's bin directory or the machine's GAC, it must be registered in either the web.config file or the machine.config file. The following code adds a module to the
IIS metabase:
In order to add our module, we must implement the following code in the web.config file:
In this example, the Web.config file tells the pipeline to attach an instance of the SampleModules.SimpleModule class to every HttpApplication object instantiated to service requests that target this application.
One of the most common operations when intercepting an HTTP request is to terminate the request. This is very common in custom authentication modules added to ASP.NET. In this case, the HttpApplication class has a method called CompleteRequest that is called for finishing the request. Calling CompleteRequest with the appropriate status codes can terminate the request.
ASP.NET HTTP Modules can be used to further extend the HTTP pipeline. Many of the services provided by the runtime are indeed implemented as HTTP modules. Common uses for creating custom modules include custom authentication and authorization schemes, in addition to any other filtering services that your application needs.
This article will help the users to examine the use of HTTP Modules and their use in extending the pipeline. The HTTP Pipeline is a series of extensible objects that are initiated by the ASP.NET runtime in order to process a request.
Summary
This article will help the users to examine the use of HTTP Modules and their use in extending the pipeline. The HTTP Pipeline is a series of extensible objects that are initiated by the ASP.NET runtime in order to process a request. Http Handlers and Http Modules are .NET components that serve as the main points of extensibility in the pipeline. This article, will demonstrate how to create an HTTP Module. Http modules are filters that can pre and post-process requests as they pass through the pipeline. As a matter of fact, many of the services provided by ASP.NET are implemented as HTTP Modules. Examples are modules which are used to implement ASP.NET security as well as ASP.NET session state.
At the most fundamental level, ASP.NET HTTP Modules are classes which implement the System.Web.IHttpModule interface, illustrated below:
public interface IHttpModule
{
void Dispose();
void Init(HttpApplication context);
}
In order to insure that your HttpHandler is hooked up to the HTTP pipeline requires an entry in the application's web config. or the machine.config file. The same holds true for HTTP modules. When an HTTP Module is added to the pipeline, the ASP.NET runtime will call the methods of the IHttpModule interface at the appropriate times. When the module is first created by the runtime, the Init method is called. As illustrated above, the parameter passed into the Init method allows your code to tie into the HttpApplication object.
The following table lists the key events exposed by the HttpApplication object. Note that all these events are implemented as multicast delegates so that numerous modules can register for each one.
Event
When It's Called
BeginRequest
Before request processing starts
AuthenticateRequest
To authenticate client
AuthorizeRequest
To perform access check
ResolveRequestCache
To get response from cache
AcquireRequestState
To load session state
PreRequestHandlerExecute
Before request sent to handler
PostRequestHandlerExecute
After request sent to handler
ReleaseRequestState
To store session state
UpdateRequestCache
To update response cache
EndRequest
After processing ends
PreSendRequestHeaders
Before buffered response headers sent
PreSendRequestContent
Before buffered response body sent
In addition to the above methods, we can also respond to the methods in the global.asax file for the HttpApplication object. These events include the session start and end events, as well as the start and end events for the application.
Let's create a simple HTTP module and hook it up to the pipeline. In the following example, the SampleModule class implements the IHttpModule interface. When the Init method is called by the runtime, the module "hooks up" to the events of the HttpApplication object. In this example, we have registered for the application's BeginRequest event as well as its EndRequest event. In our implementation of these methods, we simply record the time the request was sent in, and then we record the difference between times when the request is finished. In order to send the output to the response stream in some fashion, we add the result to the header of the HTTP response.
using System;
using System.Web;
namespace MikeModules
{
public class SampleModule : IHttpModule
{
DateTime beginrequest;
public void Init(HttpApplication app)
{
// register for events created by the pipeline
app.BeginRequest += new EventHandler(this.OnBeginRequest);
pp.EndRequest += new EventHandler(this.OnEndRequest);
}
public void Dispose() {}
public void OnBeginRequest(object o, EventArgs args)
{
// obtain the time of the current request
beginrequest = DateTime.Now;
}
public void OnEndRequest(object o, EventArgs args)
{
// get the time elapsed for the request
TimeSpan elapsedtime = DateTime.Now - beginrequest;
// get access to application object and the context object
HttpApplication app =(HttpApplication) o;
HttpContext ctx = app.Context;
// add header to HTTP response
ctx.Response.AppendHeader("ElapsedTime", elapsedtime.ToString());
}
}
}
Similar to ASP.NET HTTP Handlers, we need to notify the ASP.NET runtime that we wish to hook up our module to the pipeline. Once the module has been built and deployed to the application's bin directory or the machine's GAC, it must be registered in either the web.config file or the machine.config file. The following code adds a module to the
IIS metabase:
In order to add our module, we must implement the following code in the web.config file:
In this example, the Web.config file tells the pipeline to attach an instance of the SampleModules.SimpleModule class to every HttpApplication object instantiated to service requests that target this application.
One of the most common operations when intercepting an HTTP request is to terminate the request. This is very common in custom authentication modules added to ASP.NET. In this case, the HttpApplication class has a method called CompleteRequest that is called for finishing the request. Calling CompleteRequest with the appropriate status codes can terminate the request.
ASP.NET HTTP Modules can be used to further extend the HTTP pipeline. Many of the services provided by the runtime are indeed implemented as HTTP modules. Common uses for creating custom modules include custom authentication and authorization schemes, in addition to any other filtering services that your application needs.
Subscribe to:
Posts (Atom)