Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Wednesday, December 21, 2016

Sealed Class and Sealed Methods in C#

This article explains how to create and use a sealed class using C#. We will also review why programming gurus use sealed classes in their code and products.

Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited. 

In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an error. 

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.  


Sealed Class


Sealed class is used to define the inheritance level of a class.

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. 

Some points to remember:  

1.  A class, which restricts inheritance for security reason is declared, sealed class.
2.  Sealed class is the last class in the hierarchy.
3.  Sealed class can be a derived class but can't be a base class.
4.  A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are
     restricting it to inherit.

Practical demonstration of sealed class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sealed_class
{
    class Program
    {
        public sealed class BaseClass
        {
            public void Display()
        {
            Console.WriteLine("This is a sealed class which can;t be further inherited");
        }
    }

        public class Derived : BaseClass
        {
            // this Derived class can;t inherit BaseClass because it is sealed
        }
   
        static void Main(string[] args)
        {
            BaseClass obj = new BaseClass();

            obj.Display();

            Console.ReadLine();
        }
    }
}

Sealed Methods


Sealed method is used to define the overriding level of a virtual method.

Sealed keyword is always used with override keyword. 

Practical demonstration of sealed method


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sealed_method
{
    class Program
    {
        public class BaseClass
        {
           
            public virtual void Display()
            {
                Console.WriteLine("Virtual method");
            }
        }

       public class DerivedClass : BaseClass
        {
            // Now the display method have been sealed and can;t be overridden
            public override sealed void Display()
            {
                Console.WriteLine("Sealed method");
            }
        }

       //public class ThirdClass : DerivedClass
       //{

       //    public override void Display()
       //    {
       //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");
       //    }
       //}

        static void Main(string[] args)
        {

            DerivedClass ob1 = new DerivedClass();
            ob1.Display();

            Console.ReadLine();
        }
    }
}

Hope this article will give you better view of sealed class and sealed method. Waiting! for your valuable feedback.

Why should we use MVC vs normal ASP.NET?

There are various positive points to moving towards MVC

1.  TDD support out of the box as most of the design is based on interfaces.
2.  SEO friendly URL by design (though now this is possible in ASP.NET 4 as well)
3.  No ViewState (this may seem a bit of moving backward to some), but overall a good design decision.
4.  Clean View Markup (no additional HTML emitted)
5.  100% extensible.  You can add your own controller with IOC, switch view engines at will, control model binding at wish etc.
6.   Rich UI support (possible through client side JS libraries like jQuery UI and others).  Telerik has released some controls for MVC which includes Grid control as well (which are merely HTMLHelpers)
7.  Session, JS, Ajax works.  Validation is even more powerful with DataAnnotations and jquery.
8.  Is MVC faster?  Yes by default because of lack of viewstate and clean markup.  But performance is subject and MVC by design is more performant that traditional ASP.NET webforms (though webforms can be made as fast as required.
9.  Out of the box support for mitigating antiforgery attacks and XSS vulnerability (though asp.net does has this to some extent)
10.  Out of the box minimal IOC support.
11.  Full control over rendered HTML
12.  Pluggable architecture
13.   And much more....

Couple of limitations (though not exactly)
1.  Learning curve as most asp.net developers are used to windows form model for web development.


NOTE:  Webforms is not bad.  But by design it encourages many bad practices.  A webform at the hands of careful developer is as or could be even more productive than MVC.  Just my thought.

Additional readings at http://msdn.microsoft.com/en-us/magazine/dd942833.aspx

Hope this helps.

Friday, December 9, 2016

Exploring Connection In ADO.NET

What is connection in ADO.NET?

ADO.NET connection is an object of connected architecture just like any other C# object. When the connection of an object is instantiated , use a constructor with single string type of an argument. This argument is called the connection string. Once the connection string is passed in the connection object, by connection of an object, you can establish a connection with the database. With the help of this connection, string will identify the database and the Server name, and authentication parameters (User ID, password). Basically, a connection string is typically stored in web.config file.

What namespace or provider is used for connection class?

ADO.NET provides connection to the multiple providers but it depends on your working condition, which means, what database is used in backend and how to communicate between client to server. Thus, now the data provider is used.
  • Data Provider for SQL Server (System.Data.SqlClient).
  • Data Provider for MSACCESS (System.Data.OleDb).
  • Data Provider for MYSQL (System.Data.Odbc).
  • Data Provider for ORACLE (System.Data.OracleClient).
How to use connection class with this provider is given below-
  • Connection object for SQL Server (SqlConnection).
  • Connection object for MSACCESS (OleDbConnection).
  • Connection object for MYSQL (OdbcConnaction).
  • Connection object for ORACLE (OracleConnection).
Before working with the database, you have to add the data provider namespace, by placing the following at the start of your code module.

For SqlClient .NET data provider namespace, using-

            Using System.Data.SqlClient  

Similarly, for OLE DB, ODBC, OracleClient .NET data provides namespace, using-
            Using System.Data.OleDb 
            Using System.Data.Odbc 
            Using System.Data.OracleClient 

Properties of connection object  
PropertyDescription
AttributesWe can get or set attributes of the connection object.
Command Timeout
By Command time out, we can get or set number of seconds to wait, while attempting to execute a command.
Connection TimeoutBy Connection time out, we can get or set number of seconds to wait for the connection to open.
Connection StringConnection string is used to establish and create connection to data source by using server name, database name, user id and password.
Cursor LocationIt gets or set slocation of cursor service.
Default DatabaseIt gets or returns default database name.
Isolation LevelIt gets or returns isolation level.
ModeBy mode property, we can check provider access permission.
ProviderBy this property, we can get or set provider name.
StateBy this property, we can check your current connection open or close before connection opening or closing
VersionThis returns the ADO version number.
Method of connection object 
MethodDescription
BeginTransactionBegin to current transaction.
CancelCancel an execution.
CloseClose method is used, when any current connection is open and finally its closed after completed execution.
OpenOpen method is used, if current connection is close then before execution started. First of all You have opened connection must.
ExecuteBy this method it is used to execute query. Like as Statement, procedure or provider provides specific text.
OpenSchemaIt returns schema information from the provider about the data source.
RollBackTransationThis method invokes, whenever you cancel any changes or any conflict occurs in the current transaction, it ends the current transaction.
CommitTransationIf current transaction execution is successfully completed, it ends the current transaction.


Connection Pooling 

When establishing a connection, the database Server is a heft and high resource consuming process. If any Application needs to fire any query against any database Server we need to first establish a connection with the Server and then execute a query against that database Server.

Afterwards, it involves the overhead of the network label handshaking. ADO.NET uses a technique called connection pooling, which is minimize the cast of opening and closing connections. Connection pooling is reused in an existing active connection with the same connection string, instead of creating a new connection string. Thus, several pools exist, if different connection string asks for the connection pooling.

You can turn off pooling for a specific connection by including the pooling=”false” key-value pair in your connection string.

The sqlconnection class also includes two method ClearPool and ClearAllPools, which lets you clear its associated pool.

Connection string pooling attributes 
  • Connection Lifetime - When we have specified connection lifetime sizes, it means this indicates the length of time in seconds after connection creation. Thus, by default, it is 0. This indicates that the connection will have maximum timeout. 
  • Connection Reset - This property specifies the connection is reset, when removed from the pool. This is by default is true.
  • Load Balance Timeout - When we have specified connection lifetime sizes, this indicates the length of time in seconds. A connection can remain idle in a connection pool before being removed.
  • Max Pool Size - Maximum pool sizes indicate the maximum number of connections allowed in the pool. The default is 100.
  • Min Pool Size - Maximum pool sizes indicate the minimum number of connections maintained in the pool. The default is 0.
  • Pooling: - When pooling is set true, the connection is drawn from the appropriate pool, else if it is necessary, create and add to the appropriate pool. By default, it is true.