Saturday, February 9, 2019

HTTPHanlder and HTTPModule

When a client makes a request for a resource located on the server in an ASP.NET application, each request is handled by the HTTP Handlers. Microsoft ASP.NET has number of built-in HTTP Handlers which serves different files like .ASPX, .ASMX etc. Based on the extension of the file, the appropriate HTTP Handlers gets loaded which is mapped to the extension and is responsible for processing the ASP.NET request.


Custom HttpHandlers
public class CustomHandler:IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Write("<h1 style='Color:#000066'>WelCome To Custom HttpHandler</h1>");
        context.Response.Write("HttpHandler processed on - " + DateTime.Now.ToString());
        using (StreamWriter SW=new StreamWriter(@"E:\HandlerMessages.txt",true))
        {
            SW.WriteLine("The message date time is - " + DateTime.Now.ToString());
            SW.Close();
        }
    }
}

<httpHandlers>
        <add verb="*" path="*.curry" type="CustomHandlerModuleExample.CustomHandler"/>
</httpHandlers>


HttpModule

HttpModule is another part of request processing of ASP.NET. In a single request processing, there can be more than one modules which gets executed. HttpModules take part in processing of the request by handling the Application events. There are number of events which you can handle during the HttpModule processing. For example - BeginRequest(), EndRequest(), AuthenticateRequest() etc.
 IHttpModule interface. This interface provides two method
Init()
Dispose()


public class CustomHttpModule:IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(this.context_BeginRequest);
        context.EndRequest += new EventHandler(this.context_EndRequest);
    }
    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();
    }
    public void Dispose()
    {

    }
}

<httpModules>
      <add name="DotNetCurryModule" type="CustomHttpModule"/>
</httpModules>

SOLID

SOLID Design Principles

Liskov Substitution Principle
Iff S is a Subtype of T, then objects of type T may be replaced with objects of type S. This means, Derived types must be completely substitutable for their base types. It is basically extension of Open Closed Principle.

Implementation guidelines
1. No new exceptions can be thrown by the subtype unless they are part of the existing exception hierarchy.
2. Clients should not know which specific subtype they are calling
3. New derived classes just extend without replacing the functionality of old classes



Solution:

Tuesday, February 5, 2019

c sharp and asp.net interview questions

Q. Object V/S var V/S dynamic
The object class is the base class for all ohter classes; in other words all derived types are inherited from the object base type. We can assign values of any type to the object type variable (value type->obejct=boxing)  (object->value type=unboxing)

 var keyword was introduced in C# 3.0. It is an implicit type and the type is determined by the C# compiler. There is no performance penalty when using var. The C# compiler assigns types to the variable when it assigns the value.

var a = 10; // it is same as int a = 10;
var b = "This is test string";
var c = b; // does not gives compilation error.
var d; //gives compilation error

Use when ->We have a long class name so that our code is not so readable. var makes it short and sweet.
We use LINQ and anonymous types that help us reduce the code (reduce effort to create a new class)


C# 4.0 introduced a new type called "Dynamic". Dynamic is a new static type that is not known until runtime. At compile time, an element with dynamic is assumed to support any operation so that we need not be worried about the object. Errors are caught at runtime only. The type's dynamic status is compiled into a variable type object that is dynamic at compile time, not at run time. At compilation a dynamic is converted into a System.object. It suffers from boxing and unboxing because it is treated as a System.Object and also the application's performance will suffer siince the compiler emits the code for all the type safety.

dynamic i = 10;
dynamic s = "abcd";

Q. Static vs singleton
Ans: Static classes are basically used when you want to store a single instance, data which should be accessed globally throughout your application. The class will be initialized at any time but mostly it is initialized lazily. Lazy initialization means it is initialized at the last possible moment of time. There is a disadvantage of using static classes. You never can change how it behaves after the class is decorated with the static keyword.

Imp->Singleton Class instance can be passed as a parameter to another method whereas static class cannot
->Singleton classes support Interface inheritance whereas a static class cannot implement an interface:
->Static classes also fail during dependency injection.


Q. How to do method overloading in WCF/webservices?

Ans: WSDL does not support the same overloading concepts that are supported by C#. When you are consuming a service over HTTP/SOAP, having the same method name in your contract would mean that there is no way to determine the particular method the client can invoke.
It will throw an error contract mismatch because of the WSDL that does n't allow to create duplicate methods for clients.

[ServiceContract]
public interface IHelloWorld
{
    [OperationContract(Name = "ShowIntData")]
    string ShowData(int value);

    [OperationContract(Name = "ShowStringData")]
    string ShowData(string value);
}

So, now you fetch the overloaded methods with different name

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

Q: Can an abstract class have a constructor? If so what is  the use?
Ans : Yes, an abstract class can have a constructor. In general, a class constructor is used to initialize fields. Along the same lines, an abstract class constructor is used to initialise fields of the abstract class. You would provide a constructor for an abstract class if you want to initialise certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents duplicate code.You cannot create an instance of an abstract class. So, what is the use of a constructor in an abstract class?Though you cannot create an instance of an abstract class, we can create instances of the classes that are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor is automatically called. Note: Abstract classes can't be directly instantiated. The abstract class constructor gets executed thru a derived class. So, it is a good practice to use protected access modifier with abstract class constructor. Using public doesn’t make sense.

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

Q :How to handle exceptions that occur in finally block

Ans: The exception propagates up, and should be handled at a higher level. If the exception is not handled at the higher level, the application crashes. The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute.
1. If the "finally" block is being executed after an exception has occurred in the try block,
2. and if that exception is not handled
3. and if the finally block throws an exception
Then the original exception that occurred in the try block is lost.

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

Q: Throw vs Throw(ex)

Ans: throw(ex) will reset your stack trace so error will appear from the line where throw(ex) written while throw does not reset stack trace and you will get information about original exception.

----------------
Q: Execution order in asp.net

TextBox Init Event
UserControl Init Event
Master Page Init Event
Content Page Init Event
Content Page Load Event
Master Page Load Event
TextBox Load Event
UserControl Load Event
Content Page PreRender Event
Master Page PreRender Event
TextBox PreRender Event
UserControl PreRender Event

So, in general the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one.Please note that the master page is merged into the content page and treated as a control in the content page. Master page is merged into the content page during the initialization stage of page processing.

Singleton Design Pattern

Singleton Design Pattern
1.  Class in sealed (sealed will prevent the class inheritances(even if child child is nested class))
2. Constructor is private (helps in preventing any external instantiations of objects)
3. Double check - inner check so as to create instance. Outer check so as to not check if object is created again and again.
4. Lock so as disallow parallel invoke




Thread Safe version

Monday, February 4, 2019

SQL Transactions

Transactions:

Allowing concurrent transactions is essential for performance but may introduce concurrency issues when two or more transactions are working with the same data at the same time.


If you choose the lowest isolation level (i.e Read Uncommitted), it increases the number of concurrent transactions that can be executed at the same time, but the down side is you have all sorts of concurrency issues. On the other hand if you choose the highest isolation level (i.e Serializable), you will have no concurrency side effects, but the downside is that, this will reduce the number of concurrent transactions that can be executed at the same time if those transactions work with same data.

Dirty Read-> A dirty read happens when one transaction is permitted to read data that has been modified by another transaction that has not yet been committed. In most cases this would not cause a problem. However, if the first transaction is rolled back after the second reads the data, the second transaction has dirty data that does not exist anymore. 

Lost Update -> Lost update problem happens when 2 transactions read and update the same data. E.g. there are 2 transactions - Transaction 1 and Transaction 2. Transaction 1 starts first, and it is processing an order for 1 iPhone. It sees ItemsInStock as 10. 
At this time Transaction 2 is processing another order for 2 iPhones. It also sees ItemsInStock as 10. Transaction 2 makes the sale first and updates ItemsInStock with a value of 8. 
At this point Transaction 1 completes the sale and silently overwrites the update of Transaction 2. As Transaction 1 sold 1 iPhone it has updated ItemsInStock to 9, while it actually should have updated it to 7. 

Phantom read -> happens when one transaction executes a query twice and it gets a different number of rows in the result set each time. This happens when a second transaction inserts a new row that matches the WHERE clause of the query executed by the first transaction.  


Solutions:
1. The repeatable read isolation level uses additional locking on rows that are read by the current transaction, and prevents them from being updated or deleted elsewhere. This solves the lost update problem. 
2. Fixing phantom read concurrency problem : To fix the phantom read problem, set transaction isolation level of Transaction 1 to serializable. This will place a range lock on the rows between 1 and 3, which prevents any other transaction from inserting new rows with in that range. This solves the phantom read problem.  

Difference between repeatable read and serializable
Repeatable read prevents only non-repeatable read. Repeatable read isolation level ensures that the data that one transaction has read, will be prevented from being updated or deleted by any other transaction, but it doe not prevent new rows from being inserted by other transactions resulting in phantom read concurrency problem. 

Serializable prevents both non-repeatable read and phantom read problems.Serializable isolation level ensures that the data that one transaction has read, will be prevented from being updated or deleted by any other transaction. It also prevents new rows from being inserted by other transactions, so this isolation level prevents both non-repeatable read and phantom read problems. 

----------
What is the difference between serializable and snapshot isolation levels
Serializable isolation is implemented by acquiring locks which means the resources are locked for the duration of the current transaction. This isolation level does not have any concurrency side effects but at the cost of significant reduction in concurrency. 

Snapshot isolation doesn't acquire locks, it maintains versioning in Tempdb. Since, snapshot isolation does not lock resources, it can significantly increase the number of concurrent transactions while providing the same level of data consistency as serializable isolation does.

SQL Server Interview Question

Nth Highest salary

1. Select Max(Salary) from Employees where Salary < (Select Max(Salary) from Employees)

2. SELECT TOP 1 SALARY
FROM (
      SELECT DISTINCT TOP N SALARY
      FROM EMPLOYEES
      ORDER BY SALARY DESC
      ) RESULT
ORDER BY SALARY


3. WITH RESULT AS
(
    SELECT SALARY,
           DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
    FROM EMPLOYEES
)
SELECT TOP 1 SALARY
FROM RESULT
WHERE DENSERANK = N


NOTE-the following query can be used to get the nth highest salary. The below query will only work if there are no duplicates.
WITH RESULT AS
(
    SELECT SALARY,
           ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS ROWNUMBER
    FROM EMPLOYEES
)
SELECT SALARY
FROM RESULT

WHERE ROWNUMBER = 3



Delete Duplicate rows in table


WITH EmployeesCTE AS
(
   SELECT *, ROW_NUMBER()OVER(PARTITION BY ID ORDER BY ID) AS RowNumber
   FROM Employees
)

DELETE FROM EmployeesCTE WHERE RowNumber > 1




RANK, DENSE_RANK and ROW_NUMBER

Similarities between RANK, DENSE_RANK and ROW_NUMBER functions
Returns an increasing integer value starting at 1 based on the ordering of rows imposed by the ORDER BY clause (if there are no ties)
ORDER BY clause is required
PARTITION BY clause is optional
When the data is partitioned, the integer value is reset to 1 when the partition changes

SELECT Name, Salary, Gender,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNumber,
RANK() OVER (ORDER BY Salary DESC) AS [Rank],
DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank
FROM Employees




Difference between RANK, DENSE_RANK and ROW_NUMBER functions
ROW_NUMBER : Returns an increasing unique number for each row starting at 1, even if there are duplicates.
RANK : Returns an increasing unique number for each row starting at 1. When there are duplicates, same rank is assigned to all the duplicate rows, but the next row after the duplicate rows will have the rank it would have been assigned if there had been no duplicates. So RANK function skips rankings if there are duplicates.
DENSE_RANK : Returns an increasing unique number for each row starting at 1. When there are duplicates, same rank is assigned to all the duplicate rows but the DENSE_RANK function will not skip any ranks. This means the next row after the duplicate rows will have the next rank in the sequence

Sunday, February 3, 2019

Web API

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

5. ASP.NET Web API Content Negotiation

REST says that the client should have the ability to decide in which format they want the response - XML, JSON etc. A request that is sent to the server includes an Accept header. Using the Accept header the client can specify the format for the response. For example
Accept: application/xml returns XML
Accept: application/json returns JSON

Depending on the Accept header value in the request, the server sends the response. This is called Content Negotiation. 

So what does the Web API do when we request for data in a specific format
The Web API controller generates the data that we want to send to the client. The controller generates the data, and hands the data to the Web API pipeline which then looks at the Accept header and depending on the format that the client has requested, Web API will choose the appropriate formatter. For example, if the client has requested for XML data, Web API uses XML formatter. If the client has requested for JSON data, Web API uses JSON formatter. These formatters are called Media type formatters.

ASP.NET Web API is greatly extensible. This means we can also plugin our own formatters, for custom formatting the data.

If you don't specify the Accept header, by default the Web API returns JSON data.

When the response is being sent to the client in the requested format, notice that the Content-Type header of the response is set to the appropriate value. For example, if the client has requested application/xml, the server send the data in XML format and also sets the Content-Type=application/xml.

The formatters are used by the server for both request and response messages. When the client sends a request to the server, we set the Content-Type header to the appropriate value to let the server know the format of the data that we are sending. For example, if the client is sending JSON data, the Content-Type header is set to application/json. The server knows it is dealing with JSON data, so it uses JSON formatter to convert JSON data to .NET Type. Similarly when a response is being sent from the server to the client, depending on the Accept header value, the appropriate formatter is used to convert .NET type to JSON, XML etc.

It's also very easy to change the serialization settings of these formatters. For example, if you want the JSON data to be properly indented and use camel case instead of pascal case for property names, all you have to do is modify the serialization settings of JSON formatters as shown below. With our example this code goes in WebApiConfig.cs file in App_Start folder.

config.Formatters.JsonFormatter.SerializerSettings.Formatting =
                            Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
    new CamelCasePropertyNamesContractResolver();


Asp.net Core Continued

65 66 67 68 69 70 71 65 ASP.NET Core Identity It is a membership system Step 1 : Inherit from IdentityDbContext class instead of ...