Thursday, 30 July 2015

Value and Reference Types - Stack vs Heap in .Net

Value and Reference Types :

When ever we declared any variable in .Net whether it is primitive data type or a custom data type(Instantiate a class), part of memory is allocated to store the value of this variable.

If variable is a value type, a single space in memory is allocated to store the value of this variable.Struct is value type in .Net.

With reference type, however, an object is created in memory, and then handled through a separate reference, means two separate memories are allocated.

Stack and Heap are the two memory management techniques used by .Net. 

Whenever we declare Struct type in .Net, memory for these variables will be allocated in stack.
Variable like int, float, double, byte, bool etc. all are of type Struct so memory for these variables also stored in stack.
The Stack is self-maintaining, meaning that it basically takes care of its own memory management. When the top box is no longer used, it's thrown out.

Any class, delegates, interface, string ,object and array are the reference type and stored in heap.
Two different memories are allocated for reference variable, one in a heap that store object and other memory contain reference of this heap memory and itself stored in stack.

Unlike stack, heap doesn't have any restriction to access the memory.any memory cab be accessed randomly.

Note 1 : As we already know, System.Object is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
Any variable that has Object class as it's root base class, will be type of reference variable.


Note 2 : Any reference type variable stored in a Heap. Whereas, where value type variable will store depends on where it is declared.If value type variable used with in a class, when we create the object of that class, value type variable will be stored within Heap other wise it will stored within Stack.

Suppose Address is a struct, and Employee is a class. We can instantiate each as follows:

Address a1 = new Address();        // Address is a *struct*
Employee e1 = new Employee();   // Employee is a *class*

In the first case, one space in memory is allocated for a1, wheras in the second case, two spaces are allocated: one for a Employee object and another for its reference (e1).

Employee e1;                   // Allocate the reference
e1 = new Employee ();     // Allocate the object

If we copy the objects to new variables:

Address a2 = a1;
Employee e2 = e1;

a2, being a struct, becomes an independent copy of a1, with its own separate fields. But in the case of e2, all we’ve copied is a reference, with the result that both e1 and e2 point to the same object.

When passing parameters to methods. In C#, parameters are (by default) passed by value, meaning that they are implicitly copied when passed to the method. For value-type parameters, this means physically copying the instance (in the same way a2 was copied), while for reference-types it means copying a reference (in the same way e2 was copied). Here is an example:

Address myAddress = new Address ("delhi", 110096);      // a new value-type variable
Employee myEmployee = new Employee ();         // a new reference-type variable
Test (myAddress , myEmployee );        // Test is a method defined below

void Test (Address a, Employee e)
{
a.City = "Mumbai";             // No effect on MyAddress since a is a copy
e.Name = "TestName";       // This will change myEmployee’s name since
                                           // myEmployee and e point to the same object
e = null;                               // No effect on myEmployee
}

Assigning null to e has no effect because e is a copy of a reference, and we’ve only erased the copy.

We can change the way parameters are marshalled with the ref modifier. When passing by “reference”, the method interacts directly with the caller’s arguments. In the example below, you can think of the parameters a and e being replaced by myAddress and myEmployee:

Address myAddress = new Address ("delhi", 110096); // a new value-type variable
Employee myEmployee = new Employee ();                 // a new reference-type variable
Test (ref myAddress, ref myEmployee);                   // pass myAddress and myEmployee by reference

void Test (ref Address a, ref Employee e)
{
a.City = "Mumbai";                // This will change myAddress’s City
e.Name = "TestName";          // This will change MyEmployees’s Name
f = null;                                  // This will nuke the myEmployees variable!
}

In this case, assigning null to e also makes myEmployee null, because this time we’re dealing with the original reference variable and not a copy of it.

Monday, 27 July 2015

SSL and Https in asp.net

Https : Hyper Text Transfer Protocol Secure (HTTPS) is the secure version of HTTP.

Advantages of using Https :

When web server and clients communicates using http protocol, the messages that are exchanged over the network are not encrypted. so sensible information like username and passwords and financial transaction should not be done over http protocol.
That's why all the banking applications uses https protocol because messages exchanges between client and server over https protocol is encrypted and very secure.

By default http uses port 80 and https uses port 443.See below image of IIS binding.




We can configure IIS to use https.the encryption and decryption between client and server is done by server certificates.These server certificates should be installed on IIS.

SSL is a standard security technology for establishing an encrypted link between a web server and a client so that data sent over the internet can't be read by others.

SSL uses server certificates for encryption and decryption.When client request for secure web page, the server generates an encryption key for the user's session and then encrypts the page's data before sending a response.On client side browser uses same key to decrypt the response received from server and also encrypt new request send from that page.

SSL certificate contains a public key and certificate issuer.Client not only use this certificate to communicate with server also verified that certified is signed by an official certificate authority.

Server certificates are issued by an entity called certificate authority like Versign,Comodo,Geotrust.

When browser request for page over https, browser also request for certificate and checks it against a list of trusted site provided by certificate authority.if the server certificate does not match the web address for which it was registered, or if any other problem with the certificate occur, a warning message is displayed.

It is also possible to generate our own server certificates using tool called makecert.exe. this tool comes with visual studio.the certificate generated using this tool can be used for testing purpose not for production.

Self signed certificate :
This is a certificate that is signed by its own creator not by certificate authority. self signed certificates are fine for testing purpose not for production.

Create Self signed certificate :

  • Using IIS
  • Using MakeCert.exe

1. Create Self signed Certificate



2. Associate certificate with asp.net application :Add Https site binding if it is not already present.


3. Check Require SSL check box otherwise site can be accessed over http also.




Once you check Require SSL option, any request comes from http will get error message.
To resolve this message we need to unchecked this option and rewrite the url from http to https.

Url rewriting can be done through web.config or you can install IIS url rewrite extension and configure same using IIS.


Friday, 24 July 2015

Authentication in Asp.Net - Forms Authentication

This post is continuation of post Authentication in Asp.Net. Please visit following link before reading this post.
Authentication in Asp.Net - Anonymous Authentication

Forms authentication is used for internet web applications.The advantage of forms authentication is, unlike windows authentication, users do not have to be member of a domain-based network to access the application.

Forms authentication classes are present in System.Web.Security namespace.

If you are going to use form authentication you should set authentication mode in web.config file.

<authentication mode="Forms">

If you are using form authentication, Under the authentication tag, you should tell the url of page which you are using for your login purpose.

 <authentication mode="Forms">
      <forms loginUrl="Login.aspx" />
   </authentication>

Within the forms tag we can set the credentials of users.Only listed users under the credential tag can access the application through login.
Within authorization tag you have to deny anonymous user.Doing this will move you to Login page if you try to move other page without login by directly typing page name on address bar.

    <authentication mode="Forms">
      <forms loginUrl="Login.aspx">
        <credentials passwordFormat="Clear">
          <user name="user1" password="user1@123"/>
          <user name="user2" password="user2@123"/>
        </credentials>
      </forms>
    </authentication>
   <authorization>    
      <deny users="?"/>
    </authorization>

Note : In actual we don't save username and password in web.config file we acheive this using database.

Forms authentication classes are present in System.Web.Security namespace.You have to import this namespace.
FormAuthentication class has static method named Authenticate, this is is used to authenticate the supplied credentials.This method return true if user is authenticated and return false if user is not valid.



protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text))
            {            
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
            }
            else
            {
                lblError.Text = "Invalid Username or Password";
                lblError.ForeColor = System.Drawing.Color.Red;
            }
        }


FormsAuthentication.Authenticate method return true if provided username and password match with saved credentials in web.config file otherwise return false.

FormsAuthentication.RedirectFromLoginPage Method redirect you on your default page after login and this default page must be set inn web.config file as follows.

<forms loginUrl="Login.aspx" defaultUrl="welcome.aspx">

There are following problems with this application.
1. It is not good practice to store username and passwords in web.config file.
2. If will click register now link without login you will again return to login page because anonymous user denied for all pages.



Solution of this problem is to add one more config file in Registration folder and provide access to anonymous user on this folder.
 <system.web>
      <authorization>
        <allow users="*"/>      
      </authorization>
 </system.web>



Wednesday, 22 July 2015

Authentication in Asp.Net - Windows Authentication

This post is continuation of post Authentication in Asp.Net. Please visit following link before reading this post.
Authentication in Asp.Net - Anonymous Authentication

With the using of windows authentication, identifies and authorizes users based on the server's user list.
Access to resources on the server is then granted or denied based on the use account's privileges.

Windows authentication is best suited for Intranet web application.

The advantage of windows authentication is that, the web application can use the exact same security scheme that applies to your corporate network.
User names,passwords, and permissions are the same for network resources and web applications.

IF both, anonymous and windows authentication are enabled in IIS, and , if we don't have a deny entry for anonymous users in web.config file, then the resources on the web server are accessed using anonymous authentication.



Anonymous authentication can be disabled in IIS and Web.config file.

<authorization>
 <deny users="?"/>
</authorization>

? indicates anonymous users
* indicates all users

If you want to have the application code execute using the logged in user identity, then enable impersonation.

If Impersonation is enabled, the application executes using the permission found in your user account. So, if the logged in user has access to a specific network resource, only then he be able to access that resource through the application.

Allowing and denying access to specific users:

    <authorization>
      <allow users="Logicsmaze_PC\User1, Logicsmaze_PC\User2"/>
      <deny users="*"/>
    </authorization>

User1 and User2 are the users of Logicsmaze_PC, above setting will only allow user1 and user2 to access the site. None other user can access the server resources.

Using windows roles to control access :

Instead of providing access to each user we can provide access on behalf of roles.So all the users having allowed role can access the server resources.

<authorization>
      <allow roles="Administrators"/>
      <deny users="*"/>
</authorization>

Related Post :
Other authentication mode in Asp.net is Forms Authentication.Please visit following link for Forms Authentication.
http://logicsmaze.blogspot.in/2015/07/authentication-in-aspnet-forms.html

Tuesday, 21 July 2015

Authentication in Asp.Net - Anonymous Authentication


Most of the public websites does not ask user to enter any username and password.But still, we will
be able to access the content of these websites.

Asp.Net web applications provide anonymous access to resources on the server.

Anonymous Authentication allows users to access the public areas of the web sites, without prompting
the users for username and password.



In IIS 6.0
IUSR_ComputerName is used for providing anonymous access.

In IIS 7.0
IUSR account is used for providing anonymous access.

By default anonymous authentication is enabled in IIS.

If we disable anonymous authentication, we can not access the site.

Impersonation :
we can enable impersonation using following line in web.config.
<identity impersonate="true"/>

When the application uses anonymous authentication and

  1. If Impersonation is disabled, then, the Applicationpoolidentity is used to execute application code.
  2. If Impersonation id enabled, then, "NT Authority\IUSR" account is used to execute the application code.
IF there are 2 or more websites hosted on a machine, with IUSR as the anonymous account, then they can access each other's content.If we want to isolate, each application content, the application can be deployed to different application pools and NTFS file permission can be set for the respective application pool identity.

Related Post :
Other authentication mode in Asp.net is Windows authentication and Forms authentication.Please visit following link .
http://logicsmaze.blogspot.in/Windows_Authentication
http://logicsmaze.blogspot.in/Forms_Authentication