Thursday, 26 November 2015

Why use ASP.NET Web API?

ASP.NET Web API is built for all the other, non-human interactions your site or service needs to support. Think about jQuery code that's making an Ajax request, or a service interface that supports a mobile client. In these cases, the requests are coming from code and expect some kind of structured data and specific HTTP Status Codes.
These two are very complimentary, but different enough that trying to build out HTTP services using ASP.NET MVC took a lot of work to get right. The inclusion of ASP.NET Web API in ASP.NET MVC (and availability elsewhere, including ASP.NET Web Pages) means that you can build top-notch HTTP services in an ASP.NET MVC application, taking advantage of a common base and using the same underlying paradigms.
ASP.NET Web API includes support for the following features:
  • Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a new, strongly typed HTTP object model. The same programming model and HTTP pipeline is symmetrically available on the client through the new HttpClient type.
  • Full support for routes: Web APIs now support the full set of route capabilities that have always been a part of the Web stack, including route parameters and constraints. Additionally, mapping to actions has full support for conventions, so you no longer need to apply attributes such as [HttpPost] to your classes and methods.
  • Content negotiation: The client and server can work together to determine the right format for data being returned from an API. We provide default support for XML, JSON, and Form URL-encoded formats, and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy. Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by the Web API actions.
  • Filters: Web APIs now supports filters, including well-known filters such as the [Authorize] attribute. You can author and plug in your own filters for actions, authorization and exception handling.
  • Query composition: By simply returning IQueryable<t>, your Web API will support querying via the OData URL conventions.
  • Improved testability of HTTP details: Rather than setting HTTP details in static context objects, Web API actions can now work with instances of HttpRequestMessage and HttpResponseMessage. Generic versions of these objects also exist to let you work with your custom types in addition to the HTTP types.
  • Improved Inversion of Control (IoC) via DependencyResolver: Web API now uses the service locator pattern implemented by MVC’s dependency resolver to obtain instances for many different facilities.
  • Code-based configuration: Web API configuration is accomplished solely through code, leaving your config files clean.
  • Self-host: Web APIs can be hosted in your own process in addition to IIS while still using the full power of routes and other features of Web API.

Tuesday, 24 November 2015

What is a ViewEngine in ASP.NET MVC?

“View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.”
There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.
  • Web Form View Engine was with ASP.NET MVC since beginning.
  • Razor View Engine was introduced later in MVC3.
  • NHaml is an open source view engine since 2007.
  • Spark is also an open source since 2008.
  • public ActionResult About()
    {
        return View();
    }

Some Types=>>
1) Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC              from the beginning.
2).The namespace for Webform Engine isSystem.Web.Mvc.WebFormViewEngine.
3).The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx extension           for views, .ascx extension for partial views & editor templates and .master extension for                               layout/master pages.
4).Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.
5).Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and s                    sometimes make a view messy. Webform uses <% and %> delimiters to make the code like as:
  1. <%: Html.ActionLink("SignUp", "SignUp") %>

What is the difference between ViewData, ViewBag and TempData?

 In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e., ViewData, ViewBag and TempData.
Both ViewBag and ViewData are used to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism to maintain state between controller and corresponding view.
ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewDatabeing a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks.
TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the other controller.
ViewData
  1. ViewData is used to pass data from controller to view
  2. It is derived from ViewDataDictionary class
  3. It is available for the current request only
  4. Requires typecasting for complex data type and checks for null values to avoid error
  5. If redirection occurs, then its value becomes null
ViewBag
  1. ViewBag is also used to pass data from the controller to the respective view
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only
  4. If redirection occurs, then its value becomes null
  5. Doesn’t require typecasting for complex data type
TempData
  1. TempData is derived from TempDataDictionary class
  2. TempData is used to pass data from the current request to the next request
  3. It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
  4. It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages
You can easily find detailed examples for implementation of ViewBag, ViewData and TempData here.

Monday, 23 November 2015

Top 10 New Features in ASP.net MVC 4


What is New in ASP.net MVC 4 ?

Feature 1 : ASP.net Web API

      What is ASP.net Web API ?

  • New framework for creating HTTP services
  • That can reach a broad range of clients including browsers and mobile devices
  • Web API is also an ideal platform for building RESTful services

Feature 2 : Enhancements to Default Project Templates

  • The Template that is used to create new ASP.net MVC 4 projects has been updated to create a more modern-looking websites

Enhancements to Default Project Templates

  • In addition to cosmetic improvements, there’s improved functionality in the new template
  • The Template employs a technique called Responsive Design to look good in both desktop browsers and mobile browsers without any customization

mobile browsers without any customization


How to See Responsive Design in Action ?
  • You can use a mobile emulator or just try re-sizing the desktop browser window to be smaller
  • When the browser window gets small enough, the layout of the page will change

What is Responsive Web Design (RWD) ?
  • Is a web design approach aimed at crafting sites to provide an optimal viewing experience
  • Easy reading and navigation with a minimum of re-sizing  panning, and scrolling across awide range of devices (from desktop computer monitors to mobile phones)

Feature 3 : Mobile Project Template

  • If you’re starting a new project and want to create a site specifically for mobile and tablet browsers
  • Then you can use the new Mobile Application project Template
  • This is based on jQuery Mobile, an open-source library for building touch-optimized UI
  • This template contains the same application structure as the Internet Application template and the controller code is virtually identical
  • But it's styled using jQuery Mobile

Mobile Project Template


styled using jQuery Mobile



Feature 4 : Display Modes

  • Lets an application select views depending on the browser that's making the request

For example :
  • If a desktop browser requests the Home page, the application might use theViews\Home\Index.cshtml template
  • If a mobile browser requests the Home page, the application might return theViews\Home\Index.mobile.cshtml template
  • Layouts and Partials can also be overridden for particular browser types

That is :
Layouts :
  • If your Views\Shared folder contains both the _Layout.cshtml and _Layout.mobile.cshtmltemplates,
  • Then by default the application will use _Layout.mobile.cshtml during requests from mobile browsers and _Layout.cshtml during other requests

Partials :
  • If a folder contains both _MyPartial.cshtml and _MyPartial.mobile.cshtml,
  • The instruction @Html.Partial("_MyPartial") will render _MyPartial.mobile.cshtml duringrequests from mobile browsers, and _MyPartial.cshtml during other requests

Feature 5 : jQuery Mobile and Mobile Features


  • The jQuery Mobile library provides a user interface framework that works on all the major mobile browsers
  • jQuery Mobile applies progressive enhancement to mobile browsers that support CSS and JavaScript
  • Progressive enhancement allows all browsers to display the basic content of a web page,while allowing more powerful browsers and devices to have a richer display
  • The JavaScript and CSS files that are included with jQuery Mobile style many elements to fit mobile browsers without making any markup changes
  • You can install the jQuery.Mobile.MVC NuGet package, which installs jQuery Mobile and aview-switcher widget


Feature 6 : Task Support for Asynchronous Controllers

  • You can now write asynchronous action methods as single methods that return an object of type Task or Task<ActionResult>

Feature 7 : Azure SDK

  • ASP.net MVC 4 supports the Newer release of the Windows Azure SDK 2.0

Feature 8 : Database Migrations

  • ASP.net MVC 4 projects now include Entity Framework 5
  • One of the great features in Entity Framework 5 is support for database migrations
  • This feature enables you to easily evolve your database schema using a code-focused migration while preserving the data in the database

Feature 9 : Bundling and Minification

  • The bundling and minification framework enables you to reduce the number of HTTP requests
  • That a Web page needs to make by combining individual files into a single,
  • Bundled file for scripts and CSS
  • It can then reduce the overall size of those requests by minifying the contents of the bundle

What is Minifying ?
  • Minifying can include activities like eliminating white space to shortening variable names to even collapsing CSS selectors based on their semantics

How to Handle Bundles ?
  • Bundles are declared and configured in code and are easily referenced in views via helper methods
  • Which can generate either a single link to the bundle or,
  • When debugging, multiple links to the individual contents of the bundle

Feature 10 : Enabling Logins from Facebook and Other Sites Using OAuth
                            and OpenID

  • The default templates in ASP.net MVC 4 Internet Project template now includes support forOAuth and OpenID login using the DotNetOpenAuth library
  • It's on App_Start ==> AuthConfig.cs File


Do You Have Any Problem or Things to Share about ASP.net MVC 4 ?

MVC 4 on Linkedin

Short Description On Project Template In ASP.NET MVC 4

Short Description On Project Template In ASP.NET  MVC 4  

 
Empty: - The Empty template created the minimum references and resources required to run an Asp.net MVC application. As you can see in below image,  Models, Controllers, App_Data are completely empty folders and View folder only contains web.config and a Global.asax file and web.config. App_Start folder contains 3 configuration files ( FilterConfig.cs, RouteConfige.cs and WebApiConfig.cs ). 

 Basic: - It’s a new project type in MVC 4 and it was not available in MVC3. Basic project is much much closer structurally to Empty project in MVC3. It includes Contentand Scripts as well as few more references. Here is a short list of what’s included
jQuery
jQuery UI
jQuery Validation
modernizr
KnockoutJS
Antlr 3
Entity Framework
WebGrease
Bundling and minimization facilities have been prepared in this template. BundleConfig.cs file has been added to App_Start folder. Additionally, what had been disappeared in Views folder came back to the board. _Layout.cshtml includes the jQuery bundle as well as the default theme styling. 
 
 Internet Application :- Adds tow controllers( Account controller and Home controller)  to the Basic template with implemented actions and views.  Membership management functionality which allows you register, login, change password and so on is implemented in Account controller and Home controller gives you Index, About and Contact actions working with their own related views. Its a template used usually to start a normal web project in action.  
 

Intranet Application :- In fact, It’s  the Internet Application except for Membership management.  the Account controller and the web.config has been configured  to use Windows as it’s authentication method.
Mobile Application :-Mobile website programming is one of  most important feature in MVC 4 so this template has everything that Internet Application template has, however it  is using  jQuery.mobile instead.  
 
 Web API  Application :-Its another new Template in VS2012 to make it easy to develop RESTful web services and applications to feed a vast variety rage of clients from desktop browsers to tablet applications. It allows you to expose your data and service to the web directly over  Http. This template includes everything from Basic Template expect Account controller and membership functionality. 
 

Step by Step Creating ASP.NET MVC 4 Application - [Hello World] 

 1) Open the Visual Studio 2012 
 
 2) Select File-------->New------------------------>Project 
 3) A popup will be open, where you can see the list of all available templates for Windows and Web application. Select the Web application from the left hand side and also select the Template from the right hand side of the popup i.e. “ASP.NET MVC 4 Web Application”. Here you also provide the Proper application name and also select the folder where you save the application. 
 
 4) Select the “Ok” button, then after again a Popup will be open where you have to select the proper template for the application. Here in this case “Empty” Template is selected from the “Project Template”. 
 

 

 5) The Empty project will be open which is shown below 
 
 5) Now Right click on the “Controller” folder and then select Add------->Controller. A popup will be open where you give the appropriate name with suffix as a controller and click the add button. HelloWorldController class is opened

 6) Right click on the “Index” function in the “HelloWorldController” and select the “Add View…” option and click the “Add” button. 
 
7) “Index.cshtml” file is created inside the “HelloWorld” folder which is inside the “Views” folder. 
 
 8) Now Open the “Global.asax.cs” file and change the following code snipet 
routes.MapRoute(
               name: "Default",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "HelloWorld", action = "Index", id = UrlParameter.Optional }
           );
 9) Run the application by pressing the F5 key.
 

What is View Engine?

The view engine is responsible for creating HTML from your views. Views are usually some kind of mix-up of HTML and a programming language. The pattern behind most of these is called two-step view.

 
If you have a Web application with many pages, you often want a consistent look and organization to the site. If every page looks different, you end up with a site that users find confusing. You may also want to make global changes to the appearance of the site easily, but common approaches using Template View (350) or Transform View (361) make this difficult because presentation decisions are often duplicated across multiple pages or transform modules. A global change can force you to change several files.
Two Step View deals with this problem by splitting the transformation into two stages. The first transforms the model data into a logical presentation without any specific formatting; the second converts that logical presentation with the actual formatting needed. This way you can make a global change by altering the second stage, or you can support multiple output looks and feels with one second stage each.
In ASP.NET MVC 4 you can select either Razor View Engine or ASPX View Engine

   For example, a code block in ASPX might look like this:  
<% foreach(var item in Model) { %>
    <tr>
        <td><%: item.Name %></td>
    </tr>
<% } %>
  Whereas the Razor equivalent will look like this: 
@foreach(var item in Model) {
    <tr>
        <td>@item.Name</td>
 A view engine is what MVC uses to find and render the views you are requesting from the controller. If you are satisfied with the default routing you probably won’t need to change anything, but let’s say you wanted to have your shared files usually located in root/views/shared to instead be located in root/common, a custom view engine is what you will need to create to be able to do that.

Saturday, 21 November 2015

What is Model View and Controller

Controller: - The controller is like a traffic cop.Whenever user requests any resource it first goes to the controller. Controller than interact with both the Model and View.
is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.
The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.
Model: - The model is responsible for the data for the application and also it creates data for the view. It handles data processing and database works part. 
 the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
View: - It is a presentation layer i.e. it shows the data to the users.
is the parts of the application that handles the display of the data.
Most often the views are created from the model data.



MVC

What is MVC?

ASP.NET MVC helps us to develop powerful and pattern-based dynamic websites that enables a clean separation of concerns and also gives you a full control on a markup. First time it was implemented by Trygve Reenskaug at 1979 and it was implemented on Smalltalk at Xerox labs. Also it includes many features that help us to develop a sophisticated and modern web application. 
Here stands for Model, stands for View and C stands for controller.