IIS

HttpModule and HttpHandlers


Many times we want to implement pre-processing logic before a request hits the IIS resources

ASP.NET provides two ways of injecting logic in the request pipeline HttpHandlers and HttpModules.


HttpModule(The Event Based Preprocessor)



The Overall Picture of Handler and Modules

Steps to Implement HttpHandlers


Step 1

HttpHandlers are nothing but classes which have pre-processing logic implemented. So the first thing is to create a class project and reference System.Web namespace and implement the IHttpHandler interface as shown in the below code snippet. IHttpHandler interface has two methods which needs to be implemented; one is theProcessRequest and the other is the IsResuable. In the ProcessRequest method, we are just entering the URL into the file and displaying the same into the browser. We have manipulated the context response object to send the display to the browser.
using System;
using System.Web;
using System.IO;
namespace MyPipeLine
{
public class clsMyHandler : IHttpHandler
{
public void ProcessRequest(System.Web.HttpContext context)
{
context.Response.Write("The page request is " + context.Request.RawUrl.ToString());
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Page requested at " + DateTime.Now.ToString() + 
   context.Request.RawUrl); sw.Close();
}
public bool IsReusable
{
get
{
return true;
}
}
}

Step 2

In step 2, we need to make an entry of HttpHandlers tag. In the tag, we need to specify which kind of extension requested will invoke our class.
<system.web>
<httpHandlers>
<add verb="*" path="*.Shiv,*.Koirala" type="MyPipeLine.clsMyHandler, MyPipeLine"/>
</httpHandlers>
</system.web>
Once done, request for page name with extension ‘Shiv’ and you should see a display as shown below. So what has happened is when the IIS sees that request is for a ‘.shiv’ page extension, it just calls the clsMyHandler class pre-processing logic.

Steps to Implement HttpModule

Step 1

As discussed previously, HttpModule is an event pre-processor. So the first thing is to implement the IHttpModuleand register the necessary events which this module should subscribe. For instance, we have registered in this sample for BeginRequest and EndRequest events. In those events, we have just written an entry on to the log file.
public class clsMyModule : IHttpModule
{
public clsMyModule()
{}
public void Init(HttpApplication objApplication)
{
// Register event handler of the pipe line
objApplication.BeginRequest += new EventHandler(this.context_BeginRequest);
objApplication.EndRequest += new EventHandler(this.context_EndRequest);
}
public void Dispose()
{
}
public void context_EndRequest(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("End Request called at " + DateTime.Now.ToString()); sw.Close();
}
public void context_BeginRequest(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Begin request called at " + DateTime.Now.ToString()); sw.Close();
}
}

Step 2

We need to enter those module entries into the HttpModule tag as shown in the below code snippet:
<httpModules>
<add name="clsMyModule" type="MyPipeLine.clsMyModule, MyPipeLine"/>
</httpModules>

The Final Output

If you run the code, you should see something like this in the RequestLog.txt. The above example is not so practical. But it will help us understand the fundamentals.
Begin request called at 11/12/2008 6:32:00 PM
End Request called at 11/12/2008 6:32:00 PM
Begin request called at 11/12/2008 6:32:03 PM
End Request called at 11/12/2008 6:32:03 PM
Begin request called at 11/12/2008 6:32:06 PM
End Request called at 11/12/2008 6:32:06 PM
Begin request called at 11/12/2008 8:36:04 PM
End Request called at 11/12/2008 8:36:04 PM
Begin request called at 11/12/2008 8:37:06 PM
End Request called at 11/12/2008 8:37:06 PM
Begin request called at 11/12/2008 8:37:09 PM
End Request called at 11/12/2008 8:37:09 PM
Begin request called at 11/12/2008 8:37:38 PM
Page requested at 11/12/2008 8:37:38 PM/WebSiteHandlerDemo/Articles.shiv
End Request called at 11/12/2008 8:37:38 PM

Architecture

                            Design Patterns

1) Creational Patterns
         • Abstract Factory:- Creates an instance of several families of classes
         • Builder: - Separates object construction from its representation
         • Factory Method:- Creates an instance of several derived classes
         • Prototype:- A fully initialized instance to be copied or cloned
         • Singleton:- A class in which only a single instance can exist

2) Structural Patterns
         • Adapter:-Match interfaces of different classes.
         • Bridge:-Separates an object’s interface from its implementation.
         • Composite:-A tree structure of simple and composite objects.
         • Decorator:-Add responsibilities to objects dynamically.
         • Façade:-A single class that represents an entire subsystem.
         • Flyweight:-A fine-grained instance used for efficient sharing.
         • Proxy:-An object representing another object.

3) Behavioral Patterns
        • Mediator:-Defines simplified communication between classes.
        • Memento:-Capture and restore an object's internal state.
        • Interpreter:- A way to include language elements in a program.
        • Iterator:-Sequentially access the elements of a collection.
        • Chain of Resp: - A way of passing a request between a chain of objects.
        • Command:-Encapsulate a command request as an object.
        • State:-Alter an object's behavior when its state changes.
        • Strategy:-Encapsulates an algorithm inside a class.


      Factory Vs Abstract Factory

       Factory method uses inheritance to decide which object has to be instantiated
       Abstract factory uses delegation to decide instantiation of an object

      We can say Abstract factory uses factory method to complete the architecture. Abstract Factory is        one level higher in abstraction over Factory.

      1) Factory Patterns

             
                                      

    • The actual product section i.e.“Product” Class inherits from an abstract class  “Abstract Product”.
    • The creational aspect section i.e. “Concrete Creator” class which inherits from class "Creator”.

      Some rules the client will have to follow who will need the “Product” object?
  1. He will never refer directly to the actual “Product” object but can refer the“Product” object using “Abstract Product” class.
  2. He will never use “New” keyword to create the “Product” object but will use the “Creator” class that in turn will use the “Concrete Creator” class to create the actual “Product” object.  

        Benefits from this architecture
         All creational and initializing aspects are now detached from the actual client. As your creational aspect is now been handled in “Concrete Creator” and the client has reference to only “Creator”, so any implementation change in “Create Product” will not affect the client code. In short, now your creational aspect of object is completely encapsulated from the client’s logic.


  2) FAÇADE pattern
      
     Façade pattern sits on the top of lot of subsystems and makes access easy to interfaces of these
     subsystems. Basic purpose of Façade is to make interfacing between many modules and classes
     manageable.


     Above is a simple live application of a Façade class. In this, we have four subsystems:-
            • Customer
            • Product
            • Payment
            • Invoicing
     All the four modules when built at initial stage where built completely independent. The main
     interaction between all these subsystems is customer-placing order. This functionality can be
     attained by using all these subsystems, which involves complex interaction between them.
     That is where FAÇADE comes in to action. We have built a FAÇADE called as

    “FACADEORDER” which sits on the top of all these subsystem and fulfill our functionality.


3) Singleton pattern
  Singleton pattern ensures that a class has only one instance and provides a global point of access to it.
Following are the three steps needed to implement singleton pattern in .NET:-
     • First, create your class with static(Shared in vb.net) members.
          Public class ClsStaticClass
                  Private static clsCustomer objCustomer 
          End class
               This ensures that there is actually only one Customer object throughout the project.
     • Second, define a private constructor to your class.
            Note: - defining a private constructor to class does not allow a client to create objects directly.
     • Finally provide a static method to get access to your singleton object.

4) Prototype pattern
     Twist: - How to implement cloning in .NET? What is shallow copy and deep copy?
Cloning is achieved by using ICloneable of the System namespace. It has a “Clone” method, which actually returns the reference of the same copy. Clone method allows a Shallow copy and not a deep copy. In Shallow copy if you make changes to the cloned object it actually, changes on
the main object itself. 
So how is deep copy achieved, by using “ISerializable” interface? So what you do is first serialize the object then deserialize back to a complete new copy. Now any changes to this new copy do not reflect on the original copy of the object, this is called as Deep copy.

_______________________________________________________________________
What is three-tier architecture?
  The three-tier software architecture emerged in the 1990s to overcome the limitations of the twotier
  architecture.
  There are three layers when we talk about three-tier architecture:-

User Interface (Client/Application Layer):-
   This is mostly the windows user interface or the Web interface but this has only the UI part.
Mid layer(Business Layer): -
    Middle tier provides process management where business logic and rules are executed and can accommodate hundreds of users (as compared to only 100 users with the two tier architecture) by providing functions such as queuing, application execution, and database staging.
Data Access Layer: - 
      This is also termed by the famous acronym "DAL



What are the situations you will use a Web Service and Remoting in projects?

“Web services” uses “remoting” concepts internally. However, the major difference between
“web service” and “remoting” is that “web service” can be consumed by clients who are not
.NET platform. While remoting you need the client to be .NET compliant. Regarding the speed
issue “Remoting” is faster than “Web Services”. So when you are choosing between “Web
services” and “Remoting” keep the cross platform issue and the speed issue in mind.












SQL

enter image description here

OOPS

What is Encapsulation?
What is Abstraction?
What is the functionality of Encapsulation and Abstraction in C#?

Encapsulation and abstraction is essential part of C sharp programming that is mostly used for hide complex code from unauthorized user and shows only relevant information.

What is encapsulation?

Encapsulation is the process of hiding irrelevant data from the user. To understand encapsulation, consider an example of mobile phone. Whenever you buy a mobile, you don’t see how circuit board works. You are also not interested to know how digital signal converts into analog signal and vice versa. These are the irrelevant information for the mobile user, that’s why it is encapsulated inside a cabinet.
In C# programming, we will do same thing. We will create a cabinet and keep all the irrelevant information in it that will be unavailable for the user.

What is abstraction?

Abstraction is just opposite of Encapsulation. Abstraction is mechanism to show only relevant data to the user. Consider the same mobile example again. Whenever you buy a mobile phone, you see their different types of functionalities as camera, mp3 player, calling function, recording function, multimedia etc. It is abstraction, because you are seeing only relevant information instead of their internal engineering.
Understanding-concepts

What is Polymorphism?


Polymorphism means one name many forms. Polymorphism means one object behaving as multiple forms. 

Ex:  Person behaves as a SON in house, at the same time  behaves like an EMPLOYEE in the office.

Overloading
namespace MethodOverloadingByManishAgrahari
{
    class Program
    {
        public class TestOverloading
        {
            public void Add(string a1, string a2)
            {
                Console.WriteLine("Adding Two String :" + a1 + a2);
            }

            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Two Integer :" +  a1 + a2);
            }
        }

        static void Main(string[] args)
        {
            TestOverloading obj = new TestOverloading();
            obj.Add("Manish " , "Agrahari");
            obj.Add(5, 10);
        }
    }
}

Overriding
By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding or Dynamic binding.
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {
            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
public class Derived : Base
} { public override void Show() { Console.WriteLine("Show From Derived Class."); } } static void Main(string[] args) { Base objBase; objBase = new Base(); objBase.Show();// Output ----> Show From Base Class. objBase = new Derived(); objBase.Show();//Output--> Show From Derived Class. } } }

Virtual Keyword

“The virtual keyword is used to modify/override a  base class method in a derived class.”
Method Overriding Vs Method Hiding
Method overriding allows a subclass to provide a specific implementation of a method that is already provided by base class. The implementation in the subclass overrides (replaces) the implementation in the base class.

Method hiding does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {
            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }
        public class Derived : Base
        {
            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

        }
    }
}

Sealed Keyword

Sealed keyword can be used to stop method overriding in a derived classes.

namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {
            public virtual void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }
        public class Derived : Base
        {
            public override sealed void Show()
            {
                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---> This is Derived Class.
            Console.ReadLine();
        }
    }
}
Output ---> This is Derived Class.





Yield keyword

Yield keyword helps us to do custom stateful iteration over .NET collections.”
There are two scenarios where “yield” keyword is useful:-
  • Customized iteration through a collection without creating a temporary collection.
  •  Stateful iteration(ex: Runing total)
  • Scenario 1:- Customized iteration through a collection
    Let’s try to understand what customized iteration means with an example. Consider the below code.
    Let say we have a simple list called as “MyList” which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is browsed/iterated from console application from within static void main method.
    For now let’s visualize the “main()” method as a caller. So the caller i.e. “main()” method calls the list and displays the items inside it. Simple…till now Wink | <img src= ".
    static List<int> MyList = new List<int>();
    
    static void FillValues()
    {
                MyList.Add(1);
                MyList.Add(2);
                MyList.Add(3);
                MyList.Add(4);
                MyList.Add(5);
    }
    static void Main(string[] args) // Caller
    {
                FillValues(); // Fills the list with 5 values
                foreach (int i in MyList) // Browses through the list
                {
                    Console.WriteLine(i);
                }
                Console.ReadLine();
    }
Now let me complicate this situation let’s say the caller only wants values greater than “3” from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.
static IEnumerable<int> FilterWithoutYield()

{
            List<int> temp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
} 
Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where “yield” keyword comes to help. Below is a simple code how we have used yield.
“Yield” keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words “yield” keyword moves control of the program to and fro between caller and the collection.
static IEnumerable<int> FilterWithYield()

{
            foreach (int i in MyList)
            {
                if (i > 3) yield return i;
            }
}  
So for the above code following are details steps how the control will flow between caller and collection. You can also see the pictorial representation in the next diagram shown below.
  • Step 1:- Caller calls the function to iterate for number’s greater than 3.
  • Step 2:- Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.
  • Step 3:- Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.

What is Delegate?

  • Delegate holds pointer to a function or method.
  • The function will then can be called via the delegate object.
  • Delegate is defined with a specific signature (return type, parameter type). 
  • To make a delegate point towards a function we must satisfy the below rule: The function’s signature (which is to be pointed to by a delegate) must be the same as  delegate’s signature.
























MultiCastingDeligate

 "Invoking multiple methods in a single line"
 To do multicasting we have to assign multiple methods with the same signature to a single delegate. 
























General Questions
Does C# support multiple-inheritance? No.
Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class).
Are private class-level variables inherited? Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.
Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class.
What’s the top .NET class that everything is derived from? System.Object.
What does the term immutable mean?The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
What’s the difference between System.String and System.Text.StringBuilder classes?System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
What’s the advantage of using System.Text.StringBuilder over System.String?StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
Can you store multiple data types in System.Array?No.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
How can you sort the elements of the array in descending order?By calling Sort() and then Reverse() methods.
What’s the .NET collection class that allows an element to be accessed using a unique key?HashTable.
What class is underneath the SortedList class?A sorted HashTable.
Will the finally block get executed if an exception has not occurred?­Yes.
What’s the C# syntax to catch any possible exception?A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
Can multiple catch blocks be executed for a single try statement?No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
Explain the three services model commonly know as a three-tier application.Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
Class Questions
What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class.Example: class MyNewClass : MyBaseClass
Can you prevent your class from being inherited by another class? Yes. The keyword “sealed” will prevent the class from being inherited.
Can you allow a class to be inherited, but prevent the method from being over-ridden?Yes. Just leave the class public and make the method sealed.
What’s an abstract class?A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.
When do you absolutely have to declare a class as abstract?1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract.
What is an interface class?Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
Why can’t you specify the accessibility modifier for methods inside the interface?They all must be public, and are therefore public by default.
Can you inherit multiple interfaces?Yes. .NET does support multiple interfaces.
What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay. To Do: Investigate
What’s the difference between an interface and abstract class?In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
What is the difference between a Struct and a Class?Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.
Method and Property Questions
What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. The data type of the value parameter is defined by whatever data type the property is declared as.
What does the keyword “virtual” declare for a method or property? The method or property can be overridden.
How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
Can you declare an override method to be static if the original method is not static? No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters.
If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
Events and Delegates
What’s a delegate?
A delegate object encapsulates a reference to a method.
What’s a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.
ADO.NET and Database Questions
What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.
What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
Explain ACID rule of thumb for transactions.A transaction must be:1. Atomic - it is one unit of work and does not dependent on previous and following transactions.2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.3. Isolated - no transaction sees the intermediate results of the current transaction).4. Durable - the values persist if the data had been committed even if the system crashes right after.
What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
What does the Initial Catalog parameter define in the connection string? The database name to connect to.
What does the Dispose method do with the connection object? Deletes it from the memory.To Do: answer better. The current answer is not entirely correct.
What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.
Assembly Questions
How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
What is a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
What namespaces are necessary to create a localized application? System.Globalization and System.Resources.
What is the smallest unit of execution in .NET?an Assembly.
When should you call the garbage collector in .NET?As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.
How do you convert a value-type to a reference-type?Use Boxing.
What happens in memory when you Box and Unbox a value-type?Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.