Friday, May 9, 2008

ASP.NET Authentication

ASP.NET Authentication

Authentication is the process of obtaining identification credentials from a user ( such as name and password ), and validating those credentials against some authority.

If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.

ASP.NET implements authentication through authentication providers, the modules that contain the code to authenticate the requestor's credentials. This section describes the authentication providers built into ASP.NET.


The Windows Authentication Provider
Describes how to use the Windows Authentication provider The Passport Authentication Provider
Describes how to use the Passport Authentication provider.
The Forms Authentication Provider
Describes how to use the Forms Authentication provider.


The Windows Authentication Provider

The WindowsAuthenticationModule provider relies on IIS to provide authenticated users, using any of the mechanisms IIS supports. The provider module constructs a WindowsIdentity object. The default implementation constructs a WindowsPrincipal object and attaches it to the application context. The WindowsPrincipal object maps identities to Windows groups.

If you use IIS authentication, the provider module uses the authenticated identity passed in from IIS. IIS authenticates the identity using basic, digest, or Windows authentication, or some combination of them. You can use impersonation and you can use NTFS ACL permissions to restrict or allow access to protected resources. This is the provider configuration you should use if you want to implement site security with a minimum of ASP.NET coding.

An important reason to use the Windows Authentication provider is to implement an impersonation scheme that can use any of the authentication methods that might have already been performed by IIS before passing the request to the ASP.NET application. To do this, set the authentication mode to Windows, and confirm that the impersonate element is set to true, as shown in the following example:



Please note that configuring an ASP.NET application has no effect on the IIS Directory Security settings. The systems are completely independent and are applied in sequence. In addition to selecting an authentication mode for an ASP.NET application, it is also important to configure IIS authentication appropriately.

Next you must set the NTFS ACLs to allow access only to the proper identities. If you want to enable impersonation for only a short time during request processing, you can do it by using an impersonation context and WindowsIdentity.Impersonate.

NOTE: A Windows identity for an anonymous user cannot be impersonated because it causes an exception.

First, set the impersonate element to false, then set up a context using the WindowsIdentity.Impersonate method, as follows:

WindowsImpersonationContext context =
WindowsIdentity.Impersonate ( impersonateToken );
// do whatever.
context.Undo ( );

Dim context As WindowsImpersonationContext = _
WindowsIdentity.Impersonate ( impersonateToken )
' do whatever.
context.Undo ( )

C# VB

Notice that you can use context.Undo for identity reversion.

As mentioned earlier, you can implement a custom Windows authorization scheme by using a WindowsAuthenticate_OnAuthenticate event handler to create a WindowsPrincipal or a GenericPrincipal object from a WindowsIdentity object. You can then use one of the new objects to implement your own custom authentication scheme. The WindowsPrincipal object maps identities to Windows groups. The default implementation constructs a WindowsPrincipal object and attaches it to the application context.

See Also

Thursday, May 8, 2008

How ASP.NET Security Works

How ASP.NET Security Works
Essentially, securing an ASP.NET Web application entails controlling access to its resources.

The ASP.NET security framework accomplishes this by working in conjunction with the various security subsystems present in the machine where ASP.NET is installed. This includes security provided by the operating system ( NTFS file access permissions ) as well as security provided by IIS ( host or IP address authorization ).

And since ASP.NET is built on the Microsoft .NET Framework, the ASP.NET application developer also has access to all of the built-in security features of the .NET Framework, such as code access security and role-based user-access security.

It is imperative to understand how the various security subsystems interact, to be able to secure your ASP.NET application effectively.

Basically, to enable security for an ASP.NET application, you need to configure the application to implement, at the very least, the two fundamental functionalities described in the following table.

Security function---Authentication
Description ---- The process of obtaining identification credentials from a user ( such as name and password ), and validating those credentials against some authority.

Security function---Authorization
Description ---- The process of controlling access to resources based on the authenticated identification credentials ( such as role ).

ASP.NET implements authentication through authentication providers, the modules that contain the code to authenticate user credentials. ASP.NET includes the following authentication providers.

ASP.NET Authentication Provider
Windows Authentication
Description--- Provider ASP.NET uses Windows authentication in conjunction with IIS authentication. Authentication is performed by IIS in one of three ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize access.

ASP.NET Authentication Provider
Forms Authentication
Description----Provider A system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection. The user provides credentials and submits the form. If the application authenticates the request, the system issues a form that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the form in the request headers; they are authenticated and authorized by an ASP.NET handler using whatever validation method the application developer specifies.

ASP.NET Authentication Provider
Passport Authentication
Description----Provider Centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites.

To enable authentication for an ASP.NET application, you need to create an authentication section entry in the application root configuration file. The general syntax for the authentication section is as follows:



mode = " [ Windows | Forms | Passport | None ] ">



The mode is set to one of the authentication methods: Windows, Forms, Passport, or None. The default is Windows.

The authentication mode cannot be set at a level below the application root directory. Like all other configuration settings, all subdirectories within the application boundary inherit the authentication mode, unless explicitly overriden in a child configuration file.

Wednesday, May 7, 2008

ASP.NET Security

ASP.NET Security
Lately at SCS I have been assigned to build up the security module and related tasks in the Real Estate Management System we are building. So I decided to share what I have learned in this past period and of course to hear from the community to find optimal solutions for the scenarios I worked with, all what I write here might be repeated but I will share it anyway.

In this part, I will show some important basic points that should be clear to everyone before implementing asp.net security tasks.

Looking at any web application, the security is a matter of users/passwords/roles/groups... etc. While ASP.NET provides more mechanisms for authentication and authorization that work with the Operating system,IIS and .NET framework classes. So the ASP.NET application runs through these 3 levels.

IIS Level
ASP.NET worker process level
ASP.NET pipeline level
So, the Big Question, What is the Identity that runs my application ?

First, When an IIS web server machine receives an ASP.NET request, the IIS assigns it to one of the threads pooled in it, IIS runs under the SYSTEM account which has all the powers in a Microsoft Windows operating system. You can read extra information in the ASP.NET Application Life Cycle Overview article on the msdn.

Next, the 3 security levels run on the request one after the other.

1- The IIS thread context : the identity of this thread is determined according to the settings of the website in the IIS which has one of the following settings:

Basic authentication prompts the user for a user name and a password, also called credentials, which are sent unencrypted over the network.
Integrated Windows authentication uses hashing technology to scramble user names and password before sending them over the network.
Digest authentication operates much like Basic authentication, except that passwords are sent across the network as a hash value. Digest authentication is only available on domains with domain controllers running Windows Server operating systems.
Anonymous authentication allows everyone access to the public areas of the Web sites, without asking for a user name or password. When this is set, the identity impersonates the identity set in the textboxes, with the default user name IUSR_MACHINENAME. Like shown in the figure down below.

Tuesday, May 6, 2008

Microsoft .NET Framework

Introducing the Microsoft .NET Framework

.NET (dot-net) is the name Microsoft gives to its general vision of the future of computing, the view being of a world in which many applications run in a distributed manner across the Internet. We can identify a number of different motivations driving this vision.

Firstly, distributed computing is rather like object oriented programming, in that it encourages specialised code to be collected in one place, rather than copied redundantly in lots of places. There are thus potential efficiency gains to be made in moving to the distributed model.

Secondly, by collecting specialised code in one place and opening up a generally accessible interface to it, different types of machines (phones, handhelds, desktops, etc.) can all be supported with the same code. Hence Microsoft's 'run-anywhere' aspiration.

Thirdly, by controlling real-time access to some of the distributed nodes (especially those concerning authentication), companies like Microsoft can control more easily the running of its applications. It moves applications further into the area of 'services provided' rather than 'objects owned'.

Interestingly, in taking on the .NET vision, Microsoft seems to have given up some of its proprietary tendencies (whereby all the technology it touched was warped towards its Windows operating system). Because it sees its future as providing software services in distributed applications, the .NET framework has been written so that applications on other platforms will be able to access these services. For example, .NET has been built upon open standard technologies like XML and SOAP.

At the development end of the .NET vision is the .NET Framework. This contains the Common Language Runtime, the .NET Framework Classes, and higher-level features like ASP.NET (the next generation of Active Server Pages technologies) and WinForms (for developing desktop applications).

The Common Language Runtime (CLR) manages the execution of code compiled for the .NET platform. The CLR has two interesting features. Firstly, its specification has been opened up so that it can be ported to non-Windows platforms. Secondly, any number of different languages can be used to manipulate the .NET framework classes, and the CLR will support them. This has led one commentator to claim that under .NET the language one uses is a 'lifestyle choice'.

Not all of the supported languages fit entirely neatly into the .NET framework, however (in some cases the fit has been somewhat Procrustean). But the one language that is guaranteed to fit in perfectly is C#. This new language, a successor to C++, has been released in conjunction with the .NET framework, and is likely to be the language of choice for many developers working on .NET applications.

Monday, May 5, 2008

State Management Techniques in ASP.NET-2

Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage
of sessions object for state management can create load on server causing performance degradation
Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the section in the application's web.config file.
Configuration information:

sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout =
sqlconnectionstring =
server =
port =
Mode:

This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.

Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:

This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
• In process mode (in-memory)- State information is stored in memory of web server
• Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
• Database mode รข€“ session state is maintained on a SQL Server database.
In process mode:

This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
Configuration information:
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Fastest mode
• Simple configuration
Disadvantages:
• Session data will be lost if the worker process or application domain recycles
• Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):

This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.
Net start aspnet_state
Configuration information:

StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
• Supports web farm and web garden configuration
• Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
• Out-of-process mode provides slower access compared to In process
• Requires serializing data
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.
Configuration Information:
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Supports web farm and web garden configuration
• Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Disadvantages:
• Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.

State Management Techniques in ASP.NET-1

This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.

Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client side state management options.
Client side State management Options:

ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.
Cookie:

A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.

Let's see an example which makes use of cookies to customize web page.

if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
• Simplicity
Disadvantages:
• Cookies can be disabled on user browsers
• Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
• Inappropriate for sensitive data
Hidden fields:

Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
• Simple to implement for a page specific data
• Can store small amount of data so they take less size.
Disadvantages:
• Inappropriate for sensitive data
• Hidden field values can be intercepted(clearly visible) when passed over a network
View State:

View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;

//Reading items from ViewState
Response.Write(ViewState["myviewstate"]);

Advantages:
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• Overhead in encoding View State values
• Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Cross paging functionality makes it redundant
• Easily modified by end user


NEXT>>>

Saturday, May 3, 2008

Interfaces and Abstract classes

Interfaces and Abstract classes

Introduction
The choice of whether to use an interface or an abstract can sometimes be a difficult one. This article shows you the differences between these two and also tells you when and where to use them.
Interfaces
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. An interface represents a contract, and a class that implements an interface must implement every aspect of that interface exactly as it is defined.
You declare an interface by using the interface keyword
Example
interface IPerson
{
void Eat();

void Sleep();

int Weight
{
set;
get;
}
}
In order to use this interface, you must declare your class in the same way that you declare a class inheriting from any other object.
Example
public class Man:IPerson
{
int iWeight;

public Man()
{
}

public void Eat()
{
MessageBox.Show("Man:Eat");
}

public void Sleep()
{
MessageBox.Show("Man:Sleep");
}

public int Weight
{
set
{
iWeight = value;
}
get
{
return iWeight;
}
}

static void Main()
{
Man i = new Man();
i.Eat();
i.Sleep();
}

}

You get the following result when you run the above code.
Man:Eat
Man:Sleep

It is important to note here that an interface is very different from a base class. An interface is implemented, not extended.
1.A class can implement multiple interfaces.
2.An interface cannot contain data declarations but you can declare properties.
3.All method declarations in an interface are public.
4.There can be no implementation in an interface.
5.The class implementing the interface must provide implementation code.
6.An interface can be derived from another interface
Abstract Classes
An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes.

When you have a class that contains methods that have no implementation (i.e. abstract methods), the class is said to be abstract as well. An abstract method is simply a shell or place-marker for a method that will be defined later in a derived class. The intention of abstract methods is to force every derivation of the class to implement those methods. If a derived class does not implement an abstract method, then that class must also be declared as abstract.

You declare an interface by using the interface keyword
abstract public class Person
{
abstract public void Eat();

public void Sleep()
{
MessageBox.Show("Person:Sleep");
}

abstract public int Weight
{
set;
get;
}
}
You can inherit the abstract class just like any other class.
public class Man:Person
{
int iWeight;

public Man()
{
}
override public void Eat()
{
MessageBox.Show("Man:Eat");
}
override public int Weight
{
set
{
iWeight = value;
}
get
{
return iWeight;
}
}

static void Main()
{
Man i = new Man();
i.Eat();
i.Sleep();
}
}

You get the following result when you execute the above code.
Man:Eat
Person:Sleep

So why would you declare a class abstract? It’s actually a very powerful class hierarchy design tool since you can provide the structure for something that is not very specific —just like our Person class. You will never create an Person object; but you will create Man and Woman objects. The other advantage is that you are moving the code to where it actually belongs. This helps you locate program logic problems.

A class that is derived from an abstract class may still implement interfaces.

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. If additional functionality is needed in derived classes, it can be added to the base class without breaking code.

In the above example, an abstract class is declared with one implemented method, one unimplemented method and one unimplemented property. A class inheriting from this class would have to implement the Eat method and Weight property

When implementing an abstract class, you must implement each abstract method in that class, and each implemented method must receive the same number and type of arguments, and have the same return value, as the method specified in the abstract class.
Recommendations on using Abstract Classes and Interfaces
1. If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
2. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
3. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
4. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Friday, May 2, 2008

Storing Session information

Storing Session information

HTML (which is what gets displayed in your browser) is great for displaying web pages, but is a stateless protocol. So each page is dealt with as an isolated (request and response) transaction and there is no management of which browser a request came from.
ASP.NET has the concept of a "session", which starts when a client first requests a page and ends after a definable period of inactivity. ASP.NET sends a unique cookie to the browser with each page which the browser then sends back for each subsequent page request which enables the server to associate each request with a session.
As well as the information ASP.NET stores in the session, applications can also store information in the session through the session object.
ASP.NET provides three methods to store session information:
• In Process (InProc)
• State Server
• SQL Server
InProc is the default method, but which is best for your application? The following is provided as a summary of the strengths and weaknesses of each:



In Process:::

Advantages:1. Default.
2. Fastest.
3. Simplest

Disadvantages
1. Session information lost if the worker process (either aspnet_wp.exe or w3wp.exe) is restarted (for a developer this includes a rebuild on the development machine).
2. Not suitable for web-farms




State Server:::
Advantages:
1. Tolerant of worker process crashes.
2. Suitable for web-farms.

Disadvantages:
1. Slower than In-Process.
2. State is maintained on a single server, and thus a single point of failure (only an issue if site up-time and fault tolerance is an issue)


SQL Server:::

Advantages:
1. Tolerant of worker process crashes.
2. Suitable for web-farms.
3. Supports failover clusters

Disadvantages:
1. Requires SQL Server.
2. Slowest method.
3. Most complex to set up.





In Process
Storing session information "In Process" (also sometimes referred to as "InProc") means that all session information is stored in the worker process "aspnet_wp.exe". It has the following advantages:
• It is the default method - so its simple because no configuration is required on the part of the developer.
• Is is the fastest method.
It also has the following disadvantages:
• All session information is lost if the aspnet_wp.exe process is restarted. This also means that session information will be lost after a recompile of the application, but there are numerous other times when the aspnet_wp.exe process will be recycled.
• It is not suitable for use on a web-farm, i.e. where there is more than one computer that could respond to a request. This is simply because if a subsequent request is handled by a different server then that server will not have access to the session information (because the session information is stored on a different server).
The following is the entry in the web.config file to configure session information to be stored InProc:
mode="InProc"
cookieless="false"
timeout="20" />
The default configuration installed will also contain entries for "stateConnectionString" and "sqlConnectionString". These are default entries that are only used if the "mode" is changed and can be ignored if storing "InProc".
State Server
With the "State Server" model session information is stored in a separate "state server" process. The worker process (aspnet_wp.exe) will communicate with the State Server (aspnet_state.exe) to store and retrieve session information.
If you are working in an environment where there is more than one web server then another key difference from the in-process model is that all the servers should be configured to talk to the same state server process. This is a configuration issue and it would be easy to (wrongly) configure a web farm to use separate state server process on each server.
Storing session information in the state server has the following advantages:
• It is tolerant of the worker process being recycled. For developers this has the advantage (or disadvantage!) that session information is maintained across compiles of the application.
• It is suitable for use on web-farms.
and the following disadvantages:
• It is slightly slower and more resource demanding than the in-process model, because there is an extra level of communication required between processes.
• State information is stored on a single server - this is not an issue normally but might be if you need to avoid a single point of failure (in which case SQL Server is the route to go because it supports failover servers).
To configure to use the state server model requires the sessionState parameter in the web.config file to be updated:
mode="StateServer"
stateConnectionString="tcpip=server1:42424"
cookieless="false"
timeout="20" />
The default entry for stateConnectionString is "stateConnectionString="tcpip=127.0.0.1:42424", this is reasonable if the state server is on the same server (The IP address 127.0.0.1 is by definition the local machine). If however you are running in a web-server environment then it is vitally important that you set the server name, so substitute the name of a server for "server1" in the above example. Otherwise each server will communicate with the state server process running locally and session information will not be shared between servers.
You also need to ensure that the state server is running on the chosen server. Do this by looking at the services on the server and ensure that "ASP.NET State Service" is started and set to "Automatic" start-up.
SQL Server
In "SQL Server" mode session information is stored in an SQL Server database. The worker process (aspnet_wp.exe) will communicate with the SQL Server database to store and retrieve session information.
SQL Mode has the following advantages:
• Tolerant of worker process crashes.
• Suitable for web-farms.
• Can be configured to work in a failover cluster. Basically the session information is stored on more than one server so if a database fails then the session information is not lost. This is ideally suited to environments where high availability is required (but doesn't come cheap!).
and the following disadvantages:
• It requires SQL Server
• It is the slower than both In-Proc and State-Server methods.
• Is the most complex to set up.

Thursday, May 1, 2008

SDLC Model in Software Development

SDLC Model in Software Development
Basic models used by software development firms are
a) System Development Life Cycle (SDLC) Model
b) Prototyping Model
c) Rapid Application Development Model
d) Component Assembly Model
we study the basic
System Development Life Cycle Model (SDLC Model)
This is also known as Classic Life Cycle Model (or) Linear Sequential Model (or) Waterfall Method. This has the following activities.
1. System/Information Engineering and Modeling
2. Software Requirements Analysis
3. Systems Analysis and Design
4. Code Generation
5. Testing
6. Maintenance

System/Information Engineering and Modeling
This system view is essential when software must interface with other elements such as hardware, people and other resources. System is the basic and very critical requirement for the existence of software in any entity. So if the system is not in place, the system should be engineered and put in place. In some cases, to extract the maximum output, the system should be re-engineered and spruced up. Once the ideal system is engineered or tuned, the development team studies the software requirement for the system.

Software Requirement Analysis
This is also known as feasibility study. In this phase, the development team visits the customer and studies their system. They investigate the need for possible software automation in the given system. By the end of the feasibility study, the team furnishes a document that holds the different specific recommendations for the candidate system. It also includes the personnel assignments, costs, project schedule, and target dates

System Analysis and Design
In this phase, the software development process, the software's overall structures are defined, the number of tiers needed for the package architecture, the database design, the data structure design etc are all defined in this phase. A software development model is created. The logical system of the product is developed in this phase.

Code Generation
The design must be translated into a machine-readable form. The code generation step performs this task. If the design is performed in a detailed manner, code generation can be accomplished without much complication. Programming tools like Compilers, Interpreters and Debuggers are used to generate the code. Different high level programming languages like C, C++, Pascal, and Java are used for coding. With respect to the type of application, the right programming language is chosen.

Testing
Once the code is generated, the software program testing begins. Different testing methodologies are available to unravel the bugs that were committed during the previous phases. Different testing tools and methodologies are already available.

Maintenance
Software will definitely undergo change once it is delivered to the customer. There are many reasons for the change. Change could happen because of some unexpected input values into the system. In addition, the changes in the system could directly affect the software operations. The software should be developed to accommodate changes that could happen during the post implementation period

Wednesday, April 30, 2008

Partial Classes-2

The first example shows an easy solution todefining nested types. With the power ofpartial classes, nested types can be completely isolated to their ownfiles. DataAccessLayer is defined as partial sothat the nested type DataSourceCollection can be defined in a separatepart. The second example is probably more of atelling of the dangers of partial types when used for no good reason. Here we see that both the containing typeDataAccessLayer and the contained type DataSourceCollection are defined aspartial. Hence the the definitions can bebroken into multiple parts. Please practicecaution when using partial types, particularly with regard to nested types. You will find that in a complex program it will bealmost impossible to determine what the full definition of any one type is onceit is defined as partial.

Partialtype attributes
Attributes on partial types are combined in anunspecified order so that the appear to all be defined on the given type. In the preceding section we defined a typeDataAccessLayer as follows.

public partial class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

}

public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}

publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}
}


Attributes can be added to each part of the typedefinition as follows.

//Dal.cs
[Docking]
public partial classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}

//dal.datasourcecollection.cs
[Serializable]
public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

In the above example, an different attribute hasbeen added to each part of the definition of DataAccessLayer. To the part defined in dal.cs, the attributeDockingAttribute has been attached. To the partdefined in dal.datasourcecollection.cs, the SerializableAttribute has beenattached. This activity is equivalent tospecifying both attributes on the type asfollows.

[Serializable, Docking ]

Inheritanceand Interface Implementation
Now that we are done having all this fun it’s timeto lay down some rules regarding what you can and cant do with partialtypes. To help with the discussion, it isimportant that we visualize what the end result of a partial type is. The previous section defined a partial typeDataAccessLayer as follows.

//Dal.cs
[Docking]
public partial classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}

//dal.datasourcecollection.cs
[Serializable]
public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

This definition, once compiled, will be equivalentto the listing below.

[Docking, Serializable]
public classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public class DataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}


The lesson here is that a partial class, no matterhow fragmented, is still on functional unit. Hence, any accessibility specifications applied to a partial type must agreewith all parts of the type that also include the accessibilityspecification. The concept is illustrated withthe sample below.

[Docking]
public partial classDataAccessLayer : GenericDAL
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}


internal partialclass DataAccessLayer : GenericDAL
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

Notice that in this definition of DataAccessLayer,the two parts inherit from a base type GenericDAL. Also notice that while one part defines the class aspublic, the other uses the internal modifier. Attempting to compile this listing will fail with the followingmessage.

Error1 Partial declarations of'PartialTypes2.DataAccessLayer' have conflicting accessibilitymodifiers

The reason is evident from our first demonstrationin this section. Although DataAccessLayer isfragmented, it is still type and a type cannot be both internal and public atthe same time.

The next issue is that of base classes, andis not as easy to ascertain. Examine the listing below.

[Docking]
public partial classDataAccessLayer : GenericDAL
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}


partial classDataAccessLayer : DataSource
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}

Although the modifier incompatibility has beenremoved from the type, a problem persists during compilation of the abovesource. The difference here is that the secondpart of DataAccessLayer is now attempting to inherit from a different base typeDataSource, than the first part which inherits from GenericDAL. This might not seem intuitive because it contradictsthe combining behavior of partial type attributes; however, returning to ourinitial demonstration on the singularity of partial types, DataAccessLayer is atype; consequently, it can only inherit from one base class. The formal rule dictates that when a partial classdeclaration includes a base class specification it must agree with all otherparts that include a base class specification. Attempting to compile the listing above would produce the following errormessage.

Error1 Partial declarations of'PartialTypes2.DataAccessLayer' must not specify different base classes

Now in the world of interfaces, where multipleinheritance is the game, the compining behavior returns. Examine the example below.

public partial class DataAccessLayer : GenericDAL
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

}


partial classDataAccessLayer : IDataSourceManager
{
publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}

}
}
Similar to the example in the last section, thesecond part of DataAccessLayer defines a different base than the first. Unlike the sample in the previous section; however,IDataSourceManager is an interface and not a class. The formal rule state that the set of baseinterfaces for a type declared in multiple parts is the union of the baseinterfaces specified on each part. Furthermore,a particular base interface may only be named once on each part, but it ispermitted for multiple parts to name the same base interface(s).

This means that the first part in the listingabove could have been defined to include the IDataSourceManager interface aswell. The listing below illustrates.


public partial class DataAccessLayer : GenericDAL,IDataSourceManager
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

}

<<<<Previous

Partial Classes-1

Partial classes

Introduction

Examine the examaple below:

//definition for BinaryTree.h
class BinaryTree
{
public:
BinaryTree(void);
~BinaryTree(void);
int seed;
char*name;
void Load(char*name);
char* Find();
};

In C++ the class definitions can be separated fromthe implementations. The above snippet is takenfrom a file BinaryTree.h which contains all definitions associated with theBinaryTree class but no implementation code. Continuing with the example, the implementation file BinaryTree.cpp would bedefined as follows.

#include ".\binarytree.h"

BinaryTree::BinaryTree(void)
{
}

BinaryTree::~BinaryTree(void)
{
}

void BinaryTree::Load(char* str){
this->name =str;
}

char* BinaryTree::Find(){
returnthis->name;
}


As you can see from the sample, the first line ofBinaryTree.cpp explicitly declares the inclusion of the class definition foundin binarytree.h. Consequently; this completelyseparate file can use members defined in the later as though they were definedthere. The sample is of course nonsensical but the concept neverthelessprevails; the ability to create types across multiple files.

It is important to note that the idea of havingmultiple public types in one file was so revolting to the devout object orientedprogrammer at one time that entire languages, Java for instance, excludedit. However, you will find that while it isgood programming practice to maintain all source code for a type in a singlefile, sometimes a type becomes large enough that this is an impracticalconstraint.

Partials
C# 2.0 introduces the concept of partial typedefinitions for classes, structs, and interfaces, as a means to break types in aprogram into multiple pieces to be stored in different source files for easiermaintenance and development. This approach isparticularly useful when the need arises to use nested types or provideinterface implementation.

Unlike c/C++ where an #include keyword was used toexplicitly bind the contents of a header file to the implementation file, C#2.0partial type links are inferred through the type names given. Also, these are no interface definitions necessaryin c#2.0. A sample of a partial type is given below.

//Binarytree_header.cs
public partial class BinaryTree
{
intseed;
stringname;
publicBinaryTree()
{
}
}


The above example attempts to recreate theBinaryTree sample we saw earlier in the chapter using C#; notice that no includestatements are needed nor are any function prototypes defined. Furtherimplementation of this class may now be defined in other files, for instance aBinaryTree_Load.cs file may be created which produces more BinaryTreefunctionality.

//BinaryTree_load.cs: Loadfunctionality
public partial classBinaryTree
{
public voidLoad(string name)
{
this.name= name;
}

}

We can also create another file BinaryTree_find.cswhich would have all the functionality associated with finding an element in thetree.

//BinaryTree_find.cs: findfunctionality
public partial classBinaryTree
{
public stringFind()
{
returnname;
}
}

As you can see from the above samples, the newtype modifier,partial, isused when defining a type in multiple parts. It indicates that additional partsmay exist elsewhere. I stress the word maybecause each partial type declaration is autonomous. The example below illustrates this by creating apartial type declaration that includes no other parts.

public partial class BinaryTree
{

intx;


}


The code above will compile successfully. Addinganother part to the type will not change this successful compilation.

public partial class BinaryTree
{
inty;
}

Finally, a constructor can be added to instantiatethe two variables defined in both parts of the type. A sample showing all three parts is highlightedbelow.

public partial class BinaryTree
{
int x;
}

public partial classBinaryTree
{
inty;
}

public partial classBinaryTree
{
publicBinaryTree()
{
this.x =100;
this.y =100;
}
}


Each partial type declaration must include thepartial modifier and must be declared within the same namespace as the otherparts.

Compiling the code above will produce thefollowing type definition.

public partial class BinaryTree
{
intx;
inty;
publicBinaryTree()
{
this.x =100;
this.y =100;
}
}

If we compiled the BinaryTree sample from thefirst section it would produce a type definition similar to the one depictedbelow.



public class BinaryTree
{
intseed;
stringname;
publicBinaryTree()
{
}

public voidLoad(string name)
{
this.name= name;
}

public stringFind()
{
returnname;
}
}

It is important to note that partial types DO NOTallow already compiled types to be extended. This is because all parts of a partial type must be compiled together such thatthe parts can be merged at compile-time to produce an actual type; as discussedin the example above. The partial modifier, ifit appears, must appear immediately before either class, struct, or interfacekeywords, but is not itself a keyword.


NestedPartials
Examine the three types defined in the samplebelow.

public struct DataSource
{
public stringconnectionString;
}

public classDataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}

publicDataSource this[string dataSourceName]
{
get
{
return (DataSource)items[dataSourceName];
}
}
}
}

The snippet defines a struct DataSource of whichthe type DataSourceCollection is an aggregate through the items Hashtable. This type DataSourceCollection also happens to be anested type of the DataAccessLayer type. Usingpartial types in this scenario, the nested type DataSourceCollection may also bedeclared in multiple parts by using the partial modifier. Hence DataAccessLayer may also be defined asfollows.

public class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

public partialclass DataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}


}

public partialclass DataSourceCollection
{
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}


}

This would not make to much sense though, sincethe type DataSourceCollection is only qualified through its containerDataAccessLayer there is no way to specify a part outside of theDataSourceCollection type definition. A moreoptimal approach is to define either the containing type as partial with thecontained type as not.

public partial class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}

}

public partial classDataAccessLayer
{
public classDataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}

publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}
}

Or to define both containing and contained partsas partial.

public partial class DataAccessLayer
{
DataSourceCollection sources;
publicDataAccessLayer()
{
sources =new DataSourceCollection();
}

publicDataSourceCollection DataSources
{
get
{
return sources;
}
}
}

public partial classDataAccessLayer
{
public partialclass DataSourceCollection
{
Hashtableitems;
publicDataSourceCollection()
{
items = new Hashtable();
}
}
}

public partial classDataAccessLayer
{
public partialclass DataSourceCollection
{
publicDataSource this[string dataSourceName]
{
get
{
return(DataSource)items[dataSourceName];
}
}
}
}


NEXT>>>

How to remove duplicate rows from a table in SQL Server

This article was previously published under Q139444
SUMMARY
Microsoft SQL Server tables should never contain duplicate rows, nor non-unique primary keys. For brevity, we will sometimes refer to primary keys as "key" or "PK" in this article, but this will always denote "primary key." Duplicate PKs are a violation of entity integrity, and should be disallowed in a relational system. SQL Server has various mechanisms for enforcing entity integrity, including indexes, UNIQUE constraints, PRIMARY KEY constraints, and triggers.

Despite this, under unusual circumstances duplicate primary keys may occur, and if so they must be eliminated. One way they can occur is if duplicate PKs exist in non-relational data outside SQL Server, and the data is imported while PK uniqueness is not being enforced. Another way they can occur is through a database design error, such as not enforcing entity integrity on each table.

Often duplicate PKs are noticed when you attempt to create a unique index, which will abort if duplicate keys are found. This message is:
Msg 1505, Level 16, State 1 Create unique index aborted on duplicate key.
If you are using SQL Server 2000 or SQL Server 2005, you may receive the following error message:
Msg 1505, Level 16, State 1 CREATE UNIQUE INDEX terminated because a duplicate key was found for object name '%.*ls' and index name '%.*ls'. The duplicate key value is %ls.
This article discusses how to locate and remove duplicate primary keys from a table. However, you should closely examine the process which allowed the duplicates to happen in order to prevent a recurrence.
MORE INFORMATION
For this example, we will use the following table with duplicate PK values. In this table the primary key is the two columns (col1, col2). We cannot create a unique index or PRIMARY KEY constraint since two rows have duplicate PKs. This procedure illustrates how to identify and remove the duplicates.
create table t1(col1 int, col2 int, col3 char(50)) insert into t1 values (1, 1, 'data value one') insert into t1 values (1, 1, 'data value one') insert into t1 values (1, 2, 'data value two')
The first step is to identify which rows have duplicate primary key values:
SELECT col1, col2, count(*) FROM t1 GROUP BY col1, col2 HAVING count(*) > 1
This will return one row for each set of duplicate PK values in the table. The last column in this result is the number of duplicates for the particular PK value.
col1 col2
1 1 2


If there are only a few sets of duplicate PK values, the best procedure is to delete these manually on an individual basis. For example:
set rowcount 1 delete from t1 where col1=1 and col2=1
The rowcount value should be n-1 the number of duplicates for a given key value. In this example, there are 2 duplicates so rowcount is set to 1. The col1/col2 values are taken from the above GROUP BY query result. If the GROUP BY query returns multiple rows, the "set rowcount" query will have to be run once for each of these rows. Each time it is run, set rowcount to n-1 the number of duplicates of the particular PK value.

Before deleting the rows, you should verify that the entire row is duplicate. While unlikely, it is possible that the PK values are duplicate, yet the row as a whole is not. An example of this would be a table with Social Security Number as the primary key, and having two different people (or rows) with the same number, each having unique attributes. In such a case whatever malfunction caused the duplicate key may have also caused valid unique data to be placed in the row. This data should copied out and preserved for study and possible reconciliation prior to deleting the data.

If there are many distinct sets of duplicate PK values in the table, it may be too time-consuming to remove them individually. In this case the following procedure can be used:
1. First, run the above GROUP BY query to determine how many sets of duplicate PK values exist, and the count of duplicates for each set.
2. Select the duplicate key values into a holding table. For example:
SELECT col1, col2, col3=count(*) INTO holdkey FROM t1 GROUP BY col1, col2 HAVING count(*) > 1
3. Select the duplicate rows into a holding table, eliminating duplicates in the process. For example:
SELECT DISTINCT t1.* INTO holddups FROM t1, holdkey WHERE t1.col1 = holdkey.col1 AND t1.col2 = holdkey.col2
4. At this point, the holddups table should have unique PKs, however, this will not be the case if t1 had duplicate PKs, yet unique rows (as in the SSN example above). Verify that each key in holddups is unique, and that you do not have duplicate keys, yet unique rows. If so, you must stop here and reconcile which of the rows you wish to keep for a given duplicate key value. For example, the query:
SELECT col1, col2, count(*) FROM holddups GROUP BY col1, col2
should return a count of 1 for each row. If yes, proceed to step 5 below. If no, you have duplicate keys, yet unique rows, and need to decide which rows to save. This will usually entail either discarding a row, or creating a new unique key value for this row. Take one of these two steps for each such duplicate PK in the holddups table.
5. Delete the duplicate rows from the original table. For example:
DELETE t1 FROM t1, holdkey WHERE t1.col1 = holdkey.col1 AND t1.col2 = holdkey.col2
6. Put the unique rows back in the original table. For example:
INSERT t1 SELECT * FROM holddups
________________________________________

Sunday, April 27, 2008

Differences Between VB.NET& C# .NET-3

Programming Difference
Purpose VB.NET C#

Declaring Variables
VB.NET>>Dim x As Integer
Public x As Integer = 10
C#.NET>>int x;
int x = 10;

Comments
VB.NET>> ' comment
x = 1 ' comment
Rem comment

C#.NET>>// comment
/* multiline
comment */

Assignment Statements
nVal = 7
nVal = 7;

Conditional Statements

VB.NET>>
If nCnt <= nMax Then
' Same as nTotal =
' nTotal + nCnt.
nTotal += nCnt
' Same as nCnt = nCnt + 1.
nCnt += 1
Else
nTotal += nCnt
nCnt -= 1
End If

C#.NET>>
if (nCnt <= nMax)
{
nTotal += nCnt;
nCnt++;
}
else
{
nTotal +=nCnt;
nCnt--;
}



Selection Statements

VB.NET>>
Select Case n
Case 0
MsgBox ("Zero")
' Visual Basic .NET exits
' the Select at
' the end of a Case.
Case 1
MsgBox ("One")
Case 2
MsgBox ("Two")
Case Else
MsgBox ("Default")
End Select


C#.NET>>

switch(n)
{
case 0:
Console.WriteLine("Zero");
break;
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
default:
Console.WriteLine("?");
break;
}

FOR Loops

VB.NET>>

For n = 1 To 10
MsgBox("The number is " & n)
Next

For Each prop In obj
prop = 42
Next prop

C#.NET>>
for (int i = 1; i <= 10; i++)
Console.WriteLine(
"The number is {0}", i);
foreach(prop current in obj)
{
current=42;
}

Hiding Base Class Members

VB.NET>>
Public Class BaseCls
' The element to be shadowed
Public Z As Integer = 100
public Sub Test()
System.Console.WriteLine( _
"Test in BaseCls")
End Sub
End Class

Public Class DervCls
Inherits BaseCls
' The shadowing element.
Public Shadows Z As String = "*"
public Shadows Sub Test()
System.Console.WriteLine( _
"Test in DervCls")
End Sub
End Class

Public Class UseClasses
' DervCls widens to BaseCls.
Dim BObj As BaseCls =
New DervCls()
' Access through derived
' class.
Dim DObj As DervCls =
New DervCls()

Public Sub ShowZ()
System.Console.WriteLine( _
"Accessed through base "&_
"class: " & BObj.Z)
System.Console.WriteLine(_
"Accessed through derived "&_
"class: " & DObj.Z)
BObj.Test()
DObj.Test()
End Sub
End Class


C#.NET>>
public class BaseCls
{
// The element to be hidden
public int Z = 100;
public void Test()
{
System.Console.WriteLine(
"Test in BaseCls");
}
}

public class DervCls : BaseCls
{
// The hiding element
public new string Z = "*";
public new void Test()
{
System.Console.WriteLine(
"Test in DervCls");
}
}

public class UseClasses
{
// DervCls widens to BaseCls
BaseCls BObj = new DervCls();
// Access through derived
//class
DervCls DObj = new DervCls();
public void ShowZ()
{
System.Console.WriteLine(
"Accessed through " +
"base class: {0}",
BObj.Z);
System.Console.WriteLine(
"Accessed through" +
" derived class:{0}",
DObj.Z);
BObj.Test();
DObj.Test();
}
}
WHILE Loops

VB.NET>>
' Test at start of loop
While n < 100 .
' Same as n = n + 1.
n += 1
End While '

C#.NET>>
while (n < 100)
n++;



Parameter Passing by Value
VB.NET>>
' The argument Y is
'passed by value.
Public Sub ABC( _
ByVal y As Long)
'If ABC changes y, the
' changes do not affect x.
End Sub

ABC(x) ' Call the procedure.
' You can force parameters to
' be passed by value,
' regardless of how
' they are declared,
' by enclosing
' the parameters in
' extra parentheses.
ABC((x))

C#.NET>>
/* Note that there is
no way to pass reference
types (objects) strictly
by value. You can choose
to either pass the reference
(essentially a pointer), or
a reference to the reference
(a pointer to a pointer).*/
// The method:
void ABC(int x)
{
...
}
// Calling the method:
ABC(i);
Parameter Passing by Reference

VB.NET>>
Public Sub ABC(ByRef y As Long)
' The parameter y is declared
'by referece:
' If ABC changes y, the changes are
' made to the value of x.
End Sub

ABC(x) ' Call the procedure.




C#.NET>>
/* Note that there is no
way to pass reference types
(objects) strictly by value.
You can choose to either
pass the reference
(essentially a pointer),
or a reference to the
reference (a pointer to a
pointer).*/
// Note also that unsafe C#
//methods can take pointers
//just like C++ methods. For
//details, see unsafe.
// The method:
void ABC(ref int x)
{
...
}
// Calling the method:
ABC(ref i);

Structured Exception Handling

VB.NET>>
Try
If x = 0 Then
Throw New Exception( _
"x equals zero")
Else
Throw New Exception( _
"x does not equal zero")
End If
Catch err As System.Exception
MsgBox( _
"Error: " & Err.Description)
Finally
MsgBox( _
"Executing finally block.")
End Try


C#.NET>>
// try-catch-finally
try
{
if (x == 0)
throw new System.Exception(
"x equals zero");
else
throw new System.Exception(
"x does not equal zero");
}
catch (System.Exception err)
{
System.Console.WriteLine(
err.Message);
}
finally
{
System.Console.WriteLine(
"executing finally block");
}



Set an Object Reference to Nothing

VB.NET>> o = Nothing
C#.NET>> o = null;

Initializing Value Types

VB.NET>>
Dim dt as New System.DateTime( _
2001, 4, 12, 22, 16, 49, 844)

C#.NET>>
System.DateTime dt =
new System.DateTime(
2001, 4, 12, 22, 16,
49, 844);



New Features of both languages in 2005 version



VB.NET>>>>>
Visual Basic 2005 has many new and improved language features -- such as inheritance, interfaces, overriding, shared members, and overloading -- that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. This language has following new features,
1. Continue Statement, which immediately skips to the next iteration of a Do, For, or While loop.
2. IsNot operator, which you can avoid using the Not and Is operators in an awkward order.
3. 3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason.
4. Public Sub setbigbold( _
5. ByVal c As Control)
6. Using nf As New _
7. System.Drawing.Font("Arial",_
8. 12.0F, FontStyle.Bold)
9. c.Font = nf
10. c.Text = "This is" &_
11. "12-point Arial bold"
12. End Using
End Sub
13. Explicit Zero Lower Bound on an Array, Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.
14. Unsigned Types, Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte.
15. Operator Overloading, Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have defined.
16. Partial Types, to separate generated code from your authored code into separate source files.
17. Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.
18. Custom Events. You can declare custom events by using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the event.
19. Compiler Checking Options, The /nowarn and /warnaserror options provide more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.
20. There are eight new command-line compiler options:
a. The /codepage option specifies which codepage to use when opening source files.
b. The /doc option generates an XML documentation file based on comments within your code.
c. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.
d. The /filealign option specifies the size of sections in your output file.
e. The /noconfig option causes the compiler to ignore the Vbc.rsp file.
f. The /nostdlib option prevents the import of mscorlib.dll, which defines the entire System namespace.
g. The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to explicitly specify it.
h. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies.






C#.NET>>>>>>>

With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:
1. Generics types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types.
2. Iterators make it easier to dictate how a for each loop will iterate over a collection's contents.
3. // Iterator Example
4. public class NumChar
5. {
6. string[] saNum = {
7. "One", "Two", "Three",
8. "Four", "Five", "Six",
9. "Seven", "Eight", "Nine",
10. "Zero"};
11. public
12. System.Collections.IEnumerator
13. GetEnumerator()
14. {
15. foreach (string num in saNum)
16. yield return num;
17. }
18. }
19. // Create an instance of
20. // the collection class
21. NumChar oNumChar = new NumChar();
22. // Iterate through it with foreach
23. foreach (string num in oNumChar)
24. Console.WriteLine(num);
25. Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code.
26. Nullable types allow a variable to contain a value that is undefined.
27. Anonymous Method is now possible to pass a block of code as a parameter. Anywhere a delegate is expected, a code block can be used instead: There is no need to define a new method.
28. button1.Click +=
29. delegate { MessageBox.Show(
"Click!") };
30. . The namespace alias qualifier (::) provides more control over accessing namespace members. The global :: alias allows to access the root namespace that may be hidden by an entity in your code.
31. Static classes are a safe and convenient way of declaring a class containing static methods that cannot be instantiated. In C# v1.2 you would have defined the class constructor as private to prevent the class being instantiated.
32. 8. There are eight new compiler options:
a. /langversion option: Can be used to specify compatibility with a specific version of the language.
b. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures.
c. #pragma warning: Used to disable and enable individual warnings in code.
d. /linkresource option: Contains additional options.
e. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet.
f. /keycontainer and /keyfile: Support specifying cryptographic keys.

Conclusion
I think that this article will help you understand both language features and also you can choose a language based on your taste. I will update this article in future if there are any changes.


<<<<PREVIOUS

Differences Between VB.NET& C# .NET-2

Keyword Differences
Purpose
VB.NET
C#

Declare a variable VB.NET
Private, Public, Friend, Protected, Static1, Shared, Dim
Declare a variable c#.NET
declarators (keywords include user-defined types and built-in types)

Declare a named constant vb.net
Const
Declare a named constant c#.net
const

Create a new object vb.net
New, CreateObject()
Create a new object c#.net
new

Function/method does not return a value vb.net
Sub
Function/method does not return a value c#.net
void

Overload a function or method (Visual Basic: overload a procedure or method) vb.net
Overloads
Overload a function or method (Visual Basic: overload a procedure or method) c#.net
(No language keyword required for this purpose)

Refer to the current object vb.net
Me
Refer to the current object c#.net
this

Make a nonvirtual call to a virtual method of the current object vb.net
MyClass
Make a nonvirtual call to a virtual method of the current object c#.net
n/a

Retrieve character from a string
vb.net>> GetChar Function
c#.net>> []

Declare a compound data type (Visual Basic: Structure)
vb.net>>Structure End Structure
c#.net>>struct, class, interface

Initialize an object (constructors)
vb.net>>Sub New()
c#.net>>Constructors, or system default type constructors

Terminate an object directly
vb.net>>n/a
c#.net>> n/a

Method called by the system just before garbage collection reclaims an object7
vb.net>> Finalize
c#.net>>destructor

Initialize a variable where it is declared

vb.net>>Dim x As Long = 5
c#.net>>Dim c As New _
Car(FuelTypeEnum.Gas)


// initialize to a value:
vb.net>>int x = 123;
// or use default
// constructor:
c#.net>>int x = new int();


Take the address of a function
vb.net>> AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance)
c#.net>>delegate

Declare that an object can be modified asynchronously
vb.net>>n/a
c#.net>> volatile

Force explicit declaration of variables
vb.net>>Option Explicit
c#.net>>n/a. (All variables must be declared prior to use)

Test for an object variable that does not refer to an object
vb.net>>obj = Nothing
c#.net>>obj == null

Value of an object variable that does not refer to an object
vb.net>> Nothing
c#.net>> null

Test for a database null expression
vb.net>>IsDbNull
c#.net>>n/a

Test whether a Variant variable has been initialized
vb.net>>n/a
c#.net>>n/a

Define a default property
vb.net>>Default
c#.net>>by using indexers

Refer to a base class
vb.net>>MyBase
c#.net>>base

Declare an interface
vb.net>>Interface
c#.net>>interface

Specify an interface to be implemented
vb.net>>Implements (statement)
c#.net>>class C1 : I1

Declare a class
vb.net>>Class
c#.net>>class

Specify that a class can only be inherited. An instance of the class cannot be created.
vb.net>> MustInherit
c#.net>>abstract

Specify that a class cannot be inherited
vb.net>> NotInheritable
c#.net>>sealed

Declare an enumerated type
vb.net>> Enum End Enum
c#.net>>enum

Declare a class constant
vb.net>> Const
c#.net>>const (Applied to a field declaration)

Derive a class from a base class
vb.net>> Inherits C2
c#.net>>class C1 : C2

Override a method
vb.net>>Overrides
c#.net>> override

Declare a method that must be implemented in a deriving class
vb.net>> MustOverride
c#.net>> abstract

Declare a method that can't be overridden
vb.net>> NotOverridable (Methods are not overridable by default.)
c#.net>> sealed

Declare a virtual method, property (Visual Basic), or property accessor (C#, C++)
vb.net>>Overridable
c#.net>> virtual

Hide a base class member in a derived class
vb.net>> Shadowing
c#.net>> n/a

Declare a typesafe reference to a class method
vb.net>> Delegate
c#.net>>delegate

Specify that a variable can contain an object whose events you wish to handle
vb.net>> WithEvents
c#.net>> (Write code - no specific keyword)

Specify the events for which an event procedure will be called
vb.net>> Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.)
c#.net>> n/a

Evaluate an object expression once, in order to access multiple members

vb.net>>With objExpr
<.member>
<.member>
End With

c#.net>>n/a

Structured exception handling

vb.net>>Try
Catch

Finally

End Try

c#.net>> try, catch, finally, throw

Decision structure (selection)
vb.net>> Select Case ..., Case, Case Else, End Select
c#.net>>switch, case, default, goto, break

Decision structure (if ... then)
vb.net>>If ... Then, ElseIf ... Then, Else, End If
c#.net>> if, else

Loop structure (conditional)
vb.net>> While, Do [While, Until] ..., Loop [While, Until]
c#.net>>do, while, continue

Loop structure (iteration)
vb.net>> For ..., [Exit For], Next
For Each ..., [Exit For,] Next
c#.net>> for, foreach

Declare an array

vb.net>>Dim a() As Long


c#.net>>int[] x = new int[5];


Initialize an array

vb.net>>Dim a() As Long = {3, 4, 5}



c#.net>>int[] x = new int[5] {
1, 2, 3, 4, 5};


Reallocate array
vb.net>> Redim
c#.net>> n/a

Visible outside the project or assembly
vb.net>>Public
c#.net>> public

Invisible outside the assembly (C#/Visual Basic) or within the package (Visual J#, JScript)
vb.net>> Friend
c#.net>> internal

Visible only within the project (for nested classes, within the enclosing class)
vb.net>>Private
c#.net>> private

Accessible outside class and project or module
vb.net>> Public
c#.net>>public

Accessible outside the class, but within the project
vb.net>> Friend
c#.net>>internal

Only accessible within class or module
vb.net>> Private
c#.net>> private

Only accessible to current and derived classes
vb.net>> Protected
c#.net>> protected

Preserve procedure's local variables
vb.net>> Static
c#.net>>n/a

Shared by all instances of a class
vb.net>> Shared
c#.net>> static

Comment code
vb.net>> '
Rem
c#.net>> //, /* */ for multi-line comments
/// for XML comments

Case-sensitive?
vb.net>> No
c#.net>> Yes

Call Windows API
vb.net>>Declare
c#.net>> use Platform Invoke

Declare and raise an event
vb.net>> Event, RaiseEvent
c#.net>>event

Threading primitives
vb.net>> SyncLock
c#.net>> lock

Go to
vb.net>> Goto
c#.net>> goto



Data types Differences
Purpose/Size


Decimal
vb.net>>Decimal
c#.net>> decimal

Date
vb.net>>Date
c#.net>> DateTime

(varies)
vb.net>> String
c#.net>> string

1 byte
vb.net>> Byte
c#.net>> byte

2 bytes
vb.net>>Boolean
c#.net>> bool

2 bytes
vb.net>> Short, Char (Unicode character)
c#.net>>short, char (Unicode character)

4 bytes
vb.net>> Integer
c#.net>> int

8 bytes
vb.net>> Long
c#.net>> long

4 bytes
vb.net>>Single
c#.net>> float

8 bytes
vb.net>> Double
c#.net>> double



Operators Differences
Purpose


Integer division
vb.net>>\
c#.net>> /

Modulus (division returning only the remainder)
vb.net>> Mod
c#.net>> %

Exponentiation
vb.net>>^
c#.net>> n/a

Integer division Assignment
vb.net>>\=
c#.net>> /=

Concatenate
vb.net>>&= NEW
c#.net>>+=

Modulus
vb.net>>n/a
c#.net>>%=

Bitwise-AND
vb.net>> n/a
c#.net>> &=

Bitwise-exclusive-OR
vb.net>> n/a
c#.net>>^=

Bitwise-inclusive-OR
vb.net>>n/a
c#.net>> |=

Equal
vb.net>> =
c#.net>> ==

Not equal
vb.net>><>
c#.net>> !=

Compare two object reference variables
vb.net>> Is
c#.net>>==

Compare object reference type
vb.net>> TypeOf x Is Class1
c#.net>> x is Class1

Concatenate strings
vb.net>> &
c#.net>>+

Shortcircuited Boolean AND
vb.net>>AndAlso
c#.net>>&&

Shortcircuited Boolean OR
vb.net>>OrElse
c#.net>> ||

Scope resolution
vb.net>> .
c#.net>> . and base

Array element
vb.net>> ()
c#.net>> [ ]

Type cast
vb.net>> Cint, CDbl, ..., CType
c#.net>> (type)

Postfix increment
vb.net>> n/a
c#.net>> ++

Postfix decrement
vb.net>>n/a
c#.net>> --

Indirection
vb.net>> n/a
c#.net>> * (unsafe mode only)

Address of
vb.net>> AddressOf
c#.net>> & (unsafe mode only; also see fixed)

Logical-NOT
vb.net>> Not
c#.net>> !

One's complement
vb.net>> Not
c#.net>>~

Prefix increment
vb.net>> n/a
c#.net>>++

Prefix decrement
vb.net>> n/a
c#.net>>--

Size of type
vb.net>> n/a
c#.net>>sizeof

Bitwise-AND
vb.net>>And
c#.net>> &

Bitwise-exclusive-OR
vb.net>> Xor
c#.net>>^

Bitwise-inclusive-OR
vb.net>>Or
c#.net>> |

Logical-AND
vb.net>> And
c#.net>>&&

Logical-OR
vb.net>> Or
c#.net>> ||

Conditional
vb.net>>If Function ()
c#.net>> ?:

Pointer to member
vb.net>>n/a
c#.net>> . (Unsafe mode only)



Programming Difference
<<<<PREVOIUS
NEXT>>>>