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.

Thursday, November 24, 2016

ProgressBar in C#

A ProgressBar control is used to represent the progress of a lengthy operation that takes time where a user must wait for the operation to be finished. 

In this article, we will see how to create a ProgressBar control in a Windows Forms application using Visual Studio 2010. We will also discuss the properties and methods defined in the ProgressBar class. 
Creating a ProgressBar
We can create a ProgressBar control using a Forms designer at design-time or using the ProgressBar class in code at run-time. 
Design-time
To create a ProgressBar control at design-time, you simply drag a ProgressBar control from the Toolbox and drop onto a Form in Visual Studio. After you the drag and drop, a ProgressBar is created on the Form; for example the ProgressBar1 is added to the form and looks as in Figure 1. 

Figure 1
Run-time
Creating a ProgressBar control at run-time is merely a work of creating an instance of the ProgressBar class, set its properties and add the ProgressBar class to the Form controls. 
The first step to create a dynamic ProgressBar is to create an instance of the ProgressBar class. The following code snippet creates a ProgressBar control object:
C# Code:
ProgressBar pBar = new ProgressBar();

VB.NET Code:

Dim pBar As New ProgressBar()

In the next step, you may set the properties of the ProgressBar control. The following code snippet sets the Location, Name, Width, and Height properties of a ProgressBar.
C# Code:
pBar.Location = new System.Drawing.Point(20, 20);
pBar.Name = "progressBar1";
pBar.Width = 200;
pBar.Height = 30;

VB.NET Code:

pBar.Location = New System.Drawing.Point(20, 20)
pBar.Name = "progressBar1"
pBar.Width = 200
pBar.Height = 30

Once the ProgressBar control is ready with its properties, the next step is to add the ProgressBar to a Form. To do so, we need to add the ProgressBar control to the form using the Controls.Add method as in the following.

C# Code:
Controls.Add(pBar); 

VB.NET Code:

Controls.Add(pBar) 

Setting ProgressBar Properties
After you place a ProgressBar control on a Form, the next step is to set the properties. 
The easiest way to set the properties is from the Properties Window. You can open the Properties window by pressing F4 or right-clicking on a control and selecting the "Properties" menu item. The Properties window looks as in Figure 2. 

Figure 2
Name 
The Name property represents a unique name of a ProgressBar control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ProgressBar control. 
C# Code:
PBar.Name = "ProgresBar1";

VB.NET Code:

PBar.Name = "ProgresBar1"
Positioning a ProgressBar 
We can use the Location property to position a control. We can also dock a control using the Dock property. 
Note: A ProgressBar can only be positioned horizontally. 
The Dock property is used to set the position of a ProgressBar. It is of the type DockStyle that can have values Top, Bottom, Left, Right, and Fill. The following code snippet sets the Location, Width, and Height properties of a ProgressBar control. 
C# Code:
pBar.Dock = DockStyle.Bottom;

VB.NET Code:

PBar.Dock = DockStyle.Bottom
Minimum, Maximum, and Value 
The Minimum and Maximum properties define the range of a ProgressBar. The Value property represents the current value of a ProgressBar. The current value of the ProgressBar for the minimum value is the color green to show the progress of the control. We can also use the Value property to show the progress of an operation. 
C# Code:
pBar.Minimum = 0;
pBar.Maximum = 100;
pBar.Value = 70;

VB.NET Code:

PBar.Minimum = 0
PBar.Maximum = 100
PBar.Value = 70

A ProgressBar with a value looks as in Figure 3.


Figure 3
RightToLeftLayout and MarqueeAnimationSpeed 
The default progress of a ProgressBar is from left to right. But the ProgressBar control can also show the progress from right to left by setting RightToLeftLayout to true. The MarqueeAnimationSpeed property represents the time period, in milliseconds, that it takes the progress block to scroll across the progress bar.
Summary 

In this article, we discussed how to create menus using the ProgressBar control. First we discussed how to create menus at design-time and run-time. After that we saw, how to set menus properties and click event handlers. 

Regular Expressions Usage in C#

Description 
The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.
Explanation of Regular Expressions:
Regular expressions are used to search specified in the source string.
Examples:
Pattern#1
Regex objNotNaturalPattern=new Regex("[^0-9]");

Pattern#2  
Regex objNaturalPattern=new Regex("0*[1-9][0-9]*"); 
Pattern#1 will match for strings other than 0 to 9.^ symbol is used for Specifying not condition.[] brackets if we are to give range values such as 0 - 9 or a-z or A-Z  
eg. abc will return true
123 will return false.   
Pattern#2 will match for string which are Natural Numbers.Natural numbers Are numbers which are always greater than 0.The pattern 0* tells that a natural Number can be prefixed with any number of zero's or no zero's.the next [1-9] tells that it should contain atleast one number from 1 to 9 followed by any numbers of
0-9's 
Eg. 0007 returns true whereas 00 will return false. 
Basic things to be understood in RegEx: 
"*" matches 0 or more patterns
"?" matches single character
"^" for ignoring matches.
"[]" for searching range patterns.
More RegEx patterns in Next Article. 
Source Code:
// Source Code startsusing System.Text.RegularExpressions;using System;/*
<HowToCompile>
csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs 
</HowToComplie>
*/
 class Validation
public static void Main()
{
String strToTest;
Validation objValidate=
new Validation();
Console.Write("Enter a String to Test for Alphabets:");
strToTest=Console.ReadLine();
if(objValidate.IsAlpha(strToTest))
{
Console.WriteLine("{0} is Valid Alpha String",strToTest);
}
else{
Console.WriteLine("{0} is not a Valid Alpha String",strToTest);
}
// Function to test for Positive Integers. public bool IsNaturalNumber(String strNumber)
{
Regex objNotNaturalPattern=
new Regex("[^0-9]");
Regex objNaturalPattern=
new Regex("0*[1-9][0-9]*");return !objNotNaturalPattern.IsMatch(strNumber) &&
objNaturalPattern.IsMatch(strNumber);
// Function to test for Positive Integers with zero inclusive public bool IsWholeNumber(String strNumber)
{
Regex objNotWholePattern=
new Regex("[^0-9]");return !objNotWholePattern.IsMatch(strNumber);
// Function to Test for Integers both Positive & Negative public bool IsInteger(String strNumber)
{
Regex objNotIntPattern=
new Regex("[^0-9-]");
Regex objIntPattern=
new Regex("^-[0-9]+$|^[0-9]+$");return !objNotIntPattern.IsMatch(strNumber) && objIntPattern.IsMatch(strNumber);
// Function to Test for Positive Number both Integer & Real public bool IsPositiveNumber(String strNumber)
{
Regex objNotPositivePattern=
new Regex("[^0-9.]");
Regex objPositivePattern=
new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
Regex objTwoDotPattern=
new Regex("[0-9]*[.][0-9]*[.][0-9]*");return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber);
// Function to test whether the string is valid number or notpublic bool IsNumber(String strNumber)
{
Regex objNotNumberPattern=
new Regex("[^0-9.-]");
Regex objTwoDotPattern=
new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex objTwoMinusPattern=
new Regex("[0-9]*[-][0-9]*[-][0-9]*");
String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
Regex objNumberPattern =
new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");return !objNotNumberPattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
// Function To test for Alphabets. public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern=
new Regex("[^a-zA-Z]");return !objAlphaPattern.IsMatch(strToCheck);
}
// Function to Check for AlphaNumeric.public bool IsAlphaNumeric(String strToCheck)
{
Regex objAlphaNumericPattern=
new Regex("[^a-zA-Z0-9]");return !objAlphaNumericPattern.IsMatch(strToCheck); 
}
// Source Code End