Button Styling

Tuesday 16 July 2013
How to style button shown below

  




copy image 

 CSS for Submit Button

.clientSubmitButton
{
    background: #FAFBFB url('submitbutton.bmp') no-repeat scroll 0px center;
    border-radius: 5px;
    border: 1px solid #A4ABAC;
    color: #40464A;
    padding: 4px 7px 4px 7px;
    margin: 0px 0px 0px 0px;
    text-decoration: none;
    font-weight: bold;
    box-shadow: inset 0px -2px 5px rgba(164, 171, 172, 0.5);
    display:inline-block;
}
.clientSubmitButton:hover
{
    text-decoration: underline;    
    cursor: pointer;
    cursor: hand;
}

ASP.Net Button Control











 


  CSS for Submit Button

.button {
     
    /*Step 2: Basic Button Styles*/
      display:inline-block;
    /*Step 2: Basic Button Styles*/
height:30px;
width:100px;
    background: #34696f;
    border: 2px solid rgba(33, 68, 72, 0.59);
   
    /*Step 3: Text Styles*/
    color: rgba(0, 0, 0, 0.55);
    text-align: center; 
 
 /*Step 4: Fancy CSS3 Styles*/
    background: -webkit-linear-gradient(top, #34696f, #2f5f63);
    background: -moz-linear-gradient(top, #34696f, #2f5f63);
    background: -o-linear-gradient(top, #34696f, #2f5f63);
    background: -ms-linear-gradient(top, #34696f, #2f5f63);
    background: linear-gradient(top, #34696f, #2f5f63);
     
    -webkit-border-radius: 50px;
    -khtml-border-radius: 50px;
    -moz-border-radius: 50px;
    border-radius: 50px;
     
    -webkit-box-shadow: 0 8px 0 #1b383b;
    -moz-box-shadow: 0 8px 0 #1b383b;
    box-shadow: 0 8px 0 #1b383b;
     
    text-shadow: 0 2px 2px rgba(255, 255, 255, 0.2);
     
}
 
/*Step 3: Link Styles*/
a.button2 {
    text-decoration: none;
}
 
/*Step 5: Hover Styles*/
a.button:hover {
    background: #3d7a80;
    background: -webkit-linear-gradient(top, #3d7a80, #2f5f63);
    background: -moz-linear-gradient(top, #3d7a80, #2f5f63);
    background: -o-linear-gradient(top, #3d7a80, #2f5f63);
    background: -ms-linear-gradient(top, #3d7a80, #2f5f63);
    background: linear-gradient(top, #3d7a80, #2f5f63);
}

ASP.Net Button Control


Read more ...

MVC Interview Questions

Tuesday 9 July 2013
1

MVC is a standard design pattern that many developers are familiar with. The Model-View-Controller
(MVC) architectural pattern separates an application into three main components: the model, the view,
and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms
pattern for creating Web applications. The MVC pattern helps you create applications that separate the
 different aspects of the application (input logic, business logic, and UI logic), while providing a loose
coupling between these elements. The pattern specifies where each kind of logic should be located in
 the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic
 belongs in the model. This separation helps you manage complexity when you build an application,
because it enables you to focus on one aspect of the implementation at a time. For example, you can
 focus on the view without depending on the business logic.
The loose coupling between the three main components of an MVC application also promotes parallel
development. For example, one developer can work on the view, a second developer can work on the
controller logic, and a third developer can focus on the business logic in the model.
2
 In which assembly is MVC framework defined?

System.Web.Mvc
3

The MVC framework includes the following components:
Models. Model objects are the parts of the application that implement the logic for the application's data
 domain. Often, model objects retrieve and store model state in a database. For example, a Product
object might retrieve information from a database, operate on it, and then write updated information
back to a Products table in a SQL Server database.
In small applications, the model is often a conceptual separation instead of a physical one. For example,
 if the application only reads a dataset and sends it to the view, the application does not have a physical
 model layer and associated classes. In that case, the dataset takes on the role of a model object.Views.
Views are the components that display the application's user interface (UI). Typically, this UI is created
from the model data. An example would be an edit view of a Products table that displays text boxes,
 drop-down lists, and check boxes based on the current state of a Product object.Controllers. Controllers
are the components that handle user interaction, work with the model, and ultimately select a view to
render that displays UI. In an MVC application, the view only displays information; the controller handles
 and responds to user input and interaction. For example, the controller handles query-string values,
and passes these values to the model, which in turn might use these values to query the database.
4

MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web
application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to
display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET
 applications can be complex, because to test an individual page, you must instantiate the page class,
all its child controls, and additional dependent classes in the application. Because so many classes are
 instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of
the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to
implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application
 require a Web server. The MVC framework decouples the components and makes heavy use of
interfaces, which makes it possible to test individual components in isolation from the rest of the
 framework.
5 Advantages of MVC based applications?
The ASP.NET MVC framework offers the following advantages:
•It makes it easier to manage complexity by dividing an application into the model, the view, and the
 controller.
•It does not use view state or server-based forms. This makes the MVC framework ideal for developers
who want full control over the behavior of an application.
•It uses a Front Controller pattern that processes Web application requests through a single controller.
This enables you to design an application that supports a rich routing infrastructure. For more
information, see Front Controller on the MSDN Web site.
•It provides better support for test-driven development (TDD).
•It works well for Web applications that are supported by large teams of developers and Web designers
who need a high degree of control over the application behavior.
6 Advantages of web-based applications?
The Web Forms-based framework offers the following advantages:
•It supports an event model that preserves state over HTTP, which benefits line-of-business Web
application development. The Web Forms-based application provides dozens of events that are
 supported in hundreds of server controls.
•It uses a Page Controller pattern that adds functionality to individual pages. For more information,
 see Page Controller on the MSDN Web site.
•It uses view state or server-based forms, which can make managing state information easier.
•It works well for small teams of Web developers and designers who want to take advantage of the
large number of components available for rapid application development.
•In general, it is less complex for application development, because the components (the Page class,
controls, and so on) are tightly integrated and usually require less code than the MVC model. 
7
 Basic Features of MVC framework?

The ASP.NET MVC framework provides the following features:Separation of application tasks (input
logic, business logic, and UI logic), testability, and test-driven development (TDD). All core contracts in
 the MVC framework are interface-based and can be tested by using mock objects, which are simulated
 objects that imitate the behavior of actual objects in the application. You can unit-test the application
without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible.
You can use any unit-testing framework that is compatible with the .NET Framework.An extensible
and pluggable framework. The components of the ASP.NET MVC framework are designed so that they
 can be easily replaced or customized. You can plug in your own view engine, URL routing policy,
action-method parameter serialization, and other components. The ASP.NET MVC framework also
supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI
 enables you to inject objects into a class, instead of relying on the class to create the object itself.
 IOC specifies that if an object requires another object, the first objects should get the second object
from an outside source such as a configuration file. This makes testing easier.Extensive support for
 ASP.NET routing, which is a powerful URL-mapping component that lets you build applications that
have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are
 designed to support URL naming patterns that work well for search engine optimization (SEO) and
representational state transfer (REST) addressing.Support for using the markup in existing ASP.NET
 page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view
templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested
master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding,
 localization, and so on.Support for existing ASP.NET features. ASP.NET MVC lets you use features
 such as forms authentication and Windows authentication, URL authorization, membership and roles,
 output and data caching, session and profile state management, health monitoring, the configuration
system, and the provider architecture.
8
 What is REST model?

Representational State Transfer, or REST for short?
Well, REST is an architectural pattern that defines how network resources should be defined and
addressed in order to gain shorter response times, clear separation of concerns between the front-end
and back-end of a networked system. REST is based on three following principles:
•An application expresses its state and implements its functionality by acting on logical resources
•Each resource is addressed using a specific URL syntax
•All addressable resources feature a contracted set of operations
       
9
 Difference between ASP.NET and MVC?

It is an ASP.NET framework that performs data exchange by using a REST model versus the postback
 model of classic ASP.NET. Each page is split into two distinct components -controller and view – that
 operate over the same model of data. This is opposed to the classic code-behind model where no
 barrier is set that forces you to think in terms of separation of concerns and controllers and views.
However, by keeping the code-behind class as thin as possible, and designing the business layer
 appropriately, a good developer could achieve separation of concerns even without adopting MVC
 and its overhead. MVC, however, is a model superior to a properly-done code-behind for its inherent
 support for test-driven development. 
10
 MVC for ASP.NET programmers?

What can be the quickest and most effective way to explain the MVC Framework to ASP.NET
 developers. It's like having a central HTTP handler that captures all requests to resources identified
with a new extension. This HTTP handler analyzes the syntax of the URL and maps it to a special server
 component known as the controller. The controller supports a number of predefined actions. The
 requested action is somehow codified in the URL according to an application-specific syntax. The
central HTTP handler invokes the action on the controller and the controller will process the request
up to generating the response in whatever response format you need. The response is generated
through a view component.
What here I called the "central HTTP handler" plays the same role that was of the System.Web.UI.Page
 class in classic ASP.NET. The Page is the handler responsible for any .aspx request and generates the
 markup using the code-behind class and serves it back using postbacks. In the MVC Framework, this
 pattern - hard-coded in the ASP.NET runtime and not subject to change until the whole ASP.NET
platform is rewritten - is simply implemented using an alternative HTTP handler and an alternative
model based on REST and MVC. 
11
 When to use MVC?

I would say one very compelling scenario to use MVC is if you have a group of experienced .NET
developers who dont have experience with WebForms. They don't need to go into details and
complexity of abstraction and postbacks to use MVC.
 

What is MVC(Model view controller)?

MVC is architectural pattern which separates the representation and the user interaction. It’s divided in three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task.
  • The “View” is responsible for look and feel.
  • “Model” represents the real world object and provides data to the “View”.
  • The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.


Figure: - MVC (Model view controller)

Can you explain the complete flow of MVC? 

Below are the steps how control flows in MVC (Model, view and controller) architecture:-
  • All end user requests are first sent to the controller.
  • The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  • The final view is then attached with the model data and sent as a response to the end user on the browser.

Is MVC suitable for both windows and web application?

MVC architecture is suited for web application than windows. For window application MVP i.e. “Model view presenter” is more applicable.IfyouareusingWPFandSLMVVMismoresuitableduetobindings.

What are the benefits of using MVC?

There are two big benefits of MVC:-
Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.
Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.

Is MVC different from a 3 layered architecture?

MVC is an evolution of a 3 layered traditional architecture. Many components of 3 layered architecture are part of MVC.  So below is how the mapping goes.
Functionality3 layered / tiered architecture Model view controller architecture
Look and FeelUser interface. View.
UI logicUser interface. Controller
Business logic /validationsMiddle layer Model.
Request is first sent toUser interface Controller.
Accessing dataData access layer. Data access layer.

Figure: - 3 layered architecture

What is the latest version of MVC? 

When this note was written, four versions where released of MVC. MVC 1 , MVC 2, MVC 3 and MVC 4. So the latest is MVC 4.

What is the difference between each version of MVC?

Below is a detail table of differences. But during interview it’s difficult to talk about all of them due to time limitation. So I have highlighted important differences which you can run through before the interviewer.
MVC 2  MVC 3MVC 4 
Client-Side Validation Templated Helpers Areas Asynchronous Controllers Html.ValidationSummary Helper Method DefaultValueAttribute in Action-Method Parameters Binding Binary Data with Model Binders DataAnnotations Attributes Model-Validator Providers New RequireHttpsAttribute Action Filter Templated Helpers Display Model-Level Errors RazorReadymade project templates
HTML 5 enabled templatesSupport for Multiple View EnginesJavaScript and Ajax
Model Validation Improvements
ASP.NET Web APIRefreshed and modernized default project templatesNew mobile project template
Many new features to support mobile apps
Enhanced support for asynchronous methods

What are routing in MVC? 

Routing helps you to define a URL structure and map the URL with the controller.
For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”,  it goes to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.
routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer", 
id = UrlParameter.Optional }); // Parameter defaults   

Where is the route mapping code written?

The route mapping code is written in the “global.asax” file.

Can we map multiple URL’s to the same action?

Yes , you can , you just need to make two entries with different key names and specify the same controller and action.

How can we navigate from one view to other view using hyperlink?

By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.
<%= Html.ActionLink("Home","Gotohome") %>  

How can we restrict MVC actions to be invoked only by GET or POST?

We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.
[HttpGet]
        public ViewResult DisplayCustomer(int id)
        {
            Customer objCustomer = Customers[id];
            return View("DisplayCustomer",objCustomer);
        } 

How can we maintain session in MVC?

Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

What is the difference between tempdata ,viewdata and viewbag?



Figure:- difference between tempdata , viewdata and viewbag
Temp data: -Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect,“tempdata” helps to maintain data between those redirects. It internally uses session variables.
View data: - Helps to maintain data when you move from controller to view.
View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Figure:-dynamic keyword
Session variables: - By using session variables we can maintain data from any entity to any entity.
Hidden fields and HTML controls: - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.
Below is a summary table which shows different mechanism of persistence.
Maintains data between ViewData/ViewBagTempData Hidden fieldsSession
Controller to ControllerNo YesNoYes
Controller to ViewYes NoNoYes
View to ControllerNo NoYesYes

What are partial views in MVC? 

Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header and footer as shown in the image below.

Figure:- partial views in MVC
For every page you would like to reuse the left menu, header and footer controls. So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

How did you create partial view and consume the same?

When you add a view to your project you need to check the “Create partial view” check box.

Figure:-createpartialview
Once the partial view is created you can then call the partial view in the main view using “Html.RenderPartial” method as shown in the below code snippet.
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body> 

How can we do validations in MVC? 

One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “customer” class with a property “customercode”.
This”CustomerCode” property is tagged with a “Required” data annotation attribute. In other words if this model is not provided customer code it will not accept the same.
public class Customer
{
        [Required(ErrorMessage="Customer code is required")]
        public string CustomerCode
        {
            set;
            get;
        } 
}  
In order to display the validation error message we need to use “ValidateMessageFor” method which belongs to the “Html” helper class.
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%> 
Later in the controller we can check if the model is proper or not by using “ModelState.IsValid” property and accordingly we can take actions.
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
                obj.Save();
                return View("Thanks");
}
else
{
                return View("Customer");
}
} 
Below is a simple view of how the error message is displayed on the view.

Figure:- validations in MVC

Can we display all errors in one go?

Yes we can, use “ValidationSummary” method from HTML helper class.
<%= Html.ValidationSummary() %>   
What are the other data annotation attributes for validation in MVC?
If you want to check string length, you can use “StringLength”.
[StringLength(160)]
public string FirstName { get; set; }
In case you want to use regular expression, you can use “RegularExpression” attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the “Range” attribute.
[Range(10,25)]public int Age { get; set; }
Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }
In case you want to get a particular error message , you can use the “Errors” collection.
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call “TryUpdateModel” in your controller to check if the object is valid or not.
TryUpdateModel(NewCustomer);
In case you want add errors in the controller you can use “AddModelError” function.
ModelState.AddModelError("FirstName", "This is my server-side error.");

How can we enable data annotation validation on client side?

It’s a two-step process first reference the necessary jquery files.
<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script> 
Second step is to call “EnableClientValidation” method.
<% Html.EnableClientValidation(); %> 

What is razor in MVC? 

It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was introduced in MVC 3.

Why razor when we already had ASPX?

Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write.
<%=DateTime.Now%> 
In Razor it’s just one line of code.
@DateTime.Now

So which is a better fit Razor or ASPX?

As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes.

How can you do authentication and authorization in MVC?

You can use windows or forms authentication for MVC.

How to implement windows authentication for MVC?

For windows authentication you need to go and modify the “web.config” file and set authentication mode to windows.
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization> 
Then in the controller or on the action you can use the “Authorize” attribute which specifies which users have access to these controllers and actions. Below is the code snippet for the same. Now only  the users specified in the controller and action can access the same.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
    public class StartController : Controller
    {
        //
        // GET: /Start/
        [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
        public ActionResult Index()
        {
            return View("MyView");
        }
    } 

How do you implement forms authentication in MVC?

Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication> 
We also need to create a controller where we will check the user is proper or not. If the user is proper we will set the cookie value.
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123"))
{
            FormsAuthentication.SetAuthCookie("Shiv",true);
            return View("About");
}
else
{
            return View("Index");
}
} 
All the other actions need to be attributed with “Authorize” attribute so that any unauthorized user if he makes a call to these controllers it will redirect to the controller ( in this case the controller is “Login”) which will do authentication.
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
} 

How to implement Ajax in MVC?

You can implement Ajax in two ways in MVC: -
  • Ajax libraries
  • Jquery
Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the submit action click will be an asynchronous ajax call.
<script language="javascript">
function OnSuccess(data1) 
{
// Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};        
    %>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %> 
In case you want to make ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as shown in the below code.

Figure:- implement Ajax in MVC
So if you want to create Ajax asynchronous   hyperlink by name “GetDate” which calls the “GetDate” function on the controller , below is the code for the same.  Once the controller responds this data is displayed in the HTML DIV tag by name “DateDiv”.
<span id="DateDiv" />
<%: 
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%> 
Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.
public class Default1Controller : Controller
{
       public string GetDate()
       {
           Thread.Sleep(10000);
           return DateTime.Now.ToString();
       }
}
The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we are making an ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$.post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyper link click event as you want.
function GetData() 
    {
        var url = "/MyAjax/getCustomer";
        $.post(url, function (data) 
        {
            $("#txtCustomerCode").val(data.CustomerCode);
            $("#txtCustomerName").val(data.CustomerName);
        }
        )
    } 

What kind of events can be tracked in AJAX?  


Figure:- tracked in AJAX

What is the difference between “ActionResult” and “ViewResult”?

“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult” and so on.
“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.
public ActionResult DynamicView()
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
} 

What are the different types of results in MVC?

Note: -It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest. 
There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that canhave11subtypes’sas listed below: -
  1. ViewResult - Renders a specified view to the response stream
  2. PartialViewResult - Renders a specified partial view to the response stream
  3. EmptyResult - An empty response is returned
  4. RedirectResult - Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult - Serializes a given ViewData object to JSON format
  7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult - Writes content to the response stream without requiring a view
  9. FileContentResult - Returns a file to the client
  10. FileStreamResult - Returns a file to the client, which is provided by a Stream
  11. FilePathResult - Returns a file to the client

What are “ActionFilters”in MVC?

“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed.

Figure:- “ActionFilters”in MVC
Action filters are useful in the following scenarios:-
  1. Implement post-processinglogicbeforethe action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.
You can create action filters by two ways:-
  • Inline action filter.
  • Creating an “ActionFilter” attribute.
To create a inline action attribute we need to implement “IActionFilter” interface.The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement pre-processing logic or cancellation logic in these methods.
public class Default1Controller : Controller , IActionFilter
    {
        public ActionResult Index(Customer obj)
        {
            return View(obj);
        }
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");            
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            Trace.WriteLine("Action is executing");
        }
    } 
The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in the below code.
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
     Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
      Trace.WriteLine("Action executing");
}
} 
Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the “Default1Controller” with “MyActionAttribute” class which was created in the previous code.
[MyActionAttribute]
public class Default1Controller : Controller 
{
 public ActionResult Index(Customer obj)
 {
 return View(obj);
 }
}  

Can we create our custom view engine using MVC?

Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to follow 3 steps:-
Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time.
Step 1:- We need to create a class which implements “IView” interface. In this class we should write the logic of how the view will be rendered in the “render” function. Below is a simple code snippet for the same.
public class MyCustomView : IView
    {
        private string _FolderPath; // Define where  our views are stored
        public string FolderPath
        {
            get { return _FolderPath; }
            set { _FolderPath = value; }
        }

        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
           // Parsing logic <dateTime>
            // read the view file
            string strFileData = File.ReadAllText(_FolderPath);
            // we need to and replace <datetime> datetime.now value
            string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
            // this replaced data has to sent for display
            writer.Write(strFinal); 
        }
    } 
Step 2 :-We need to create a class which inherits from “VirtualPathProviderViewEngine” and in this class we need to provide the folder path and the extension of the view name. For instance for razor the extension is “cshtml” , for aspx the view extension is “.aspx” , so in the same way for our custom view we need to provide an extension. Below is how the code looks like. You can see the “ViewLocationFormats” is set to the “Views” folder and the extension is “.myview”.
public class MyViewEngineProvider : VirtualPathProviderViewEngine
    {
        // We will create the object of Mycustome view
        public MyViewEngineProvider() // constructor
        {
            // Define the location of the View file
            this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; //location and extension of our views
        }
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing logic so that it can be registered in the view engine collection
        }
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing logic so that it can be registered in the view engine collection
        }
    } 
Step 3:- We need to register the view in the custom view collection. The best place to register the custom view engine in the “ViewEngines” collection is the “global.asax” file. Below is the code snippet for the same.
protected void Application_Start()
 {
            // Step3 :-  register this object in the view engine collection
            ViewEngines.Engines.Add(new MyViewEngineProvider());
<span class="Apple-tab-span" style="white-space: pre; "> </span>…..
} 
Below is a simple output of the custom view written using the commands defined at the top.

Figure:-customviewengineusingMVC
If you invoke this view you should see the following output.

How to send result back in JSON format in MVC?

In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a simple sample code which returns back “Customer” object in JSON format using “JsonResult”.
public JsonResult getCustomer()
{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
 return Json(obj,JsonRequestBehavior.AllowGet);
} 
Below is the JSON output of the above code if you invoke the action via the browser.

What is “WebAPI”?

HTTP is the most used protocol.For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile,javascripts,windows  application etc.
For satisfying the broad range of client “REST” was the proposed approach. You can read more about “REST” from WCF chapter.
“WebAPI” is the technology by which you can expose data over HTTP following REST principles.

But WCF SOAP also does the same thing, so how does “WebAPI” differ?


SOAP WEB API
SizeHeavy weight because of complicated WSDL structure. Light weight, only the necessary information is transferred.
ProtocolIndependent of protocols.Only  for HTTP protocol
FormatsTo parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call. Output of “WebAPI” are simple string message,JSON,Simple XML format etc. So writing parsing logic for the same in very easy.
PrinciplesSOAP follows WS-* specification. WEB API follows REST principles. (Please refer about REST in WCF chapter).

With WCF also you can implement REST,So why "WebAPI"?

WCF was brought in to implement SOA, never the intention was to implement REST."WebAPI'" is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

How to implement “WebAPI” in MVC?

Below are the steps to implement "webAPI" :-
Step1:-Create the project using the "WebAPI" template.

Figure:- implement “WebAPI” in MVC
Step 2:- Once you have created the project you will notice that the controller now inherits from "ApiController" and you can now implement "post","get","put" and "delete" methods of HTTP protocol.
public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        public void Post([FromBody]string value)
        {
        }
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    } 
Step 3:-If you make a HTTP GET call you should get the below results.

Figure:- HTTP
 
 
Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers.
  • What is IL code, CLR, CTS, GAC & GC?
  • How can we do Assembly versioning?
  • can you explain how ASP.NET application life cycle and page life cycle events fire?
  • What is the problem with Functional Programming?
  • Can you define OOP and the 4 principles of OOP?
  • What are Classes and Objects?
  • What is Inheritance?
  • What is Polymorphism, overloading, overriding and virtual?
  • Can you explain encapsulation and abstraction?
  • What is an abstract class?
  • Define Interface & What is the diff. between abstract & interface?
  • What problem does Delegate Solve ?
  • What is a Multicast delegate ?
  • What are events and what's the difference between delegates and events?
  • How can we make Asynchronous method calls using delegates ?
  • What is a stack, Heap, Value types and Reference types ?
  • What is boxing and unboxing ?
  • Can you explain ASP.NET application and Page life cycle ?
  • What is Authentication, Authorization, Principal & Identity objects?
  • How can we do Inproc and outProc session management ?
  • How can we windows , forms and passport authentication and authorization in ASP.NET ?
  • In a parent child relationship which constructor fires first ?
MVC ASP.NET Q & A series
  • How to create a simple "Hello World" using ASP.NET MVC template? - Lab 1
  • How to pass data from controller to views? - Lab 2
  • Can we see a simple sample of model using MVC template? - Lab 3
  • How can we create simple input screens using MVC template? - Lab 4
  • How can we create MVC views faster and make them strong typed by using HTML helper? - Lab 5
  • Can we see how easy it is do unit testing for MVC application? - Lab 6
  • What is MVC routing? - Lab 7
  • How can we set default values & validate MVC routes? - Lab 8
  • How we can define actions & navigate from one page to other page? - Lab 9
WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview question and answers
  • What is SOA, Services and Messages ?
  • What is the difference between Service and Component?
  • What are basic steps to create a WCF service ?
  • What are endpoints, address, contracts and bindings?
  • What are various ways of hosting WCF service?
  • What is the difference of hosting a WCF service on IIS and Self hosting?
  • What is the difference between BasicHttpBinding and WsHttpBinding?
  • How can we do debugging and tracing in WCF?
  • Can you explain transactions in WCF (theory)?
  • How can we self host WCF service ?
  • What are the different ways of implementing WCF Security?
  • How can we implement SSL security on WCF(Transport Security)?
  • How can we implement transport security plus message security in WCF ?
  • How can we do WCF instancing ?
  • How Can we do WCF Concurency and throttling?
  • Can you explain the architecture of Silverlight ?
  • What are the basic things needed to make a silverlight application ?
  • How can we do transformations in SilverLight ?
  • Can you explain animation fundamentals in SilverLight?
  • What are the different layout methodologies in SilverLight?
  • Can you explain one way , two way and one time bindings?
  • How can we consume WCF service in SilverLight?
  • How can we connect databases using SilverLight?
  • What is LINQ and can you explain same with example?
  • Can you explain a simple example of LINQ to SQL?
  • How can we define relationships using LINQ to SQL?
  • How can we optimize LINQ relationships queries using ‘DataLoadOptions’?
  • Can we see a simple example of how we can do CRUD using LINQ to SQL?
  • How can we call a stored procedure using LINQ?
  • What is the need of WPF when we had GDI, GDI+ and DirectX?
  • Can you explain how we can make a simple WPF application?
  • Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?
  • Can you explain the Architecture of WPF?
  • What is Azure?
  • Can you explain Azure Costing?
  • Can we see a simple Azure sample program?
  • What are the different steps to create a simple Worker application?
  • Can we understand Blobs in steps, Tables & Queues ?
  • Can we see a simple example for Azure tables?
  • What is Package and One click deploy(Deployment Part - 1) ?
  • What is Web.config transformation (Deployment Part-2)?
  • What is MEF and how can we implement the same?
  • How is MEF different from DIIOC?
  • Can you show us a simple implementation of MEF in Silverlight ?
Design pattern, Estimation, VSTS, Project management interview questions and answers

Design Pattern Training / Interview Questions and Answers
  • Introduction
  • Factory Design Pattern
  • Abstract Factory Design Pattern
  • Builder Design Pattern
  • Prototype Design Pattern
  • Singleton Design Pattern
  • Adapter Design Pattern
  • Bridge Design Pattern
  • Composite Design Pattern
  • Decorator Design Pattern
  • Facade Design Pattern
  • Flyweight Design Pattern
  • Proxy Design Pattern
  • Mediator Design Pattern
  • Memento Design Pattern
  • Interpreter Design Pattern
  • Iterator Design Pattern
  • COR Design Pattern
  • Command Design Pattren
  • State Design Pattern
  • Strategy Design Pattern
  • Observer Design Pattern
  • Template Design Pattern
  • Visitor Design Pattern
  • Dependency IOC Design pattern
  • MVC , MVP , DI IOC and MVVM Training / Interview Questions and Answers


UML Training / Interview Questions and Answers
  • Introduction
  • Use Case Diagrams
  • Class Digrams
  • Object Diagrams
  • Sequence Digrams
  • Collaboration Diagrams
  • Activity Diagram
  • State chart Diagrams
  • Component Diagrams
  • Deployment Diagrams
  • Stereo Types Diagrams
  • Package Diagram and UML Project Flow.
Function points Training / Interview Questions and Answers
  • Introduction
  • Application Boundary
  • EI Fundamentals
  • EO Fundamentals
  • EQ Fundamentals
  • EIF
  • Fundamentals
  • ILF Fundamentals
  • GSC Fundamentals
  • Productivity Factor
  • Costing and a complete estimation of customer screen using function points.
  • FXCOP and Stylecop Training / Interview Questions and Answers


VSTS Training / Interview Questions and Answers
  • VSTS questions and answer videos
  • What is Unit Testing & can we see an example of the same?
  • How can we write data driven test using NUNIT & VS Test?
  • Can we see simple example of a unit test for database operation?
  • How can we do automated testing using Visual Studio Test?
  • How can we do Load Testing using VSTS test?
  • Can you explain database unit testing?
  • How can we do test coverage using VSTS system?
  • How can we do manual Testing using VSTS?
  • What is Ordered Test in VSTS test?



Enterprise Application Blocks Training
  • Introduction
  • Validation Application Block
  • Logging Application Block
  • Exception error Handling
  • Data Application Block
  • Caching Application Block
  • Security Application Block
  • Policy Injection Application Block and
  • Unity Application Block


Complete .NET invoicing project end to end
  • Introduction to .NET Projects
  • Different levels of Programming
  • Necessary Tools
  • What should we learn ?
  • The IIS
  • Making UI using .net IDE
  • Database, The SQL Server
  • Connecting ASP.net with Database
  • Loading the Data Grid
  • Update and Delete
  • Validations
  • Issue with the Code
  • Two Tier Architecture
  • Three Tier Architecture
  • Database Normalization
  • Session and State Management
  • Using Enterprise Application Block
  • Aggregation and Composition
  • Implementing Interfaces and Factory
  • Inheritance relationship
  • Abstract Class Implementation


Share point interview Training / Interview Questions and Answers videos
  • What is SharePoint, WSS and MOSS?
  • How does WSS actually work?
  • What is Site and SiteCollection?
  • What is the use of SQL server in SharePoint & use of Virtual path provider?
  • What is Ghosting and UnGhosting in SharePoint?
  • How can we create a site in SharePoint?
  • How can we Customize a SharePoint Site?
  • What kind of readymade functional modules exists collaboration?
  • Can you display a simple Custom Page in SharePoint?
  • How can we implement behind code ASPX pages in SharePoint?
  • What is the concept of features in SharePoint?
  • I want a feature to be only displayed to admin?
  • How do we debug SharePoint error’s?
  • Why customized pages are parsed using no-compile mode?
  • Can you explain WSS model?
  • How can we use custom controls in SharePoint?
  • How can we display ASCX control in SharePoint pages?
  • What are Web Parts?
  • How can we deploy a simple Webpart in SharePoint?
  • How can we achieve customization and personalization using WebParts?
  • How can we create custom editor for WebPart?
  • SharePoint is about centralizing documents, how similar is to the windows folder?
  • What are custom fields and content types?
  • Can you explain SharePoint Workflows?
  • What is a three-state Workflow in SharePoint?
  • How can we create sharepoint workflow using sharepoint designer?


.NET best practices and SQL Server Training / Interview Questions and Answers
  • Basics :- Query plan, Logical operators and Logical reads
  • Point 1 :- Unique keys improve table scan performance.
  • Point 2 :- Choose Table scan for small & Seek scan for large records
  • Point 3 :- Use Covering index to reduce RID (Row Identifier) lookup
  • Point4:- Keep index size as small as possible.
  • Point5:- use numeric as compared to text data type.
  • Point6:- use indexed view for aggregated SQL Queries
  • Finding high memory consuming functions
  • Improve garbage collector performance using finalize/dispose pattern
  • How to use performance counters to gather performance data
 
What is an Object in OOPS??
An object is a software bundle of variables and related methods. Objects are related to real life scenario. Class is the general thing and object is the specialization of general thingObjects is instance of classes.

Declaration of an Object in OOPs
ClassName objectName=new ClassName();
E.g.: Person objPerson= new Person();
An object is characterized by concepts like:
  • Attribute
  • Behavior
  • Identity
What is an Attribute in OOPs??
  • Attributes define the characteristics of a class.
  • The set of values of an attribute of a particular object is called its state.
  • In Class Program attribute can be a string or it can be a integer.
What is Encapsulation in OOPS??
  • Encapsulation is one of the fundamental principles of object-oriented programming.
  • Encapsulation is a process of hiding all the internal details of an object from the outside world.
  • Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required
  • Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class
  • Encapsulation gives us maintainability, flexibility and extensibility to our code.
  • Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.
  • Encapsulation provides a way to protect data from accidental corruption
  • Encapsulation hides information within an object
  • Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods
  • Encapsulation gives you the ability to validate the values before the object user change or obtain the value
  • Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.


There are two ways to create a validation process.
  • Using Assessors and Mutators
  • Using properties
Benefits of Encapsulation
  • In Encapsulation fields of a class can be read-only or can be write-only
  • A class can have control over in its fields
  • A class can change data type of its fields anytime but users of this class do not need to change any code
What is Inheritance in OOPS? ?
  • Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (concept) of object-oriented programming
  • Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes
  • The Class whose methods and variables are defined is called super class or base class
  • The Class that inherits methods and variables are defined is called sub class or derived class
  • Sometimes base class known as generalized class and derived class known as specialized class
  • Keyword to declare inheritance is “:” (colon) in visual c#


Benefits of using Inheritance
  • Once a behavior (method) or property is defined in a super class(base class),that behavior or property is automatically inherited by all subclasses (derived class).
  • Code reusability increased through inheritance
  • Inheritance provide a clear model structure which is easy to understand without much complexity
  • Using inheritance, classes become grouped together in a hierarchical tree structure
  • Code are easy to manage and divided into parent and child classes


When we define clean up destructor , how does it affect garbage collector?
If you define clean up in destructor garbage collector will take more time to clean up the objects and more and more objects are created in Gen 2..

What is Polymorphism in OOPS?
  • Polymorphism is one of the primary characteristics (concept) of object-oriented programming
  • Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details
  • Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form
  • Polymorphism is the ability to process objects differently depending on their data types
  • Polymorphism is the ability to redefine methods for derived classes.


Types of Polymorphism
  • Compile time Polymorphism
  • Run time Polymorphism
What is Access Modifier in OOPS?
Access modifiers determine the extent to which a variable or method can be accessed from another class or object.

  • Private
  • Protected
  • Internal
  • Protected Internal
  • Public
Read more ...

Sharing

Get widget