Tuesday, 23 July 2013

Insight MVC interview question

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax


 protected void Application_Start()
        {
            .....

            RegisterRoutes(RouteTable.Routes);
        }

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default"// Route name
                "{controller}/{action}/{id}"// URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
 
            routes.MapRoute(
                "TwoParameters"// Route name
                "{controller}/{action}/{parentId}/{id}"// URL with parameters
                new { controller = "Home", action = "Index", parentId = "", id = UrlParameter.Optional } // Parameter defaults
            );
        }

What are the different return type controllers action method supports in ASP.NET MVC?

There are total nine return types we can use to return results from controller to view.  The base type of all these result types is ActionResult. 1. ViewResult (View) : This return type is used to return a webpage from an action method. 2. PartialviewResult (Partialview) : This return type is used to send a part of a view which will be rendered in another view. 3. RedirectResult (Redirect) : This return type is used to redirect to any other controller and action method depending on the URL. 4. RedirectToRouteResult (RedirectToAction, RedirectToRoute) : This return type is used when we want to redirect to any other action method. 5. ContentResult (Content) : This return type is used to return HTTP content type like text/plain as the result of the action 6. jsonResult (json) : This return type is used when we want to return a JSON message. 7. javascriptResult (javascript) : This return type is used to return JavaScript code that will run in browser. 8. FileResult (File) : This return type is used to send binary output in response. 9. EmptyResult : This return type is used to return nothing (void) in the result. 
Action Filtering in ASP.NET MVC Applications
Action Filters allow us to add pre-action and post-action behavior to controller action methods.n action filter is a .NET class that inherits from FilterAttribute or one of its subclasses, usually ActionFilterAttribute, which adds the OnActionExecutingOnActionExecutedOnResultExecuting, and OnResultExecuted methods, providing hooks for code to be executed both before and after the action and result are processed.ASP.NET MVC provides several action filters out of the box:
  • Authorize – checks to see whether the current user is logged in, and matches a provided username or role name (or names), and if not it returns a 401 status, which in turn invokes the configured authentication provider.
  • ChildActionOnly – used to indicate that the action method may only be called as part of a parent request, to render inline markup, rather then returning a full view template.
  • OutputCache – tells ASP.NET to cache the output of the requested action, and to serve the cached output based on the parameters provided.
  • HandleError – provides a mechanism for mapping exceptions to specific View templates, so that you can easily provide custom error pages to your users for specific exceptions (or simply have a generic error view template that handles all exceptions).
  • RequireHttps – forces a switch from http to https by redirecting GET requests to the https version of the requested URL, and rejects non-https POST requests.
  • ValidateAntiForgeryToken – checks to see whether the server request has been tampered with. Used in conjunction with the AntiForgeryToken HTML Helper, which injects a hidden input field and cookie for later verification (Here’s a post showing one way you can enable this across the board).
  • ValidateInput – when set to false, tells ASP.NET MVC to set ValidateRequest to false, allowing input with potentially dangerous values (i.e. markup and script). You should properly encode any values received before storing or displaying them, when request validation is disabled. Note that in ASP.NET 4.0, request validation occurs earlier in the processing pipeline, so in order to use this attribute, you must set the following value in your web.config file: 
    <httpRuntime requestValidationMode="2.0"/>

Insight Regular Expression.

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

Namespace for regular expression is
using System.Text.RegularExpressions;

The next thing is to create the regex object with the pattern. The below pattern specifies to search for alphabets between a-z with 10 length.
Regex obj = new Regex(“[a-z]{10}”);

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

Finally search the pattern over the data to see if there are matches. In case the pattern is matching the ‘IsMatch’ will return true.
MessageBox.Show(obj.IsMatch(“Andrew1234”).ToString());

regex syntax is mainly depend on use of bracket, caret and dollar. 


BThere are 3 types of brackets used in regular expression
Square brackets “[“and Curly “{“ brackets.
Square brackets specify the character which needs to be matched while curly brackets specify how many characters. “(“ for grouping.
We will understand the same as we move ahead in this article.
Ccaret “^” the start of a regular expression.
DDollar “$” specifies the end of a regular expression.

Example :
^[a-e]{1,2}$ 
explains a expression with aphabets between a and e with minimum size of 1 and maximum size of 2

Validate invoice numbers which have formats like LJI1020, the first 3 characters are alphabets and remaining is 8 length number?
^[a-z]{3}[0-9]{8}$

make above validation case insensitive
^[a-zA-Z]{3}[0-9]{8}$

Simple validation of website URL



Insight Short topics

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

Order of lifecyle of ASP.NET page in mvc

App initialization
Routing
Instantiate and execute controller
Locate and invoke controller action
Instantiate and render view


=============================================================
Overloading
Overloading is when you have multiple methods in the same scope, with the same name but different signatures.
//Overloading
public class test
{
    public void getStuff(int id)
    {}
    public void getStuff(string name)
    {}
}

Overriding
Overriding is a principle that allows you to change the functionality of a method in a child class.
//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}

DELETE 
1. DELETE is a DML Command. 
2. DELETE statement is executed using a row lock, each row in the table is locked for deletion. 
3. We can specify filters in where clause 
4. It deletes specified data if where condition exists. 
5. Delete activates a trigger because the operation are logged individually. 
6. Slower than truncate because, it keeps logs. 
7. Rollback is possible. 

TRUNC ATE 
1. TRUNCATE is a DDL command. 
2. TRUNCATE TABLE always locks the table and page but not each row. 
3. Cannot use Where Condition. 
4. It Removes all the data. 
5. TRUNCATE TABLE cannot activate a trigger because the operation does not log individual row deletions. 
6. Faster in performance wise, because it doesn't keep any logs. 
7. Rollback is not possible. 

DELETE and TRUNCATE both can be rolled back when used with TRANSACTION. 

If Transaction is done, means COMMITED, then we can not rollback TRUNCATE command, but we can still rollback DELETE command from LOG files, as DELETE write records them in Log file in case it is needed to rollback in future from LOG files.


Unitofwork 

Unitofwork pattern can be applied on all tables having at least one identity column because UOW always check against this identity value to update or to add a new record.


When unitofwork.save() is called it check for change in identity column value. if the value of identity column say  219 does not exists in the table than it will simply insert the new record in table where as if the value of identity column say 219 is already exists than it will update the column against that identity column.

Insight ViewModel

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

So far you made your Views display hardcoded HTML, but in order to create dynamic web applications, the View template should receive information from the Controller. One common technique to be used for that purpose is the ViewModel pattern.

  • ViewModel allow you to shape multiple entities from one or more data models or sources in to a single object. It usually made to optimized for consumption and rendering by the views.



Why We Use ViewModel ?

1. If you need to pass more than one thing to a strongly-typed view (which is best practice),
    you will generally want to create a separate class to do so.

2. This allows you to validate your ViewModel differently than your domain model for
    attribute-based validation scenarios

3. Can be used to help shape and format data.
    e.g: need a date or money value formatted a particular way?
          ViewModel is the best place to do it.

4. The use of a ViewModel can make the interaction between model and view more simple

Best Practices When Using ViewModels

1. Put only data that you'll render (use in View) in the ViewModel

2. The View should direct the properties of the ViewModel, this way it fits better for rendering
    and maintenance

Thursday, 4 July 2013

"Checking performance on SQL"

Hi , we will perform a sql performance test on union and union all in this case.

Please copy and paste the following script

/* Declare First Table */
DECLARE @Table1 TABLE (ColDetail VARCHAR(10))
INSERT INTO @Table1
SELECT 'First'
UNION ALL
SELECT 'Second'
UNION ALL
SELECT 'Third'
UNION ALL
SELECT 'Fourth'
UNION ALL
SELECT 'Fifth'
/* Declare Second Table */
DECLARE @Table2 TABLE (ColDetail VARCHAR(10))
INSERT INTO @Table2
SELECT 'First'
UNION ALL
SELECT 'Third'
UNION ALL
SELECT 'Fifth'

/* UNION ALL */
SELECT *
FROM @Table1
UNION ALL
SELECT *
FROM @Table2
/* UNION */
SELECT *
FROM @Table1
UNION
SELECT *
FROM @Table2
GO

Now turn on actual execution plan using CTRL+M.
Below you can see which query get expensive i.e. union as it return only distinct sort values.


Wednesday, 3 July 2013

"Stack, heap, value types, reference types, boxing, and unboxing"

In general,Stack memory -- Value types
Heap memory -- Reference types


When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated that type of memory. There are two types of memory allocation: stack memory and heap memory. In the coming sections, we will try to understand these two types of memory in more detail.


Stack and heap:
public void Method1()
{
    // Line 1
    int i=4;

    // Line 2
    int y=2;

    //Line 3
    class1 cls1 = new class1();
}
It’s a three line code, let’s understand line by line how things execute internally.

Line 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the running memory needed in your application.
Line 2: Now the execution moves to the next step. As the name says stack, it stacks this memory allocation on top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other.
Memory allocation and de-allocation is done using LIFO (Last In First Out) logic. In other words memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.

Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation. 
One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1;does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword, it allocates on "heap".

Now finally the execution control starts exiting the method. When it passes the end control, it clears all the memory variables which are assigned on stack. In other words all variables which are related toint data type are de-allocated in ‘LIFO’ fashion from the stack.
The big catch – It did not de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.





Dynamic v. Strongly Type MVC views

There are three ways to pass information from a controller to a view in ASP.NET MVC 3:
  1. As a strongly typed model object.
  2. As a dynamic type (using @model dynamic)
  3. Using the ViewBag

As a dynamic type (using @model dynamic)

@model dynamic
           
@{
    ViewBag.Title = "IndexNotStonglyTyped";
}
<h2>Index Not Stongly Typed</h2>
<p>
 <ul>
@foreach (var blog in Model) {
   <li>
    <a href="@blog.URL">@blog.Name</a>
   </li>   
}
 </ul>
</p>

Monday, 1 July 2013

Access modifiers

They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

Access modifiers can be apply to 
class, 
fields 
and methods. 

public :
private :
protected :
internal :
protected internal

Public - Any class can refer to the field or call the method. The type or member can be accessed by any other code in the same assembly or another assembly that references it.
The public keyword is an access modifier for types and type members. Public access is the most permissive access level.
There are no restrictions on accessing public members.
 Accessibility
Can be accessed by objects of the class

Can be accessed by derived classes

Private - Only the current class will have access to the field or method. This is the default access modifier type if none is formally specified. By default methods and fields are private. 
Accessibility
Cannot be accessed by object

Cannot be accessed by derived classes

Protected - Only the current class and sub classes (and sometimes also same-package classes) of this class will have access to the field or method. A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Accessibility
Cannot be accessed by object

Can be accessed by derived classes


public class A
    {
       protected int fieldA = 8;
    }
 
    public class B : A
    {
       public void MethodB()
       {
           A obja = new A();
           // obja.fieldA = 5; // Error
 
           B objb = new B();
           objb.fieldA = 23;
 
       }
 
    }


internalAccess is limited exclusively to classes defined within the current project assembly.  Internal member can b accessible anywhere whithin a project. By default Classes are internal

Class Modifiers:
A class can be…
public
private
internal
abstract
sealed
new

public: Instances of this class are available to any class that wants to access.
private: A nested class that can only be accessed inside the class in which it is defined.
internal: The class is only accessible from other classes in the same assembly. This is the default access for non-nested types. If no modifier is specified, the class has internal access.
abstract: An instance of the class cannot be created.Usually this means the class is intended to serve as a base class.
sealed: The class cannot serve as a base class for another class (it can’t be derived from). A class cannot be both abstract and sealed.
new: Used only with nested classes. “New” indicates that the class hides an inherited member of the same name.

Methods:
Methods can be declared as virtual, abstract , or sealed. Methods can be overloaded, overridden and hidden.
virtual methods can be overriden by a derived class using the override keyword.
abstract methods must be overriden in a derived class. If any method of a class is abstract, the entire class must be declared as abstract.

sealed methods are methods that override an inherited virtual method having the same signature. When a method is sealed, it cannot be overriden in a derived class.