Wednesday, 4 November 2015

Difference between Bindings :

BasicHttpBinding  : 


  • By default security level is none.
  • Also support one extra security mode "TransportCredentialOnly" that is not supported by wshttp,tcp,msmq.
  • we can't use protection level(sign&encrypt,sign,none) if doesn't change security level from none to other.
  • duplex message exchange mode is not supported.
  • does not support session, if we change Instance context mode from percall to per session it will also work as per call. 
  • we can't use required session mode with this binding(allowed,not allowed, required)
  • similar as a asmx service.
  • client with older version of .net can use this.(before 3.0)
  • use SOAP 1.1 specification
  • support http protocol
  • support transfermode (streamed,buffered)


WSHttpBinding :


  • By default security level is Message(means ws-security specification is used to secure the message, provide end to end security)
  • Both client and service should support ws-specification so less interoperability.
  • Duplex message exchange mode is not supported by WSHttp binding instead use WsDualHttpBinding.otherwise get error WShttpBinding doesn't support Duplex.
  • Support all instance context mode
  • We can't use not-allowed session mode with this binding(allowed,not allowed, required)
  • Use SOAP1.2 specification.
  • Support http protocol
  • Does not have transfer mode



NetTcp Binding:

  • Default security mode is transport.(ssl of tls is used to encrypt message.point to point security, mediator can read message)
  • Duplex message exchange mode is supported.
  • Support all instance context mode.
  • We can't use not-allowed session mode with this binding(allowed,not allowed, required)
  • Support TCP protocol so used within same network.
  • Support transfer mode.


MSMQ :

  • Does not support percall message exchange pattern.
  • Default transport level security.
  • Doesn't support mixed(Transport with message credential) security mode.
  • Only binding that support both security mode.


MSMQ allow us to create a program that can reliably send or receive messages over a wire without any loss of message.it uses a queue to store messages in the order in which they arrive.msmq is implemented in the manner that there are multiple clients sending a request to server but because of overload, server is busy processing  previous client requests so in such cases MSMQ can be implemented to maintain a queue of reequests,whenever the server become free it will take requests from queue and process them one by one.

Step1 : Install MSMQ component from windows features on or off
Step2 : Check queue from Administrative tool  -->  Computer management  -->  Service and applications  --> messagequeuing

Step3 :Create queue on host application programatically
string muqueue="D:\\RahulQ";
if(!MessageQueue.Exist(myqueue))
{
MessageQueue.Create(muqueue,false); false means non transaction queue.
}

host.Open();


Step4: App.config changes

<bindings>
 <binding name="msmq" exactlyOnce="false">
 <security mode="none"/> // for remote address of queue

<endpoint binding="netMsmqBinding">


Make multiple calls from client and close host console.
check queue , u will get messages there .
run host console, message will be served and remove from queue.

Named Pipe :
Only support transport security level.
Used if service and clients are on same machine.

Friday, 14 August 2015

Partial in C# - Partial class and Partial methods

It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

Creating partial class :


  • All the part of class spread across different files must use the partial keyword.
  • All part of class must have same access modifiers.
  • If any of the part is declared abstract, then entire type is considered abstract.
  • If any of the part is declared sealed, then entire type is considered sealed.
  • If any of part inherit a class , then entire type inherit that class.
  • Different part of partial class can't specify different base class.
  • Different part of partial class can specify different base interface.
  • Any member declared in a partial definition are available to all the other parts of the partial class.

Partial Method :


  • A partial  class and structure can contain partial method.
  • Implementation of partial method is optional, If we compile it without body, it will compile.actually compiler ignore partial method declaration and its call until it's body is defined.
  • Partial method is private by default.partial method can't have any modifier like access modifiers, static, abstract, virtual etc.
  • Without declaration of partial method you can't provide definition for partial method, it will give compile time error.
  • A partial method return type is must be void, including any other return type is a compile time error.
  • signature of declaration and definition of partial method must be same.
  • Partial method can be implemented only once otherwise compile time error.


class Program
    {
        public static void Main()
        {

            test obj ;
            obj.hello();

            Console.Read();          

        }
    }  
    public partial struct test
    {
        partial void partialMethod();
        public void hello()
        {
            partialMethod();
        }
    }
    public partial struct test
    {
        partial void partialMethod()
        {
            Console.WriteLine("Hello");
        }      
    }

Wednesday, 12 August 2015

Invoke method dynamicly in C# - Late Binding using Reflection

Late binding is associating a method with an object at runtime.At compile time compiler does not know about this association.

Reflection is one of the way to achieve late binding.

In following example we will inspect the assembly, create object of class at runtime, find method of this class using reflection and call this method using created object.

namespace TypeCastingRND
{  
    public class Program
    {
        public static void Main()
        {
             // Get current Assembly
            Assembly executedAssembly = Assembly.GetExecutingAssembly();          
            Type studentType = executedAssembly.GetType("TypeCastingRND.Student");

           // Create instance of Student class
           object studentInstance = Activator.CreateInstance(studentType);

            // Get method using reflection
            MethodInfo methodName = studentType.GetMethod("StudentFullName");

            //Create parameter array
            string[] parameters = new string[2];
            parameters[0] = "Rahul";
            parameters[1] = "Saini";

            //Invoke method and get return 
            string StudentName=(string)methodName.Invoke(studentInstance, parameters);
            Console.WriteLine("Student Name : " + StudentName);

            Console.Read();
        }
    }

    public class Student
    {
        public string studenFirstName { get; set; }
        public string studenLastName { get; set; }
        public Student()
        {
       
        }
        public string StudentFullName(string FirstName,string LastName)
        {
            return FirstName + " " + LastName;
        }
    }  
}

Output :
Student  : Rahul Saini

Reflection in C#

Reflection is the way of inspecting an assemblies's metadata at runtime. it is used to find all types in an assembly and dynamically invoke methods of an assembly.With the help of reflection you can find what classes, methods, propertied, constructors etc. assembly contains.You can also know what any method is expecting and what will method return and many more.

Uses of reflection :
  • When you drag and drop a button on a win form or an asp.net application.the property window uses reflection to show all the properties of the button class so reflection is used by IDE or UI designers .
  • When you use ILDASM command to inspect a assembly, internally it's also using reflection..
  • Late binding can be achieved by reflection can use reflection to dynamically create an instance of a type, about which we don't have any information at compile time. so reflection enables you to use code that is not available at compile time.
  • Suppose you have two alternate implementation of an interface. you want to allow user to pick one or the other using a config file. with reflection, you can simply read the name of the class whose implementation you want to use from config file, and instantiate an instance of that class. this is another example of late binding using reflection.
Following is the example of reflection :


using System.Reflection;

namespace Logicsmaze
{
     public class Student
    {
        public string studenName { get; set; }
        public int rollno { get; set; }
        public int parentsIncome { get; set; }

        public Student()
        {
       
        }

        public Student(int rollNo,string name,int Income)
        {
            this.rollno = rollNo;
            this.studenName = name;
            this.parentsIncome = Income;
        }

        public static void Scholarship(List<Student>lstStudent)
        {
           
        }
    }

    class Program
    {
        public static void Main()
        {
            //Type t = Type.GetType("Logicsmaze.Student");  or
            Type t = typeof(Student);

            Console.WriteLine("...............Class Detail..........");
            Console.WriteLine(t.Name);
            Console.WriteLine(t.FullName);
            Console.WriteLine(t.Namespace);

            Console.WriteLine();
            Console.WriteLine("...........Properties in Student class........");
            PropertyInfo[] properties = t.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                Console.WriteLine(property.Name + " is type of: " + property.PropertyType.Name);
            }
            Console.WriteLine();
            Console.WriteLine("...........Methods in Student class........");
           MethodInfo[] methods = t.GetMethods();
           foreach (MethodInfo method in methods)
           {
               Console.WriteLine(method.Name + " has return type : "+method.ReturnType.Name);
           }

           Console.WriteLine();
           Console.WriteLine("...........Constructors in Student class........");
           ConstructorInfo[] constroctors = t.GetConstructors();
           foreach (ConstructorInfo constructor in constroctors)
           {
               Console.WriteLine(constructor.ToString());
           }

            Console.Read();
        }
    }    
}

Output : 


Wednesday, 5 August 2015

Which one will be Called!!! - Calling Overloaded Functions with Float, Decimal, Double and int

class Program
    {
        static void Main(string[] args)
        {
            double dbl = 10;
            float flt = 10;
            decimal dml = 10;


            FunctionWithOverload(10);               // Function with int called
            FunctionWithOverload(10f);              // Function with float called
            FunctionWithOverload(10.56);            // Function with double called
            FunctionWithOverload(.25);              // Function with double called
            FunctionWithOverload(flt);              // Function with float called
            FunctionWithOverload(dbl);              // Function with double called
            FunctionWithOverload(dml);              // Function with decimal called
            FunctionWithOverload(10.25f);           // Function with float called
            FunctionWithOverload(10.253m);          // Function with decimal called
            FunctionWithOverload(10.2534585685m);       // Function with decimal called
            FunctionWithOverload(10.2535698455);        // Function with double called
            FunctionWithOverload(10.2535698f);          // Function with float called

            Console.ReadLine();
        }
        public static void FunctionWithOverload(object var_obj)
        {
            Console.WriteLine("Function with Object called :" + var_obj);
        }
        public static void FunctionWithOverload(float var_float)
        {
            Console.WriteLine("Function with float called :" + var_float);
        }
        public static void FunctionWithOverload(decimal var_dcl)
        {
            Console.WriteLine("Function with decimal called :" + var_dcl);
        }
        public static void FunctionWithOverload(double var_dbl)
        {
            Console.WriteLine("Function with double called :" + var_dbl);
        }
        public static void FunctionWithOverload(int var_int)
        {
            Console.WriteLine("Function with int called :" + var_int);
        }
    }

Output : 

Tuesday, 4 August 2015

Examples of Implicit and Explicit Casting of datatypes in C#


Case 1 : 
Suppose you have a class, class having some properties/data members.
When you instantiate this class, all the data members of this class will be initialized with it's default values or by null.

  • If data member of class is value type, it will be initialize by its default value like int variable initialize with zero, float with 0.0, bool with false etc.
  • If data member of class is reference type, it will be null like string variable, array, object of other class will also be null.
Please refer following example :

 public class Class1
    {
        public int var_int;
        public string var_string;
        public float var_float;
        public bool var_bool;
        public string[] var_str_arr;
        public int[] var_int_arr;
        public Class2 var_class2;
    }
    public class Class2
    {
        public int var_int;
        public string var_string;
        public float var_float;
    }

  class Program
    {
        static void Main(string[] args)
        {            
            Class1 objclass1 = new Class1();   

            Console.WriteLine(objclass1.var_int);        // Output will be 0              
            Console.WriteLine(objclass1.var_float);      // Output will be 0.0
            Console.WriteLine(objclass1.var_bool); // Output will be false
           Console.WriteLine(objclass1.var_string);    // var_string will be null
            Console.WriteLine(objclass1.var_str_arr); // var_str_arr will be null
            Console.WriteLine(objclass1.var_int_arr); // var_int_arr will be null
            Console.WriteLine(objclass1.var_class2); // var_class2 will be null
            
            Console.ReadLine();
        }
    }
   

Case 2 : Casting of variables

class Program
    {
        static void Main(string[] args)
        {
            int i;
            float flt;
            double dbl;
            decimal deci;

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to int...........");
            //i = flt;                              //Error : can not implicitly convert type float to int
            i = (int)flt;                          //Explicit casting
            Console.WriteLine(i);
            //i = dbl;                            //Error : can not implicitly convert type double to int
            i = (int)dbl;                         //Explicit casting
            Console.WriteLine(i);
            //i = deci;                           //Error : can not implicitly convert type decimal to int
            i = (int)deci;                        //Explicit casting
            Console.WriteLine(i);

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to float...........");
            flt = i;
            Console.WriteLine(flt);
            //flt = dbl;                        //Error : can not implicitly convert type double to float
            flt = (float)dbl;
            Console.WriteLine(flt);
            //flt = deci;                      //Error : can not implicitly convert type decimal to float
            flt = (float)deci;
            Console.WriteLine(flt);

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to double...........");
            dbl = i;
            Console.WriteLine(dbl);
            dbl = flt;                     
            Console.WriteLine(dbl);            
            //dbl = deci;                       //Error : can not implicitly convert type decimal to double
            dbl = (double)deci;
            Console.WriteLine(dbl);

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to decimal...........");
            deci = i;
            Console.WriteLine(deci);
            //deci = flt;                                 //Error : can not implicitly convert type float to decimal
            deci = (decimal)flt;
            Console.WriteLine(deci);
            //deci = dbl;                             //Error : can not implicitly convert type double to decimal
            deci = (decimal)dbl;
            Console.WriteLine(deci);
                                  
            Console.ReadLine();

        }

Output : 

Case 3 :  Calling of function by changing it's argument type also depends on implicit conversion of data types.


class Program
    {
        static void Main(string[] args)
        {
            int i;
            float flt;
            double dbl;
            decimal deci;

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            //******Passing expected argument******
            CheckIntFloatDecimalDouble(i, flt, deci, dbl);          // Work Fine

            //******Changing first(integer) argument******
            //CheckIntFloatDecimalDouble(flt, flt, deci, dbl);      // Error : has some invalid argument

            //******Changing second(float) argument******
            //CheckIntFloatDecimalDouble(i, dbl, deci, dbl);        // Error : has some invalid argument
            CheckIntFloatDecimalDouble(i, i, deci, dbl);            // Work Fine

            //******Changing third(decimal) argument******
            //CheckIntFloatDecimalDouble(i, flt, flt, dbl);         // Error : has some invalid argument
            //CheckIntFloatDecimalDouble(i, flt, dbl, dbl);         // Error : has some invalid argument

            //******Changing fourth(double) argument******
            CheckIntFloatDecimalDouble(i, flt, deci, flt);          // Work Fine
            //CheckIntFloatDecimalDouble(i, flt, deci, deci);       // Error : has some invalid argument
        
            Console.ReadLine();
        }
        public static void CheckIntFloatDecimalDouble(int int_var, float float_var, decimal deci_var, double dbl_var)
        {
            Console.WriteLine(int_var);
            Console.WriteLine(float_var);
            Console.WriteLine(deci_var);
            Console.WriteLine(dbl_var);
        }
    }


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






Wednesday, 17 June 2015

WCF security

While we talk about security following terms play important role.

Authentication : Process of validating/identifying the sender and recipient of the message.

Authorization : Process of determining the rights of authenticated user.

Confidentiality : Process of ensuring that only the intended recipient of the message can view the message.this can be achieved by encrypting the message.

Integrity : Ensuring that the message is not tampered by a malicious user as it is being transmitted from sender to receiver.we can achieve this by signing the message.

By default all the bindings provide above security features except basicHttpBinding.

Following security modes can be used with WCF service.

Transport Security : Securing the transport channel is called transport security. each of the protocol (Http,TCP, MSMQ etc.) have their own way of providing transport security.

For example, TCP provides transport security, by implementing TLS (Transport Layer Security). The TLS implementation is provided by the operating system.

HTTP provides transport security by using SSL(Secure Socket Layer) over http. 

Transport security provides only point-to-point channel security.it means if there is an intermediary (Load balancer, proxy etc.) between, then the intermediary has direct access to content of message.

Message Security : Securing the message itself by encapsulating the security credential with every SOAP message is called message security. as the message itself is protected if provides end to end security.

Mixed transfer security mode : It uses Transport security for message integrity, privacy and service authentication and it uses Message security mode for securing client credential.
One of the disadvantage of the mixed mode is that it will secure only point-to-point as nature of Transport security.

Both security modes: This mode Both transfer security mode uses both Transport security and Message security..

Default security mode in wsHttpBinding is Message Security mode.(encryption and signing of message aromatically attached)
Please refer following table for supported and default security mode of different bindings.

NameNoneTransportMessageMixedBoth
BasicHttpBindingYes(default)YesYesYesNo
NetTcpBindingYesYes(default)YesYesNo
NetNamedPipeBindingYesYes(default)NoNoNo
WsHttpBindingYesYesYes(default)YesNo
WsDualHttpBindingYesNoYes(default)NoNo
NetMsmqHttpBindingYesYesYes(default)NoYes

Following is the SOAP body if security mode is message.Message is both encrypted and signed.

<s:Body u:Id="_0">
<e:EncryptedData Id="_1" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:e="http://www.w3.org/2001/04/xmlenc#">
<e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></e:EncryptionMethod>
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<o:SecurityTokenReference xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<o:Reference ValueType="http://schemas.xmlsoap.org/ws/2005/02/sc/dk" URI="#uuid-3c8a7bb8-acd0-4bbb-8abe-1ea4a214254b-96"></o:Reference>
</o:SecurityTokenReference>
</KeyInfo>
<e:CipherData>
<e:CipherValue>yAMmq3Dv28ukYopUIObISQ3YLRap/o7s77aZPA5UWGcRPmvCxEmDuApNOjPxO+7cMCh7KTYRqovSCg5XFgsnfli6zVhIRXBX76Uh7etSJqyu3M/xs6hTwKXr/W5qIvN0r491vnJnSeiSXkAWpWrJQ/hswZm46tKIVPi9/Uq4hyCnUMQ86Kzg7eP3jxu+6JLj/EPEdjutKNgsL8crv6T2dC9MZBmSo1HgfkTYq/JYBP4=</e:CipherValue>
</e:CipherData>
</e:EncryptedData>
</s:Body>

If we change security mode from default(that is message in wsHttpBinding) to None 

<wsHttpBinding>
        <binding name="wsHttp">          
          <security mode="None"></security>
        </binding>
</wsHttpBinding>

After changing security mode, SOAP body will be as follows.

<s:Body>
<HelloMessageResponse xmlns="http://tempuri.org/">
<HelloMessageResult>HelloRahul!!</HelloMessageResult>
</HelloMessageResponse>
</s:Body>

We can customize the level of protection using ProtectionLevel attribute .











None : No protection.Message is not encrypted and not signed.
Sign : No encryption but is digitally signed to ensure the integrity of message.
EncryptAndSign : Message is encrypted and then signed to ensure confidentiality and integrity of message. 

Following 6 attributes has the ProtectionLevel named parameter.They are specified in the order of precedence.

[ServiceContract]
      [OperationContract]
            [FaultContract]
            [MessageContract]
                  [MessageHeader]
                  [MessageBodyMember]


Note : If we use binding that by default does not support security like basicHttpBinding and we use Protection level other than None, at run time we will get error.




Authentication in WCF


Most binding in WCF provide authentication without any additional configuration.

for example, both wsHttpBinding and netTcpBinding provides windows authentication.

we can check this by using following code.

ServiceSecurityContext.Current.Primaryidentity.IsAuthenticated;
ServiceSecurityContext.Current.Primaryidentity.AuthenticationType;
ServiceSecurityContext.Current.Primaryidentity.Name;

We can set the the authentication type by using clientCredentialType attribute within security tag of binding.

















Friday, 12 June 2015

Multiple Concurrency Mode in WCF

This post is continuation of post Concurrency Mode in WCF. Please visit following link before reading this post.
http://logicsmaze.blogspot.in/2015/06/concurrency-mode-in-wcf.html

Multiple Concurrency Mode in WCF :
With multiple concurrency mode an exclusive lock is not acquired by on the service instance. With multiple concurrency modem multiple threads are are allowed to access the service instance simultaneously and we get better  throughput.

Like single concurrency mode, multiple concurrency mode is not influenced by instance context mode and whether the binding supports session or not.

Concurrency mode can be set by using ConcurrencyMode attribute of [ServiceBehaviour]




Instance Context ModeConcurrency ModeIs Binding Support SessionWill Concurrency Call Processed
PerCallMultipleNoYes
PerCallMultipleYesYes
PerSessionMultipleNoYes
PerSessionMultipleYesYes
SingleMultipleNoYes
SingleMultipleYesYes

For detailed description about other concurrency mode please visit following posts.
Single-concurrency-mode-in-wcf
Multiple-concurrency-mode-in-wcf
Reentrant-concurrency-mode-in-wcf

Thanks :-)

Reentrant Concurrency Mode in WCF

This post is continuation of post Concurrency Mode in WCF. Please visit following link before reading this post.
http://logicsmaze.blogspot.in/2015/06/concurrency-mode-in-wcf.html

The Reentrant concurency mode is nothing but a modified version of a single concurrency mode.Similar to single concurrency, reentrant concurrency exclusively lock the service instance so that a concurrent call on the same instance is never called.
But apart from that, Reentrant concurrency mode allows the service to issue callbacks to the client.And this call back can be two way and re-entrant calls can be accepted by service instance.




If we implement call back scenario, set Concurrency mode Single, as we run client we will get error because call back will be two way and service reference will not serve re-entrant call.

If we set Concurrency mode Single and set IsOneWay = true within [OperationContract], in this scenario call back request go to the client but client can't send call back response to service, so everything will work fine.

   [ServiceContract]

    public interface IReportProgressCallback
    {
        [OperationContract(IsOneWay=true)]
        void ReportProgress(int percentage);
    }

If we want to use two way callback than we need to set concurrency mode reentrant.

For detailed description about other concurrency mode please visit following posts.
Single-concurrency-mode-in-wcf
Multiple-concurrency-mode-in-wcf
Reentrant-concurrency-mode-in-wcf

Thanks :-)