Monday, May 9, 2016

WEB farm - Load Balancing in Asp.net

Scope:

Considering the high volume of traffic the Web site uses two or more servers needed to handle user requests. The concept behind the web farm is that a number of different web sites share pooled resources. They typically share a common front-end dispatcher to perform load control and distribute customer requests. They share the multiple web servers themselves. Based onexperience and with reference to Microsoft sites this document was created to address certain issues faced in web farm while using ASP.NET.

Machine Key:

Consider a scenario while doing a PostBack in ASP.NET and which looses the form information.

For Example:

When a user selects an item from a DropDownList and then clicks a submit button, the Click event on the button redirects them to the value of the selected item. This works fine if you are on Webserver1 and the button click PostBacks to Webserver1. If you are on Webserver1 and the load balance submits back to Webserver2, the page reloads and the Button click event never fires. This happen site wide and affects utilities such as submitting a textbox search and other form posting events.

Approach 1

You can modify the pages element in In machine.config of both the servers:
<system.web> 
   <pages enableViewStateMac="false" /> 
</system.web>

EnableViewStateMac indicates that ASP.NET should run a machine authentication check (MAC) on the page's view state when the page is posted back from the client;

True - if view state should be MAC checked
False - We need to ensure that it is kept to false.

Approach 2

Force every server in your farm to use the same key; generate a hex encoded 64-bit or 128-bit <machineKey> and put that in each server's machine.config.

Example: <don't use the below key> 

<machineKey    validationKey='A130E240DF1C49E2764EF8A86CEDCBB11274E5298A130CA08B90EED016C0
14CEAE1D86344C29E67E99DF83347E43820050A2B9C9FC89E0574BF3394B6D0401A9'
decryptionKey='2CC37FFA8D14925B9CBCC0E3B1506F35066FEF33FEB4ADC8' validation='SHA1'/>

You can generate a key from 


Session Management:

ASP.NET provides two solutions for sharing state information between multiple servers:

  1. The ASP.NET State Server service
  2. Microsoft SQL Server.

State Server


In a web farm, make sure you have the same <machinekey> in all your web servers.

http://support.microsoft.com/default.aspx?scid=kb;EN-US;q3103091
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 in all the web servers in the web farm.
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q325056
Make sure objects are serializable. Here in state server session gets serialized and stored in memory in a separate process (aspnet_state.exe). Also if you try to store instance of a class that is not marked as serializable into a session variable, the request returns without an error. However, Asp.net actually fails to save the session data and blocks subsequent requests in the same session. (Because the class is not marked as serializable).
SQL Server
Make sure objects are serializable (as like above).
If you specify integrated security in the connection string (For example "trusted_connection= true", or "integrated security=sspi") it won't work also if you turn on impersonation in asp.net.
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 in all the webservers in the web farm.
Using SQL Server to Store ASP.NET Session State:
Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store session state. This script will create the necessary database and database objects.
The .NET Framework installs this script in the same folder as its compilers and other tools.
For example: C:\WINNT\Microsoft.NET\Framework\v1.0.3705 on a Windows 2000 computer with the 1.0 version of the Framework.
Edit the sessionState element in the web.config file for your ASP.NET application as follows:
<sessionState mode="SQLServer" StateConnectionString="tcpip=127.0.0.1:42424"
SqlConnectionString = "data source=SERVERNAME; user id=sa; password=sa"
cookieless="false" timeout="20" />

Supply the server name, user name, and password for a SQL Server account that has access to the session state database in the sqlConnectionString attribute.
Steps to run the InstallSqlState.sql and the UninstallSqlState.sql script files to configure SQL Server mode session state management.
In SQL Query Analyzer, on the File menu, click Open.

In the Open Query File dialog box, browse to the InstallSqlState.sql script file, and then click Open. By default, InstallSqlState.sql is located in one of the following folders:

system drive\Windows\Microsoft.NET\Framework\version\

After InstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.

Before you run the UninstallSqlState.sql script file to uninstall SQL Server mode session state management configuration, you must stop the w3svc process. To do this, follow these steps:

  • On the Windows Start menu, click Run, type cmd, and then click OK to open a command prompt.
  • At the command prompt, type net stop w3svc. You receive confirmation that the w3svc process is stopped.
In SQL Query Analyzer, on the File menu, click Open.

In the Open Query File dialog box, browse to the UninstallSqlState.sql script file, and then click Open. By default, UninstallSqlState.sql is located in one of the following folders:

system drive\Windows\Microsoft.NET\Framework\version\

After UninstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.

After you uninstall SQL Server mode session state management configuration, you must restart the w3svc service. To restart the w3svc process, type net starts w3svc at a command prompt.

Security Considerations Sql Server [Session]:

The following aspects need to be kept in mind:

  • Use Windows authentication to the database
  • Encrypt sqlConnectionString
  • Limit the application's login in the database
  • Secure the channel
Caching Considerations:

There are three options explained below.
  1. Synchronizing all servers in web farm
  2. Centralized Cache location to be maintained.
  3. SQL server caching
1. Synchronizing all servers in web farm

By providing a wrapper class simply having a CacheControl.aspx receiver page in each of the Applications, it is possible to send a WebRequest to each of the machines (maintained in an easy-to-configure web.config AppSettings element) and have each enabled with code to do its own update "on demand".
So, whenever add a "real" item to the Cache, it will also create a new populated instance of the same class, serialize it into a compact byte stream, and iterate through our server list sending it over the wire via the WebRequest so that each app in the farm, WebGarden, etc can receive and deserialize it, and update its own Cache. Simple, elegant, and fast! Even if it is a complex object such as a class that you have added to your Cache, provided that it is serializable, it will work.
2. Centralized Cache location
One Cache-application is to be created, which will take care of the caching and returning the cached items. And that is to be placed in centralized location. All applications should send the data to be cached, to that cache-application. The Cache-application will store the data. When any application requests the cached data, it will be retrieved from the Cache-application. (The centralized Cache-application can be called with credentials.)

3. SQL server caching

SQL Server caching is easy to implement by using ADO.NET and the .NET Framework, and it provides a common development model to use with existing data access components. It provides a robust security model that can easily be configured to work across a Web farm using SQL Server replication.

If the application requires cached data to persist across process recycles, reboots, and power failures, in-memory cache is not an option. In such cases, Caching mechanism based on a persistent data store, such as SQL Server or the NTFS file system. It also makes sense to use SQL Server to cache smaller data items to gain persistency.

Because the cache service needs to access SQL Server over a network and the data is retrieved using database queries, the data access is relatively slow. We need to carefully compare the cost of recreating the data versus retrieving it from the database.

NLB(Network Load Balancing):

Network Load Balancing_NLB is a network driver that distributes the load for networked client/server applications across multiple c luster servers. Network Load Balancing works by distributing client requests across a set of servers.
Shopping cart contents at an e-commerce site and Secure Sockets Layer (SSL) authentication data are examples of a client's session state. Network Load Balancing can be used to scale applications that manage session state spanning multiple connections. When its client affinity parameter setting is enabled, Network Load Balancing directs all TCP connections from one client IP address to the same cluster host. This allows session state to be maintained in host memory.
NLB provides the client affinity parameter, which, when enabled, basically makes you "always come back to the server you landed on first", thereby insuring that your Session and Application variables don't get thrown away. Use the client affinity feature. When client affinity is enabled, Network Load Balancing directs all TCP connections to the same cluster host. This allows session state to be maintained in host memory. You can enable client affinity in the Add/Edit Port Rules dialog box in Network Load Balancing Manager. Choose either Single or Class C affinity to ensure that only one cluster host will handle all connections that are part of the same client session. This is important if the server application running on the cluster host maintains session state (such as server cookies) between connections.
Network Load Balancing, a clustering technology included in the Microsoft Windows 2000 Advanced Server and Datacenter Server operating systems, enhances the scalability and availability of mission-critical, TCP/IP-based services, such as Web, Terminal Services, virtual private networking, and streaming media servers. This component runs within cluster hosts as part of the Windows 2000 operating system and requires no dedicated hardware support.
Other Tasks:
Request distribution: Incoming HTTP requests must be distributed among all servers by using a mechanism such as round-robin DNS, Microsoft Application Center 2000, or a third-party load distribution device.
Log aggregation: Before you process HTTP usage logs, it is a good idea to combine the logs to create a single log that includes requests sent to all systems.
Monitoring: To detect problems that affect a single server or the whole site, you must monitor both the external URL for the site and the URLs for each of the Web servers.
Scheduler:  Scheduling an event to occur on a single server should cause only that one server to run the task. Scheduling an event to occur on all servers should cause all servers to run the task. [Updations need to be done and should get reflected in all servers hence scheduler should appropriately picked-up]
Centralized database: Web applications that use a database must have a single database that is shared between multiple Web servers. In environments that require no single point of failure, cluster the database server.
Synchronize Configuration and Content:
You need to ensure that the config files are present in the right path on all the servers, and that their contents are continuously in sync.

You can copy configuration files to servers by using any standard file copy or synchronization method, including DFS, the File Replication service, and Microsoft Application Center 2000.

The following batch file will work in environments where each Web server has the virtual server root folder shared as:


When you deploy configuration information and ASP.NET content to multiple servers, it is critical to deploy the content from a single staging server to all production servers at the same time. This reduces the chance of problems occurring when a user's requests are sent to different servers. Microsoft recommends that all configuration and content updates occur on the staging server. Ideally, this staging server does not receive requests from users. It is dedicated to the task of testing and deploying new content.

Load Balancing And Session State Configuration

Load Balancing And Session State Configuration are techniques for the Application Administrator to divide or distribute the workload evenly across various servers. When multiple servers use this type of environment it is known as Web Farms. So basically farming helps in avoiding overload on a single server thus helps in providing better performance, better resource utilization and maximizes throughput.

Load BalancerLoad Balancer is the single point for handling requests and is the key that decides which request needs to be forwarded to which server in the Web Farm Environment. Every request first arrives at the Load Balancer and then it is the role of the Load Balancer to forward the request to a specific server based on the current load and the state of the server.

In a Web Farm scenario, even if one of the servers stop working or crashes, the application will still work or respond, since other servers are still working, so the only point at which your application can go down is when the Load Balancer goes off.

There are various algorithms to define how the Load Balancer works, like "Round Robin" and "Least Connections" and so on.
For achieving this type of environment we need to take into consideration a few things like Session Management, Cache Management and the most important is the Database clustering (that is not usually taken care of by many). I will elaborate Session Management as keeping the scope defined; I will only be saying what changes you may need to make in your application or how to make your application work in a Load Balanced Environment. The configuration the of the Load Balancer is out of the scope of this article.

There are many tools available in the market for Load Balancing, you just need to do the configuration settings and if your application is ready for this environment, you are ready to go.

Sticky Sessions

So what are Sticky Sessions?

When a client makes a first request to the server, a session is created (by default or usually as In-Proc Sessions) in the server memory for that user, all the subsequent requests use the same session object. Now as I said, the session is created in the memory of the server handling the very first request, and in the Load Balanced environment we have more than one servers serving the requests, so what if the second request goes to another server that does not have that session object in memory, it will create a big mess, so that is the use of Sticky Sessions. To use Sticky Sessions we configure the load balancer to send the request for a specific session to the server that has served the first request. This can create a problem in the Load Balanced environment because it may be possible with Sticky Sessions that some of the servers are fully loaded and some are actually free at that time. But with In-Proc sessions we need to have Sticky Sessions in the load balanced environment.

Serializable Objects

As far as In-Proc Sessions are concerned that are maintained in the server memory, this is not a problem, but if some other technique for Session management is used, like maintaining sessions in SQL Server, then it will be a problem if the Objects that need to be in the Session are not serializable, this is very obvious since they all must know if something needs to travel on the network, if it does then it has to be serializable. Here we will store it on a separate server and all the servers that are part of the Load Balanced environment will access and update the session objects and put it into SQL Server.

Encrypting View State

Encrypting a view state can also create a problem because the encryption logic can vary from machine to machine, for this we need to update the Machine Key in "machine.config", and need to keep it the same on every machine.

Session Management

As of now there are three types of Session Management Techniques that are available:
  1. In-Proc
  2. SQLServer
  3. StateServer
In-Proc Session

For configuring an In-Proc Session just make the following changes to the "Web.config" file:
<sessionState mode="InProc" cookieless="false" timeout="100"/>

In this mode of Session state handling, all the session information is stored within the server memory (In-Memory) managed by an ASP.NET worker thread. This approach is good until the data that is stored in the session is not that heavy, but if you are going to maintain heavy data into it can create a mess for your application then the performance will decrease drastically. Also, the session data stored In-Proc will go off as soon as the application pool restarts.

As I discussed earlier in this article about sticky sessions, if we are using this mode for Session handling then we need to configure Load Balancer (in the case of Web Farms) for sticky sessions, because every server will maintain a session in its memory and if the subsequent request from a client is served by various servers then the application will not behave as it is supposed to. To solve all these problems, we can use SQLServer and StateServer techniques of Session handling.

SQLServer Session

In this mode of session state the session objects are stored into SQL Server instead of a processor or server In-Memory. The "Web.config" changes are as in the following:
<sessionState mode="SQLServer" allowcustomsqldatabase="true" sqlconnectionstring="Data Source=<SERVERNAME>;Initial Catalog=<DATABASENAME>;User ID=<USERID>;Password=<PASSWORD>;"cookieless="false" timeout="100"/>
The benefit of using this technique is that all the data in the session will be stored together in a different location or you can say a centralized location in SQL Server, to get it working we just need to configure the SQLServer to store session data.
While configuring this mode in your application, one needs to consider that all the objects to be stored in a session should be serializable. So if you are currently using an In-Proc session state mode and intend that your application may require to have heavy sessions and you eventually need to shift it to SQLServer or the StateServer, then please take into consideration this "Serialization" issue from now on, because once the application is running and is the production environment, sometimes it is very difficult to make changes to session mode, because of these issues.

Configuring SQLServer to store Session data

Here I will show you how to configure SQLServer for storing session data in a custom database, although we also configure it to save session data in a temporary database, but this database goes off when you restart your SQL Server.
It is very simple by using the command line:

aspnet_regsql -d <SQLDATABASENAME> -S <SQLSERVERNAME> -U <USERNAME> -P <PASSWORD> -ssadd -sstype c

In this command "–d" specifies custom database name, "-S" specifies SQL Server Name, "-U" specifies Username, "-P" specifies Password, "-ssadd" is an option specifying we need to add support for handling session in SQLServer and "-sstype" specifies the type of storage for Session State (if we need a temporary database or a custom database) and "c" represents the custom database.

Image1.jpg

As soon as you are done with it, you will get a message saying "Finished" with a notification for the settings you need to do in "Web.Config". So here we can see the message saying to configure the sessionState in "Web.Config" to allow session data to be stored in a custom database and we need to specify the connection string for it. You can also check the database created by accessing that server; it will look something like this:

Image2.jpg

With this we are done with configuring Session State in SQLServer mode.

StateServer Session

In this mode of session state the session objects are stored in a separate server handled by a Windows Service running on that server. The "Web.config" changes are the following:
<sessionState mode="SQLServer" stateConnectionString="tcpip=<IPADDRESSOFTHESERVER>:42424"cookieless="false" timeout="100"/>

The benefit of using this technique is that all the data in the session will be stored together in a different location. In this case the server to be handled by the Windows Service is named "aspnet_state"; this will become the centralized location for session data. To get it working we just need to configure the StateServer to store Session data.

While configuring this mode in your application, one needs to take into consideration that all the objects to be stored in the session should be serializable. So if you are currently using the In-Proc session state mode and intend your application to possibly have heavy sessions and you eventually need to shift it to SQLServer or the StateServer, then please consider this "Serialization" issue, because once the application is running and is in a production environment, sometimes it very difficult to make changes to session mode, because of these issues.

Configuring StateServer to store Session data

Here I will show you how to configure StateServer for storing session data. Press "Windows + R" on your machine where you want to configure it, type in "Services.msc". Here you can see the service "ASP.NET State Service". Just start this service and you are ready to go with StateServer configuration, you can now see this service running in your "Task Manager".

Image3.jpg

As soon as you are done with it, we are good to go for using this mode of session state.

  • In-process Session State + More than One Web Server: If you're using in-proc Session on ASP.NET, remember that the session has "affinity" with the server.  That means that if www2.hanselman.com is the first server the user ever hits, the user will get an ASPSESSIONID cookie that is an index into the Cache object (the In-Proc Session is really just a key to a Hashtable-type structure inside the Cache/Application) that only exists in the memory of THAT ONE SERVER.  So, since you're using Load Balancing (you have more than one server) it's important to ensure you're using "sticky connections" or node-affinity to guarantee the user gets back to his/her session on the next HTTP Request. 
    Note that it's often tricky to get a user back to the same box when dealing with "mega-proxies" of large corporations, ISPs, and AOL.  That means that if your load-balancer (hardware or otherwise) is looking at various combinations of IP+VPORT+Whatever that these values MAY CHANGE if the ISP changes their source port or IP address.  If you're using SSL, you can use the SSL ID to route traffic, but this can slow you down a smidge.  You can also let the hardware loadbalancer add in a cookie of its own.  Check your loadbalancer's FAQ for details.  But, it's worth being aware of the things
  • Out-of-Proc (State Server) + More than One Web Server: If you are using the State Service, you might think about putting it behind your second firewall, in a different DMZ than both the Web Servers or the Database. 
  • Out-of-Proc State Server + ONLY ONE Web Server:  Some folks use the Session State Service even if they have only one Web Server so the session state isn't lost when the ASPNET_WP.EXE process recycles.  If you do this, make sure to lock down the state service to serve local requests only.
    HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnections
    You can also change the port that the state service listens on with the following key:
    HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port
    If you're using the state server in a web farm, it's important that you put it behind a firewall or otherwise prevent anything but the web servers from talking to it. [Early and AdopterEarly and Adopter]
  • WebFarm Gotchas: When you're using either the State Service or SQL Server Session State, you're indicating that you don't want "session affinity" and you'll probably set your Load Balancer to Round-Robin dispatching of traffic. (It won't using any smarts or algorithms to get traffic, it will just go 1, 2, 3, etc.)  When you do this AND you're using Forms Authentication OR you have EnableViewStateMAC set to protect your ViewState, remember to synchronize your <machinekey> between all machines in the farm.  As users move around your site, each page could put served up from a different machine, meaning that not only are your encrypted forms-auth cookies passed around, but your ViewState (protected by the machinekey) may be sourced from one machine, and posted to another.
  • Security: Remember to secure the crap out of everything you do. 


Wednesday, April 27, 2016

Introducing New Features in Entity Framework 6.1.0

Introduction
This article explains the latest version of Entity Framework, Entity Framework 6.1.0 features. The latest version of Entity Framework has some useful features that are given below and more useful features will be coming soon because this release is currently being worked on.
Check out the features below:
  • Handling of Transaction Commit Failures
  • Tooling Consolidation
  • Code First Annotations
  • IndexAttribute
  • Public Mapping API
I am describing some features in this article. So let's start.
Handling of Transaction Commit Failures
There is a new connection ability introduced in this version of Entity Framework. This feature has the functionality to encounter the short connection failure and get back automatically. Generally, there are two possible ways of exception raising during the transaction commit:
  • The transaction commit failed on the server
  • The transaction commit succeeded on the server but a connectivity issue prevented the success notification from reaching the client.
If the first exception occurs, then the user can execute the operation again. And if the second exception occurs then the user should not perform the execution again; the application could recover automatically. The new feature allows to Entity Framework  to double-click with the database it the transaction is done successfully. The following code snippet helps you to understand how we can use it:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;

namespace MvcSample.Models
{
    public class MyDbConfiguration : DbConfiguration
    {
        public MyDbConfiguration()
        {
            SetTransactionHandler(SqlProviderServices.ProviderInvariantName, () => new CommitFailureHandler());
            SetExecutionStrategy(SqlProviderServices.ProviderInvariantName, () => new SqlAzureExecutionStrategy());
        }
    }
}
Tooling Consolidation
Using this feature we can select various contents to create or generate the model. We have a single entry point for creating the Entity Data Model.
Formerly the ADO.NET Entity Data Model did not have this facility.
Entity Data Model
We must install the Entity Framework Power Tools and use the Reverse Engineer Code First Tool for creating the Code First Models that targets an existing database. Have a look:
Generating Code First
Now the new wizard has the ability to support the creation of the Code First Models or they can select the Entity Framework Designer model also. They can also choose between a new and existing database.
Updgraded Entity Data Model Wizard
That's it.
Summary
This article explained the new features of the latest Entity Framework version 6.1.0. You can also check out the upgraded data model wizard to create the model in the latest framework. Thanks for reading.

Monday, October 19, 2015

Row and Column wise sum in a table using Sqlserver



CREATE TABLE [dbo].[tbl_Sample](
[ColumnA] [int] NOT NULL,
[ColumnB] [int] NOT NULL,
[ColumnC] [int] NULL
) ON [PRIMARY]

GO

SELECT  [ColumnA]
      ,[ColumnB]
      ,[ColumnC]
  FROM [SampleTest].[dbo].[tbl_Sample]

UPDATE tbl_Sample
SET ColumnC = (ColumnA+ColumnB)
FROM (
      SELECT ROW_NUMBER() OVER (ORDER BY [COLUMNA]) AS tbl_Sample
      FROM tbl_Sample
      ) x

INSERT INTO tbl_Sample(ColumnA,ColumnB,ColumnC)
SELECT SUM(ColumnA),SUM(ColumnB),SUM(ColumnC)
FROM tbl_Sample

SELECT  [ColumnA]
      ,[ColumnB]
      ,[ColumnC]
  FROM [SampleTest].[dbo].[tbl_Sample]

Friday, October 2, 2015

SQL Query Order of Operations


  1. FROM clause
  2. WHERE clause
  3. GROUP BY clause
  4. HAVING clause
  5. SELECT clause
  6. ORDER BY clause
This order holds some very interesting pros/cons:

FROM Clause

Since this clause executes first, it is our first opportunity to narrow down possible record set sizes. This is why I put as many of my ON rules (for joins) as possible in this area as opposed to in the WHERE clause:
FROM
contact c
INNER JOIN
display_status d
ON
(
c.display_status_id = d.id
AND
d.is_active = 1
AND
d.is_viewable = 1
)

This way, by the time we get to the WHERE clause, we will have already excluded rows where is_active and is_viewable do not equal 1.

WHERE Clause

With the WHERE clause coming second, it becomes obvious why so many people get confused as to why their SELECT columns are not referencable in the WHERE clause. If you create a column in the SELECT directive:
SELECT
( 'foo' ) AS bar

It will not be available in the WHERE clause because the SELECT clause has no
t even been executed at the time the WHERE clause is being run.

ORDER BY Clause

It might confuse people that their calculated SELECT columns (see above) are not available in the WHERE clause, but they ARE available in the ORDER BY clause, but this makes perfect sense. Because the SELECT clause executed right before hand, everything from the SELECT should be available at the time of ORDER BY execution.
I am sure there are other implications based on the SQL clause order of operations, but these are the most obvious to me and can help people really figure out where to tweak their code.

order-of-execution-of-the-query

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.
  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP
FROM [MyTable]
    ON [MyCondition]
  JOIN [MyJoinedTable]
 WHERE [...]
 GROUP BY [...]
HAVING [...]
SELECT [...]
 ORDER BY [...]

Thursday, October 1, 2015

abstract, sealed, static, and partial in c#

  1. Why do we want to have class as Abstract?

    Abstract – Abstract classes are incomplete classes, i.e., they will have combination of implemented and unimplemented methods along with data members, properties, events, delegates and indexers.
    The main idea to have class as abstract is to have only Base class that can be derivable and that will have basic functionality. As I mentioned above, we can have unimplemented method in abstract class that gives flexibility to derived classes to implement as required along with basic functionality. And also, we can’t instantiate object of abstract class. Abstract class can be with/without abstract methods. But if methods are declared as abstract in a class, that class also should be declared as abstract.
    Sealed – Sealed classes are classes that are not inheritable. Methods also can be sealed, that is, those methods declared as sealed can’t be overridable, i.e., derived classed can’t override those methods. And normal classes can’t have sealed method. Sealed keyword should be declared with overridekeyword in the derived class' method for which base class will have virtual method.

    Why do we want to have class and method as Sealed?

    The reason to have class and method as sealed is to stop the inheritance at one level.

    Where to use sealed?

    If you think that class is not to be inherited in your design, you can use class as sealed. But sealed class can inherit from interface and class. If you think virtual method cannot to be inherited in derived class at one stage, we can declare a method with sealed+override combination.
    By default structures are sealed, that is the reason structures are not supporting inheritance.

    Why do we want to have class and methods as static?

    In your design, if you feel that a class should have a set of methods which operate only on arguments that we pass without initiating object of that class, then we can make that class as static class (Example:System.Math). Merely call those instance methods by class name.

    How this class will be loaded without creating an object?

    If your code accesses any of static class’s methods, then this is the responsibility of CLR (Common Language Runtime) to load this class into memory once which is the lifetime of your application.
    Object of static class can’t be instantiated. Why? Since static class can’t have instance constructor.Static class supports inheritance but other classes can’t inherit from static class, i.e., static classes are sealed. Classes can have static methods but static classes can’t have instance member and instance methods .if, should be declared with static keyword.
    Static class is useful when you implement Singleton Design pattern.

    What does partial modifier indicate?

    Partial key word is to declare the class as partial meant to say it splits the classes into multiple parts under the same class name in a single namespace.
    Why? So that developers can implement the functionally for the same class parallely.
    But all combined will give one class. Each split class can have instance variable, instance methods, properties, indexers, events and delegates.
    Structures can’t have modifiers like abstractsealed, and static whereas classes can have.
    Both structure and class can have partial modifiers.
    As I mentioned earlier, structures can have method declaration but not virtual and sealed methods. Why? Since those two are essential for inheritance. Anyhow, the structure won’t support inheritance and declaring methods using those two keywords will throw compile time errors.
  2. Classes can have explicitly parameterless constructors whereas structures can’t.
  3. Member variable initialization is possible in class whereas in Structures, it is not.
  4. It is not possible to declare destructor in structure but in class it is possible.
  5. Process of converting structure type into object type is called boxing and process of converting object type into structure type is called unboxing.Example: int a=10;
    Object ob = (object) a;  //Boxing
     a= (int) obj;   //Unboxing
  6. The “this” keyword gives different meaning in structure and class. How?
    1. In class, “this” keyword is classified as value type of class type within which it is used like inside instance constructor or instance method.
    2. In structure, “this” keyword is classified as variable type of structure type within which it is used.