Explain about Partial Class and partual methods

Introduction

Recently I was researching about partial classes and their real world use. Many of the postings found on Google talked about the concept of partial classes and partial methods, but very few highlighted in what scenarios to use them.
In this article, we will first start with the fundamentals of partial classes and methods and then discuss four real world uses. I have also created a video here where I have discussed about partial classes and shown their real world use.

Fundamentals of partial classes

A partial class allows a single class to be divided into two separate physical files. During compile time, these files get compiled into a single class. For instance, you can see in the below figure we have the customer class divided into two different files “customer1.cs” and “customer2.cs”.
During compilation, these files get compiled into a single class internally. So when you create an object of theCustomer class, you will be able to see methods lying in both the physical files. For instance, you can see the Addmethod belongs to customer1.cs and the Delete method belongs to customer2.cs, but when the Customer object is created, we can see both the Add and Delete methods.

Fundamentals of partial methods

There is one more important concept in partial classes called partial methods. Partial methods helps us to define a method in one physical file and we can implement that method in another physical file, as shown in the below figure.
In the figure, you can see we have defined the Validate method in Customer1.cs and this Validate method is implemented in Customer2.cs. Please note the partial keywords attached to both of these methods.

Use number 1: ASP.NET auto generated code

The biggest use of partial classes is in technologies where there is code generation. The Microsoft team themselves use partial classes in ASP.NET, LINQ, and EF code generation. For instance when we look at ASP.NET, there are two parts: the auto generated code of a page and the code-behind where you write your custom logic.
The custom logic is written in the “.aspx.cs” file while the auto generated logic is in the “.aspx.designer.cs” file, as shown in the below figure.
As a developer, you would like the auto generated code to do its work, i.e., generate code when you drag and drop a button in the ASP.NET designer.
Below is how the auto generated code looks like:
public partial class WebForm1 {
        
    /// <summary>
    /// form1 control.
    /// 
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.HtmlControls.HtmlForm form1;
    
    /// <summary>
    /// Button1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.Button Button1;
        
    /// <summary>
    /// Label1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.Label Label1;
}
At the same time, you would also like to customize the code in some other file in such a way that the auto generation part is not disturbed. For that, ASP.NET provides the “.aspx.cs” file which is a partial class where you can put your own custom logic.
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Your custom logic
    }
}
This is only possible when the class is split into two physical files but united via the partial keyword. So if you look at any ASP.NET code-behind class file, it’ll be marked with the word partial.
By using the partial keyword in ASP.NET, the Microsoft team has made VS and developers work side by side thus not fiddling with each other’s code and increasing productivity.

Use number 2: LINQ and Entity Framework

LINQ and EF also use partial classes and methods heavily because of the auto generation nature of these technologies. So when you drag tables in these framework, they create auto generated classes as shown in the below figure.
In the figure, you can see how the auto generated code has partial classes and partial methods.
The partial methods later can be extended to put custom logic. For instance, you can see in the below code that for the above auto-generated class tblCustomer, we have used partial methods to override the OnCustomerCodeChangedevent to ensure that customer code is not more than 8 characters.
public partial class tblCustomer
{
    partial void OnCustomerCodeChanged()
    {
        if (_CustomerCode.Length > 8)
        {
            throw new Exception("Customer code can not be greater than 8");
        }
    }
}
So by using partial classes and partial methods, LINQ and EF keep auto generating classes and by using partial methods, we can customize the classes with our own logic.

Use number 3: Better maintenance by compacting large classes

The other important use of partial classes is for better maintenance of the project. If you have large classes with lots of methods as shown in the figure, it’s a bit of a pain to maintain those classes.
By using partial classes, you can split them into physical files as shown in the below figure, thus making your project better and easy to maintain.

Use number 4: Multiple people working on the same class

The last and final real world use I see of partial classes is when we want developers to work simultaneously in the same class. I agree this can be a very rare use as there are better options like using a version control software like TFS or Subversion, but in case you want something quick and local, this option is not bad at all.

SSL on IIS 7.0

SSL enables browsers to communicate with a web-server over a secure channel that prevents eavesdropping, tampering and message forgery.  You should always use SSL for login pages where users are entering usernames/passwords, as well as for all other sensitive pages on sites (for example: account pages that show financial or personal information). 
Configuring SSL on Windows with previous versions of IIS has been a pain.  Figuring out how to install and manage a certificate, and then associate it with a web-site, is something I bet most web developers don't know how to enable.
The good news is that IIS 7.0 makes it radically easier to configure and enable SSL.  IIS 7.0 also now has built-in support for creating "Self Signed Certificates" that enable you to easily create test/personal certificates that you can use to quickly SSL enable a site for development or test purposes. 
Using IIS 7.0 you can SSL enable an existing web site in under 30 seconds.  The below tutorial demonstrates how to-do this.
Step 1: Create a New Web Site
We'll start by creating a new web-site using the new IIS 7.0 admin tool.  This admin tool is a complete re-write of the previous IIS admin tool (and was written entirely in managed code using Windows Forms), and provides a more logical organization of web features.  It provides a GUI admin experience for all ASP.NET and IIS settings:
 
To create a new site on the box, right click on the "Web Sites" node in the left hand tree-view pane and choose the "Add Web Site" context menu option.  Enter the appropriate details to create a new web-site:
One nice feature of IIS7 on Windows Vista is that you can now have an unlimited number of sites on a box (previous versions of IIS on Windows Client only allowed 1 site).  The 10 simultaneous request limitation on Windows Client versions of IIS also no longer exists with IIS 7.0.
Once we've completed the above steps, we will now have a brand new site running on our IIS web-server.
Step 2: Create a new Self Signed Certificate
Before binding SSL rules to our new site, we need to first import and setup a security certificate to use with the SSL binding. 
Certificates are managed in IIS 7.0 by clicking the root machine node in the left-hand tree-view explorer, and then selecting the "Server Certificates" icon in the feature pane on the right:
This will then list all certificates registered on the machine, and allow you to optionally import and/or create new ones.
I could optionally go to a certificate authority like Verisign and purchase a certificate to import using this admin UI.  Alternatively, I can create a "self-signed certificate" which is a test certificate that I can use during the development and testing of my site.  To-do this, click the "Create Self-Signed Certificate" link on the right-hand side of the admin tool:
Enter a name to use for the certificate (for example: "test") and hit ok.  IIS7 will then automatically create a new self-signed crypto certificate for you and register it on the machine:
Step 3: Enable HTTPS Bindings for our New Site
To SSL enable the web-site we created earlier, select the web-site node in the left-hand tree-view, and the click the "Bindings" link in its "actions" pane on the right-hand side of the screen:
This will then bring up a dialog that lists all of the binding rules that direct traffic to this site (meaning the host-header/IP address/port combinations for the site):
To enable SSL for the site, we'll want to click the "Add" button. This will bring up an "add binding" dialog that we can use to add HTTPS protocol support.  We can select the self-signed certificate we created earlier from the SSL certificate dropdownlist in the dialog, and in doing so indicate that we want to use that certificate when encrypting content over SSL:
Click ok, and we now have SSL enabled for our site:
Step 4: Test out the Site
Add a "default.aspx" page to the site, and then try and hit it with the browser by typing https://localhost/default.aspx (note the usage of "https" instead of "http" to indicate that you want to connect over SSL).
If you are using IE7, you'll likely see this anti-phishing error message kick in
Don't panic if this happens - it is just IE being helpful by suggesting that a self-signed certificate on your local machine looks suspicious. Click the "Continue to this website" link to bypass this security warning and proceed to the site.  You'll find that your default.aspx page is now running protected via SSL:
You are all done. :-)
Appendix: A Few Last SSL Notes
A few last SSL related notes:
  • The IIS 7.0 admin tool has an "SSL Settings" node that you can select for each site, directory or file that allows you to control whether that particular resource (and by default its children) requires an SSL request in order to execute.  This is useful for pages like a login.aspx page, where you want to guarantee that users can only enter their credentials when they are posting via an encrypted channel. If you configure the login.aspx page to require SSL, IIS 7.0 will block browsers from accessing it unless they are doing so over SSL.
  • Within an ASP.NET page or handler, you can programmatically check whether the current request is using SSL by checking the Request.IsSecure property (it will return "true" if the incoming browser request is over SSL).
  • You can set the "requireSSL" attribute on the <forms> configuration section within web.config files to have ASP.NET's forms-authentication system ensure that forms-authentication cookies are only set and used on SSL enabled pages and URLs.  This avoids the risk of a hacker trying to intercept the authentication cookie on a non-SSL secured page, and then trying to use a "replay attack" from a different machine to impersonate a user.

Explain about Constant and ReadOnly and Static

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.

Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
  1. public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
  1. void Calculate(int Z)
  2. {
  3. const int X = 10, X1 = 50;
  4. const int Y = X + X1; //no error, since its evaluated a compile time
  5. const int Y1 = X + Z; //gives error, since its evaluated at run time
  6. }
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
  1. const MyClass obj1 = null;//no error, since its evaluated a compile time
  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
  1. class MyClass
  2. {
  3. readonly int X = 10; // initialized at the time of declaration
  4. readonly int X1;
  5.  
  6. public MyClass(int x1)
  7. {
  8. X1 = x1; // initialized at run time
  9. }
  10. }
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.

Static

The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
  1. class MyClass
  2. {
  3. static int X = 10;
  4. int Y = 20;
  5. public static void Show()
  6. {
  7. Console.WriteLine(X);
  8. Console.WriteLine(Y); //error, since you can access only static members
  9. }
  10. }

Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can't be parameterized and public. Static constructor is always a private default constructor which is used to initialize static fields of the class.


    -------------------------------------------------------------------------------------------------------


    These are very common keywords and are quite confusing. So today we will discuss these keywords and try to understand them.
    1. Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

      Csharp-Const-ReadOnly-and-StaticReadOnly1.jpg

      Here I have created a class named Variables and defined all three variables, so first let's play with const.

      Csharp-Const-ReadOnly-and-StaticReadOnly2.jpg

      Here I tried to de-initialize the const variable, it gaves me an error like "A const field requires a value to be provided".  Ok now I initialize a value for this variable and try to change it further in the class.

      Csharp-Const-ReadOnly-and-StaticReadOnly3.jpg

      Here I have created a static constructor, default constructor, parameterized constructor and a Simple Method. I tried to change the value of the const variable everywhere but once I assign the value, I am unable to change it again since when I do it gives me a compile time error as you can see in the snapshot above.

      Now let's on to the readonly keyword.
       
    2. Readonly: Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor. Not even a method. Let's see:

      Csharp-Const-ReadOnly-and-StaticReadOnly4.jpg

      Here first I try to initialize the value in the static constructor. It gives me an error. Which you can see above.
      Now I try to change the value in a method, see what happened:

      Csharp-Const-ReadOnly-and-StaticReadOnly5.jpg
       
      Here, it is also giving an error that you can only assign a value either through a variable or a constructor.
      Now try to change the value in the default constructor.

      Csharp-Const-ReadOnly-and-StaticReadOnly6.jpg
       
      Now in the snapshot above you can see it's built successfully without an error, warning or messages. Let's check if there is a runtime error. OK.

      Csharp-Const-ReadOnly-and-StaticReadOnly7.jpg
       
      Now here we can see that there is not a runtime error and the value was assigned successfully to the Readonly variable.
      Now one gotcha is, now that you have assigned the value, can you change this value again ??? 
      Let's try to change the value again.

      Csharp-Const-ReadOnly-and-StaticReadOnly8.jpg

       
      Here I created  a parameterized constructor and created a new object, and passing a value as "Hello Frend'z" and as I built it, it gave me the result "Build Succeeded".  Now let's move ahead and check for a runtime error:

      Csharp-Const-ReadOnly-and-StaticReadOnly9.jpg
       
      See guys. There is no runtime error !!  And the value can be changed again and again through a constructor.
       
      Now move ahead to Static Readonly variables.
       
    3. Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime. Let's understand it practically.

      Csharp-Const-ReadOnly-and-StaticReadOnly10.jpg

      Now in the preceding you can see that I used two variables, one is not assigned and another is assigned, and the static constructor.  Now in the static constructor you can see that the unassigned variable is being assigned and the assigned value is being changed. And there is no compile time error. Further I try to again change this variable's value.  See what happened:

      Csharp-Const-ReadOnly-and-StaticReadOnly11.jpg
       
      As you can see in the above, I created Default, Parameterized Constructor and Method and tried to change the value again here. But I am getting a compile time error for all.