Wednesday, April 21, 2010

Windows Communication Foundation (WCF)

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.

Which Namespace is used to access WCF service?
System.ServiceModel


Difference between WCF and Webservice?
  • Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type. 
  •  Web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends. 
  •  We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc 
  •  WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:    
          IIS         
         WAS
         Self-hosting
         Managed Windows Service
  •  Webservice works in stateless environment
What are the various ways of hosting WCF services?
There are three major ways of hosting a WCF services
  • Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
  • Host in application domain or process provided by IIS Server.
  • Host in Application domain and process provided by WAS (Windows Activation Service) Server.

What was the code name for WCF?
The code name of WCF was Indigo .

WCF is a unification of .NET framework communication technologies which unites the following technologies:-

NET remoting
MSMQ
Web services
COM+


What are the main components of WCF?
The main components of WCF are

1. Service class
2. Hosting environment
3. End point


How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.

<client>  
   <endpoint  
      ...  
      binding = "wsHttpBinding"  
      bindingConfiguration = "LongTimeout"   
      ...  
   />  
</client>  
<bindings>  
   <wsHttpBinding>  
      <binding name = "LongTimeout" sendTimeout = "00:04:00"/>   
   </wsHttpBinding>  
</bindings>


If no timeout has been specified, the default is considered as 1 minute.


What is transport reliability and Message reliability?
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.


What are the different elements of WCF Services Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like


<system.serviceModel>  
   <client>  
      <endpoint name = "MyEndpoint"  
         address  = "http://localhost:8000/MyService/"  
         binding  = "wsHttpBinding"  
         contract = "IMyContract"  
      />  
   </client>  
</system.serviceModel>  


What are contracts in WCF?

In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

Service contracts
Describe which operations the client can perform on the service.

There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

[ServiceContract]  
interface IMyContract  
{  
   [OperationContract]  
   string MyMethod( );  
}  
class MyService : IMyContract  
{  
   public string MyMethod( )  
   {  
      return "Hello World";  
   }  
}


Data contracts
Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.


[DataContract]  
class Contact  
{  
   [DataMember]  
   public string FirstName;  
  
   [DataMember]  
   public string LastName;  
}


If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.


Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.


What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.


What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.


IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.


Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.


Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.


Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.


MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.


MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.


Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)


What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas

HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService


What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.

The client of a service is merely the party consuming the service.

Tuesday, April 6, 2010

How Authentication and Authorization Works?

The following section lists the sequence of events that take place in the authentication and authorization process when a new request arrives.

The IIS first checks the validity of the incoming request. If the authentication mode is anonymous (default) then the request is authenticated automatically. But if this authentication mode is overridden in the web.config file settings, the IIS performs the specified authentication check first before the request is passed on to ASP.NET.

Now ASP.NET checks whether Impersonation is enabled or not. If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing executing the task. If impersonation is not enabled, the application runs with the identity of the IIS local machine’s identity and the privileges of the ASP.NET user account. ASPNET or NETWORK SERVICE is the default ASP.NET unprivileged account on Windows XP and Windows Server 2003, respectively. Now, the identity that has already been authenticated and verified is used to request resources from the operating system. Then ASP.NET performs an authorization check on the requested resources and if the user is authorized, it returns the request through IIS.

What is Authorization in ASP.Net?

Authorization

Authorization is the process of determining the accessibility to a resource for a previously authenticated user. Note that authorization can only work with authenticated users, hence ensuring that no un-authenticated user can access the application. The default authentication mode is anonymous authentication. There can be three types of authorization in ASP.NET. They are

·         URL Authorization

·         File Authorization

·         Authorization based on ACLs

Authorization like authentication is specified in the web.config file of the application. The following specification in the web.config file allows or grants access to the user Joydip but denies the same to Jini and all anonymous users.  Note that the allow/ and deny/ element ordering is important, since the first one that matches the request will be used.  Hence, if you were to add a deny users="*" / to the top of the list, it would always deny everyone, regardless of any allow / elements that followed it.

authorization
  allow users="Joydip"/
  deny users="Jini"/
  deny users="?"/
/authorization

Authentication in ASP.Net

Authentication

Authentication is the process of determining the authenticity of a user based on the user’s credentials. Whenever a user logs on to an application, the user is first authenticated and then authorized. The application’s web.config file contains all of the configuration settings for an ASP.NET application. It is the job of the authentication provider to verify the credentials of the user and decide whether a particular request should be considered authenticated or not. An authentication provider is used to prove the identity of the users in a system. ASP.NET provides three ways to authenticate a user:

· Forms authentication

· Windows authentication

· Passport authentication

Hence, ASP.NET contains the three respective authentication providers to support the above authentication modes.

Forms Authentication

This authentication mode is based on cookies where the user name and the password are stored either in a text file or the database. After a user is authenticated, the user’s credentials are stored in a cookie for use in that session. When the user has not logged in and requests for a page that is insecure, he or she is redirected to the login page of the application. Forms authentication supports both session and persistent cookies. Authentication modes can be specified in the application’s web.config file as shown below:

Listing 1

configuration
system.web
    authentication mode="[Windows/Forms/Passport/None]"
    /authentication
/system.web
/configuration

The following needs to be specified in the application’s web.config file for using Forms Based Authentication in ASP.NET:

Listing 2

configuration
system.web
authentication mode="Forms"/
    forms name="login"loginUrl="login.aspx" /
   authorization
        deny users="?"/
/authorization
/system.web
/configuration

Note: The statement in the web.config file as stated in Listing 2 implies that all permissions are granted only to the authenticated users. The users who are not authenticated are not granted any permission. The symbol "?" indicates all Non Authenticated and Anonymous users.

Generally the user’s credentials are stored in the database and the entered credentials are verified using those that are stored in the database. Typically, the user enters the username and the password, clicks the login button and the form validates the values against values from the database. This is shown in the code snippet below:

Listing 3

if (Verify (txtUserName.Text, txtPassword.Text))
{
  FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False);
    else
  lblMessage.Text = "Invalid login name orpassword specified...";
}

private Verify(string userName, string password)
{
      //Usual Code to connect to the DB
      // and verify the user's credentials
}

The static method RedirectFromLoginPage creates an authentication ticket and is used to redirect an authenticated user back to the originally requested URL or the default URL. The authentication ticket creates a persistent cookie that becomes a part of the HttpResponse object. Later, when the user tries to access a page in a restricted folder, the ASP.NET framework uses the cookie to retrieve the ticket and determine whether the user has access to that particular resource. The first parameter to this method identifies the user while the second is used to specify whether the user’s authentication cookie needs to be persisted across multiple site visits.

The user’s credentials can be also be specified in the web.config file as shown below:

Listing 4
 

configuration
   system.web
    authentication mode="Forms"
    forms loginUrl="login.aspx"
        credentialspasswordFormat="Clear"
            user name="Joydip"password="Joydip" /
        /credentials
    /forms
    /authentication
        authorization
    /system.web
/configuration

Windows Authentication

This is the default authentication mode in ASP.NET. Using this mode, a user is authenticated based on his/her Windows account. Windows Authentication can be used only in an intranet environment where the administrator has full control over the users in the network. The following should be set in the web.config file to use Windows Authentication:

Listing 5

authentication mode="Windows"/

authorization
allow users ="*" /
/authorization

Note: The symbol "*" indicates all users inclusive of Authenticated and Anonymous users. Hence the statement in the web.config file as stated in Listing 5 indicates that all permissions are granted to both the Anonymous and Authenticated users.

Windows authentication can be of the following types

·         Anonymous Authentication

·         Basic Authentication

·         Digest Authentication

·         Integrated Windows Authentication

Passport Authentication

Passport authentication is a centralized authentication service that uses Microsoft's Passport Service to authenticate the users of an application. It allows the users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. The following code shows how we can specify Passport Authentication in the web.config file:

Listing 6
 

configuration
  system.web
    authenticationmode="Passport"
      passportredirectUrl="login.aspx" /
    /authentication
    authorization
      deny users="?" /
    /authorization
  /system.web
/configuration

ASP.NET also supports custom authentication. In such a case the authentication mode has to be specified as none in the web.config file as shown below:
 

authentication mode="none"

Then we need to write our own custom authentication provider.

How to create appdomain?

In the following cases generally we create an application domain
1. If we create our own runtime host application,
2. If our application needs to create or work with additional application domains that are not automatically generated by the runtime.
3. If the requirement is such that some assemblies have to be managed personally, If this is the case we create our own application domain, load the assemblies that are supposed to be managed personally into application Domain.
AppDomain Class has CreateDomain() method
//To create an app Domain Explicitly
AppDomain.CreateDomain("AppDomainName");
Console.WriteLine(app.FriendlyName); // Displays child domain name
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); // Displays Host Domain name

Unloading :
When you call a Web service by using SSL and an application domain must be unloaded If the call is in progress, the application domain does not unload, a System.CannotUnloadAppDomainException exception is thrown, and the Microsoft ASP.NET worker process may die. So when we make a call to web service using SSL we explicitly unload the application domain programmatically by AppDomain.Unload method
Note: An application domain may be unloaded for some reason that is unrelated to calling the Web service. For example, if the Web.config file is modified, the application domain may be unloaded

what is the use of appdomain?

Operating systems and runtime environments typically provide some form of isolation between applications. For example, Microsoft Windows uses processes to isolate applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications.

Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.

What is application domain ?

The application Domain is used to isolate an application from other applications. One process has its own virtual memory and does not over lap the other process's virtual memory; due to this one process can not crash the other process. As a result any problem or error in one process does not affect the other process. In .Net they went one step ahead introducing application domains. In application domain multiple applications can run in same process with out influencing each other. If one of the application domains throws error it does not affect the other application domains.

Tuesday, March 23, 2010

Using file upload control to upload the file

Step 1:
Drop the FileUpload control from Toolbox to a Web page. The following code adds the FileUpLoad control:

asp:FileUpLoad id="FileUpLoad1" runat="server"

Step 2:
To support file upload, we need to add a Button control:


asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px"

Step 3:
Now on this button click event handler, we need to call SaveAs method of FileUpLoad control, which takes a full path where the file will be uploaded.

protected void UploadBtn_Click(object sender, EventArgs e)
{
if (FileUpLoad1.HasFile)
{

FileUpLoad1.SaveAs(@"C:\temp\" + FileUpLoad1.FileName);
Label1.Text = "File Uploaded: " + FileUpLoad1.FileName ;
}
else
{
Label1.Text = "No File Uploaded.";
}
}

Step 4:
You can restrict the FileUpload control to upload a file type. For example, I wanted to upload images (Jpgs and Gifs) only so I put a validator, which allows Gifs and Jpegs only.

asp:RegularExpressionValidator
id="FileUpLoadValidator" runat="server"
ErrorMessage="Upload Jpegs and Gifs only."
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$"
ControlToValidate="FileUpload1"


Step 5:
The default size of files uploaded by the FileUpload control is 4MB. So if we try to upload the files larger than 4MB, it won't let you do so.  If you want to apply this to only the application you are working with, apply this node to the web.config file of your application, overriding any setting that is in the web.config.comments file. Make sure this node resides between the nodes in the configuration file. This number is in KB.

httpRuntime
executionTimeout = "110" [in Seconds][number
maxRequestLength = "4096" [number]
requestLengthDiskThreshold = "80" [number]
useFullyQualifiedRedirectUrl = "false" [true|false]
minFreeThreads = "8" [number]
minLocalRequestFreeThreads = "4" [number]
appRequestQueueLimit = "5000" [number]
enableKernelOutputCache = "true" [true|false]
enableVersionHeader = "true" [true|false]
apartmentThreading = "false" [true|false]
requireRootedSaveAsPath = "true" [true|false]
enable = "true" [true|false]
sendCacheControlHeader = "true" [true|false]
shutdownTimeout = "90" [in Seconds][number]
delayNotificationTimeout = "5" [in Seconds][number]
waitChangeNotification = "0" [number]
maxWaitChangeNotification = "0" [number]
enableHeaderChecking = "true" [true|false]

Sunday, February 7, 2010

What is DiffGram ?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service. ADO.NET introduced the DataSet class to support the disconnected, distributed data-access scenarios. With DataSet, the data retrieved from the database is cached in-memory, in addition to the constraints and relationships among the tables. When the ADO.NET DataSet is serialized as XML (for example, when returning a DataSet from an ASP.NET XML Web service method), the XML format used for DataSet serialization is known as DiffGram. Like Updategrams, DiffGrams also contains the tags that specify the original and new state of data. SQLXML and .NET Managed classes can be used to execute DiffGrams to perform the database updates, however there are many things that are supported by Updategrams and not by DiffGrams (ability to pass parameters being one example).

Now let's see an example of DiffGrams. The code is to reads data from Employees tables and write in an XML document in DiffGram format.
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Northwind.mdb"
Dim sql As String = "SELECT EmployeeID, FirstName, LastName, Title FROM Employees"
Dim conn As OleDbConnection = Nothing
Dim ds As DataSet = Nothing
' Create and open connection
conn = New OleDbConnection(connectionString)
If conn.State <> ConnectionState.Open Then
conn.Open()
End If 'Create a data adapter
Dim adapter As New OleDbDataAdapter(sql, conn)
' Create and fill a DataSet
ds = New DataSet("TempDtSet")
adapter.Fill(ds, "DtSet")
' Write XML in DiffGram format
ds.WriteXml("DiffGramFile.xml", XmlWriteMode.DiffGram)
' Close connection
If conn.State = ConnectionState.Open Then
conn.Close()
End If

Now if you update data, you'll see new additions to the XML file with and tags and if there are any errors occur during the updatio, the entries will go to the section.
You can use the ReadXml method to read XML documents in DiffGram format. The first parameter of ReadXml is the XML document name and second parameter should be XmlReadMode.DiffGram. See the following code snippet:

' Create a DataSet Object
Dim ds As New DataSet

' Fill with the data
ds.ReadXml("DiffGramFile.xml", XmlReadMode.DiffGram)

DataRowState members
Added
Add added rows to a DataRowCollection of a DataSet and AcceptChanges has not been called. Deleted
All the deleted rows. Detached Rows were created but not added to the row collection. Either waiting for the addition or have removed from the collection.
Modified
Modified rows and AcceptChanges has not been called.
Unchanged
Unchanged rows since last AcceptChanges was called.

The following code copies only modified rows of ds to new DataSet tempDs.
Dim tempDs As DataSet
tempDs = ds.GetChanges(DataRowState.Modified)

What are the Session State Modes/ Session States

Storage location
InProc - session kept as live objects in web server (aspnet_wp.exe)
StateServer - session serialized and stored in memory in a separate process aspnet_state.exe). State Server can run on another machine
SQLServer - session serialized and stored in SQL server

Performance
InProc - Fastest, but the more session data, the more memory is consumed on the web server, and that can affect performance.
StateServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 15% slower than InProc. However, the cost of serialization/deserialization can affect performance if you're storing lots of objects. You have to do performance testing for your own scenario.
SQLServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 25% slower than InProc. Same warning about serialization as in StateServer.

Performance tips for Out-of-Proc (OOP) modes
If you're using OOP modes (State Server or SQL Server), one of your major cost is the serialization/deserialization of objects in your session state. ASP.NET performs the serialization/deserialization of certain "basic" types using an optimized internal method. ("Basic" types include numeric types of all sizes (e.g. Int, Byte, Decimal, String, DateTime, TimeSpan, Guid, IntPtr and UIntPtr, etc) .
If you have a session variable (e.g. an ArrayList object) that is not one of the "basic" types, ASP.NET will serialize/deserialize it using the BinaryFormatter, which is relatively slower.

So for performance sake it is better to store all session state data using one of the "basic" types listed above. For example, if you want to store two things, Name and Address, in session state, you can either (a) store them using two String session variables, or (b) create a class with two String members, and store that class object in a session variable. Performance wise, you should go with option (a).

Robustness
InProc - Session state will be lost if the worker process (aspnet_wp.exe) recycles, or if the appdomain restarts. It's because session state is stored in the memory space of an appdomain. The restart can be caused by the modification of certain config files such as web.config and machine.config, or any change in the \bin directory (such as new DLL after you've recompiled the application using VS) For details, see KB324772. In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and in v1.1. See KB321792.
If you're using IIS 6.0, you may want to go to IIS Manager, go to Application Pools/DefaultAppPool, and see if any of the parameters on the Recycling and Performance tabs are causing the IIS worker process (w3svc.exe) to shutdown.
StateServer - Solve the session state loss problem in InProc mode. Allows a webfarm to store session on a central server. Single point of failure at the State Server.
SQLServer - Similar to StateServer. Moreover, session state data can survive a SQL server restart, and you can also take advantage of SQL server failover cluster, after you've followed instructions in KB 311209.

Caveats
InProc - It won't work in web garden mode, because in that mode multiple aspnet_wp.exe will be running on the same machine. Switch to StateServer or SQLServer when using web garden. Also Session_End event is supported only in InProc mode.
StateServer - In a web farm, make sure you have the same in all your web servers. See KB 313091 on how to do it. - Also, make sure your objects are serializable. See KB 312112 for details. - For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical (case sensitive) in all the web servers in the web farm. See KB 325056 for details
SQLServer - In v1, there is a bug so that iif you specify integrated security in the connection string (e.g. "trusted_connection=true", or "integrated security=sspi"), it won't work if you also turn on impersonation in asp.net. This problem is (wrongly) described in KB 324479. Unfortunately, the "Description" and the "Cause" sections in the KB are quite wrong and misleading. But anyway, there is a QFE fix for it, and the fix will also be available when SP3 ships. The problem is fixed in v1.1. - Also, make sure your objects are serializable. Otherwise, your request will hang! See KB 312112 for details. The SQLServer mode hanging problem was fixed in v1.1. The QFE fix for KB 324479 also contains the fix for this problem. The problem will be fixed in v1 SP3 too. - For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical (case sensitive) in all the web servers in the web farm.

Monday, February 1, 2010

Handle paging in Gridview Control

Step 1:
Connect database and access any table to display in Gridview.

'Declare below code in Partial Class _Default
Dim con As SqlConnection
Dim cmd As SqlCommand
Dim adp As SqlDataAdapter
Dim ds As DataSet

'write code at page_load event
con = New SqlConnection(ConfigurationManager.AppSettings("cn"))
Dim sql As String
sql = "select * from tbl_logo_info"
cmd = New SqlCommand(sql, con)
adp = New SqlDataAdapter(cmd)
ds = New DataSet()
adp.Fill(ds, "tbl_adminuser")

GridView1.DataSource = ds
GridView1.DataBind()

Step 2:
'write below code at pageindexchaging event
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging

GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()

End Sub

Thursday, January 28, 2010

Difference between session and viewstate

1. Session state is a server based state management. It can be accessible from all pages in web application. It is scoped to current browser session only. It's structured as a key/value dictionary for storing session specific info that needs to be maintained between server round trips.

2. SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.

3. VIEWSTATE Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.

4. ViewState persist the values of controls of particular page in the client (browser) when post back operation done. When user requests another page previous page data no longer available.

5. SessionState persist the data of particular user in the server. This data available till user close the browser or session time completes.

6. Viewstate is particular to a control/page whereas session is for the whole application. You can access the session data stored in page A in page B but viewstate does not behave so.

7. ViewState is maintained at client side whereas session is maintained at server side

8. Since viewstate is maintained at client, it does not have a concept of expiry but session will expire after the stipulated time

9. You can enable/disable view state for specific controls but you can't do that for session.

What is ViewState?

ViewState
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

When to use the ViewState
View state is a good way to store data in between postbacks, because it doesn't take up any memory on the server side and it doesn't impose any arbitrary usage limits (such as a timeout). So, what might force you to abandon view state for another type of state management? Here are three possible reasons:
  • You need to store mission-critical data that the user cannot be allowed to tamper with. (An ingenious user could modify the view state information in a postback request.) In this case, consider session state.
  • You need to store information that will be used by multiple pages. In this case, consider session state, cookies, or the query string.
  • You need to store an extremely large amount of information, and you don't want to slow down page transmission times. In this case, consider using a database, or possibly session state.
Remember, any data that you put in the view state will be part of the data stream that goes to the client and then comes back to the server, so be very careful while putting large chunks of data in the ViewState!

Problems with ViewState
Viewstate has lots of advantages and as well as disadvantages, so you need to weigh carefully before making the decision to use it. As I told you early, view state doesnt require any server resources for its operation. It is passed to the client during every postback as an hidden element. Since it is added with every page, it adds few Kbytes to the page. This effects the loading of the page in the client. Other main problem with Viewstate is, since it is passed as plain text to the client. Anybody can tamper this value, because of this you shouldnt store any important data in the viewstate. View state is one of the most important features of ASP.NET, not so much because of its technical relevance, but more because it makes the magic of the Web Forms model possible. However, if used carelessly, view state can easily become a burden. Although ViewState is freely accessible in a hidden field called __VIEWSTATE, the view state information is not clear text. By default, a machine-specific authentication code is calculated on the data and appended to the view state string. The resulting text is then Base64 encoded only, but not encrypted. In order to make the view state more secure, the ASP.NET @Page directive supports an attribute called EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original data.

Tuesday, January 26, 2010

Logical Layers vs. Physical Layers

Logical Layers vs. Physical Layers (Distributed)
Logical Layers and Physical Layers are the ones that confuse people. Firstly, a logical layer means that layers are separate in terms of assembly or sets of classes, but are still hosted on the same server. Physical layer means that those assemblies or sets of classes are hosted on different servers with some additional code to handle the communication between the layers. E.g. remoting and web services.

Deciding to separate the layers physically or not is very important. It really depends on the load your application expects to get. I think it's worth mentioning some of the facts that might affect your decision.

Please DO note that separating the layers physically WILL slow your application down due to the delay in communicating between the servers throughout the network, so if you are using the physical layer approach, make sure the performance gain is worth the performance loss from this.

Cost for deploying and maintaining physically separated applications is much greater. First of all, you will need more servers. You also need network hardware connecting them. At this point, deploying the application becomes more complex too! So decide if these things will be worth it or not.

Another fact that might affect your decision is how each of the tiers in the application are going to be used. You will probably want to host a tier on a separate server if more than 1 service is dependent on it, e.g. You might want to host business logic somewhere else if you have multiple presentation layers for different clients. You might also want a separate SQL server if you have other applications using the same data.

What is n-Tier Architecture?

n-Tier Architecture
We will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures we can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.

What is n-Tier architecture?
N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.
N-Tier the word means Multiple Tier.
N-Tier Architecture is nothing but splitting your solution into different project based on the business requirement.
Why use n-Tier architecture?
Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.
This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.

Advantage:
  1. Reduce the business and the programming complexity.
  2. Easy to process

Note: tier and layer mean the same thing

An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.

Presentation Layer
Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

Business Tier
Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.

In ASP.NET it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.

Often this layer is divided into two sub layers
BLL and DAL
The Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.

In ASP.NET it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

Data Tier
Data tier is the database or the source of the data itself. Often in .NET it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.

Some reasons for data tier is ;
  • Security
  • Code Maintenance and Reuse
  • Scalability

How to Implement N-Tier Architecture in Web Application?
To  work with n-Tier system
  1. Create a solution.
  2. Include a web application project in it and name it as "PRESENTATION LAYER"
  3. Include a Class Library Project and name it as "DATALAYER"




  4. Include a Class Library Project and name it as "BUSINESSLAYER"
  5. Now we have 3 project in single solution
  6. Build the DataLayer.
  7. Go to Business layer and right click on reference and in reference go to Project's. Here we can see the Datalayer. Click on that and include as reference.
  8. Now in the Business Layer reference we can see the DataLayer assembly
  9. Go to Presentationlayer and right click on reference and in reference go to Project's. Here we can see the BusinessLayer. Click on that and include as reference.
  10. Now we can see the BusinessLayer Assembly in the Presentation Layer.
  11. Now we can access all the methods
    DataLayer in Business Layer
    BusinessLayer in PresentationLayer



  12. This is the way we build our N-Tier Application. For example, this is a 3 Tier System.

Monday, January 25, 2010

What is the difference between Dataset and Recordset?

Below is the differences between Dataset and Recordset?

  • Dataset is a disconnected architecture
  • Dataset can be connect two database example oracle,sql table
  • DataSet is Xml Based and faster
  • Performancewise DataSet is better than recordset
  • Data Set is main for storage tool in ADO.Net
  • A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
  • Data in a DataSet is bulk-loaded, rather than being loaded on demand.
  • There's no concept of cursor types in a DataSet.
  • DataSets have no current record pointer You can use For Each loops to move through the data.
  • You can store many edits in a DataSet, and write them to the original data source in a single operation.

  • Recordset provides data one row at a time.
  • Record Set is a Connected Architecture
  • Recordset connect only one database
  • RecordSet is one (1) table that contains all the data
  • Retrieving data from more than one table or source requires a database JOIN.

Thursday, January 21, 2010

Binding Grid view with datasource and handling paging option

We have two steps for binding gridview with datasource and handling paging option

Step 1:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GridView1.DataSource = ds
GridView1.DataBind()
end sub

Step 2:
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
End Sub

Wednesday, January 20, 2010

ASP.Net Page Life Cycle Events

Page life-cycle events that we use most frequently. There are more events than those listed; however, they are not used for most page processing scenarios. If we want to write our own ASP.NET server controls, we need to understand more about these events.

1. PreInit
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.
Note:
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

2. Init
Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

3. InitComplete
Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

4. PreLoad
Use this event if you need to perform processing on your page or control before the Load event. Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

5. Load
The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections.

6. Control Events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
Note:
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

7. LoadComplete
Use this event for tasks that require that all other controls on the page be loaded.

8. PreRender
Before this event occurs:
  • The Page object calls EnsureChildControls for each control and for the page.
  • Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

9. SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

10. Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.

If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

11. Unload
This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

Note:
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

ASP.Net Page Life Cycle Stages

Below is the ASP.NET Application Page Life Cycle Stages for IIS 7.0

1. Page Request
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

2. Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

3. Page Initialization
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

4. Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

5. Validation
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

6. Postback Event Handling
If the request is a postback, any event handlers are called.

7. Rendering
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

8. Unload
Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Tuesday, January 19, 2010

Memory Leak in Dot Net

Memory leaks can occur either in the stack, unmanaged heap, or the managed heap. There are many ways to find out that memory is leaking, like memory increasing in the Task Manager. Before starting to correct the memory problem, you need to determine the kind of memory which is leaking. Perfmon can be used to examine counters such as Process/Private bytes, .NET CLR Memory/# bytes in all heaps, and the .NET CLR LocksAndThreads/# of the current logical thread. If the .NET CLR LocksAndThreads/# is increasing unexpectedly, then the thread stack is leaking. If only Process/Private bytes are increasing but the .NET CLR Memory is not increasing, then unmanaged memory is leaking, else if both are increasing, then managed memory is leaking.

Stack memory
Stack memory gets reclaimed after the method returns. Stack memory can get leaked in two ways. First, a method call consumes a significant amount of stack resources that never returns, thereby never releasing the associated stack frame. The other is by creating background threads and never terminating them, thus leaking the thread stack.

Unmanaged Heap Memory
If the total memory usage is increasing but the .NET CLR memory is not increasing, then unmanaged memory is leaking. Unmanaged memory can leak in several ways - if the managed code is interoperating with unmanaged code and a leak exists in the unmanaged code. .NET doesn't make any guarantee that the finalizer for each object will get called. In the current implementation, .NET has one finalizer thread. If there exists a finalizer which blocks this thread, then the other finalizer will never get called and the unmanaged memory will leak which was supposed to be released. When an AppDomain is torn down, the CLR tries to run all the finalizers, but if a blocking finalizer exists, then it can prevent the CLR from completing the AppDomain tear down. To prevent this, the CLR implements a timeout on the process, after which it stops the finalization process, and the unmanaged memory which was supposed to be removed is left leaked.

Managed Heap Memory
Managed memory can also get leaked by several ways like fragmentation of the Large Object Heap. The memory in the Large Object Heap never gets compacted, so there is a loss in memory over there. Also, if there exist some objects which are not needed, but there exists a reference to the objects, then GC never claims the memory assigned to these objects.

Example:
static object someObj;

static void SomeMethod()
{
someObj = new Object();
}

The GC would not be able to collect the allocated object until someObj was set equal to null. This is because the static someObj reference is always reachable from code.

MVC Architecture in ASP.net

Model View Controller architecture aims to separate an application into three parts:

Model:
It is the business logic of an application. From an object oriented perspective it would consist of a set of classes that implement the critical functionality of an application from a business point of view.
View: It can consist of every type of interface given to the user. In ASP.NET the view is the set of web pages presented by a web application.
Controller: This part of the architecture is the most difficult to explain, hence the most difficult to implement in many platforms. The controller is the object that allows the manipulation of the view. Usually many applications implement Model-Controller tiers that contain the business logic along with the necessary code to manipulate a user interface. In an ASP.NET application the controller is implicitly represented by the code-behind or the server side code that generates the HTML presented to the user.

A basic diagram that would help us understand perfectly the specific parts that implement the Model View Controller architecture in an ASP.NET application is presented below:

-----------------------------------------------------------------------------------
  
Advantages:
1. Layering Approach helps us a lot and we need to enhance it to get full customizability.
2. We need to enhance this with all our design knowledge.
3. No IDE enforces these patterns, it is up to us to do clean and disciplined way of coding.
4. Once we are used to these approaches / patterns then we are addicted to it.

References: 
http://www.techbubbles.com/aspnet/aspnet-35-mvc-application/

Thursday, January 7, 2010

What is the difference between datatable and dataset?

Dataset
dataset is collection of data table and it is provide interface between database and datatable. dataset consist multiple table. A Dataset is an in-memory representation of a collection of Database objects including tables of a relational database schema. Dataset represents an in-memory cache of data. The dataset contains a collection of Tables, Relations, constraints etc., The dataset contains all the objects as a Collection of objects. For example it contains the Database Tables as DataTable objects. Dataset is a collection of tables, which is used in disconnected architecture. Generally to fill dataset we use fill method of dataadapter.

It can be used for manipulating the data remotely and finally updating the database with the modified data. This way it enables disconnected means of working with data. This improves performance in terms of reducing the number of times a database is accessed for data manipulations.

Example for dataset:
using System.Data.SqlClient;
using System.Data;

string strDBConnection = "server=(local);database=DatabaseName;user id=UserName;password=Pwd;connection reset=false;connection lifetime=5;Trusted_Connection=Yes;"
SqlConnection dbConnection;
dbConnection = new SqlConnection(strDBConnection);

string strSelectSql = "Select * from [DatabaseName].[OwnerName].[TableName] order by FieldName";

//Open the connection
dbConnection.Open();

//Create a command
SqlCommand selectSqlCommand = new SqlCommand(strSelectSql,dbConnection);
SqlDataAdapter sqlData = new SqlDataAdapter(selectSqlCommand);
DataSet dsSelectData = new DataSet();
sqlData.Fill(dsSelectData);


Data Table
Data table is a collection of records that consist the single table. You can get datatable from dataset as follows.

DataTable tbl = DataSet.Tables["Tablename" or Table instance number]

Datatable represents one table of in-memory data. Datatable is a single table. datatable is just like table which has columns and rows. A DataTable is an in-memory representation of data, typically retrieved from a database or XML source.