Labels

Sunday, July 7, 2019

MS - ASP.NET MVC

Here we'll talk about ASP.NET MVC, can be build either thru .NET Framework or .NET Core

Project Structure:




0). MVC Versions & Features:

  • MVC 1.0 | VS2008 |.Net 3.5 | 13-Mar-2009
    • MVC architecture with webform engine
    • Routing
    • HTML Helpers
    • Ajax Helpers
    • Auto binding
  • MVC 2.0 | VS 2008 |.Net 3.5/4.0 | 10-Mar-2010
    • Area
    • Asynchronous controller
    • Html helper methods with lambda expression
    • DataAnnotations attributes
    • Client side validation
    • Custom template
    • Scaffolding  
    • Templated Helpers  
    • Html.ValidationSummary Helper Method
    • DefaultValueAttribute in Action-Method Parameters
    • Binding Binary Data with Model Binders
    • Model-Validator Providers
    • New RequireHttpsAttribute Action Filter
    • Templated Helpers
    • Display Model-Level Errors
  • MVC 3.0 | VS 2010 | .Net 4.0 | 13-Jan-2011
    • Unobtrusive javascript validation
    • Razor view engine
    • Global filters
    • Remote validation
    • Dependency resolver for IoC
    • ViewBag
    • HTML 5 enabled templates
    • Model Validation Improvements
  • MVC 4.0 | VS 2010 - 2012 | .NET 4.0/4.5 | 15-Aug-2012 
    • Mobile project template
    • Bundling and minification
    • Support for Windows Azure SDK
    • ASP.NET Web API
    • Enhanced support for asynchronous methods
  • MVC 5.0 | VS 2013 |.NET 4.5 | 17-oct-2013
    • Authentication filters
    • Bootstrap support
    • New scaffolding items
    • ASP.Net Identity
    • Attribute based routing
    • Filter overrides
  • MVC 5.2 | VS 2013 |.NET 4.5 | 28-Aug-2014
    • Attribute based routing
    • Bug fixes and minor features update
  • MVC 6
    • ASP.NET MVC and Web API has been merged in to one.
    • Dependency injection is inbuilt and part of MVC.
    • Side by side - Deploy the runtime and framework with your application
    • Everything packaged with NuGet, Including the .NET runtime itself.
    • New JSON based project structure.
    • No need to recompile for every change. Just hit save and refresh the browser.
    • Compilation done with the new Roslyn real-time compiler.
    • vNext is Open Source via the .NET Foundation and is taking public contributions.
    • vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

1) Define Default Routing in MVC?
- This is defined in App_Start/RouteConfig.cs

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

2) Define Custom Routing in MVC to handle incoming requests that look like this: /Archive/12-25-2009
- This is defined in App_Start/RouteConfig.cs

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Blog", // Route name
url:  "Archive/{entryDate}", // URL with parameters
defaults: new { controller = "Archive", action = "Entry" } // Parameter defaults
);


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

public class ArchiveController : Controller
{
public string Entry(DateTime entryDate)
{
   return "You requested the entry from " + entryDate.ToString();
}
}


3) Define Routing Constraints in MVC ?
- In above custom route, url ‘/Archive/apple’ will produce error - Because the Entry() action expects an DateTime parameter
- To avoid this make a constraint – when defining a route to restrict the URLs that match the route.
- This constraint causes the Archive route to not to match the URL -  ‘/Archive/apple’ and so no error at runtime.

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Blog", // Route name
url:  "Archive/{entryDate}", // URL with parameters
defaults: new { controller = "Archive", action = "Entry" }, // Parameter defaults
new { entryDate = @"\d{2} - \d{2} - \d{4}" }
);


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

4). How to prevent a Public Action Method from Being Invoked
- Use [NonAction] attribute.
- Any attempt to invoke such controller action will result into an error message

namespace MvcApplication1.Controllers
{
public class BookController : Controller
{
[NonAction]
public ActionResult Index()
{
return View();           
}
}
}

5). What are different Action Results ?
- A controller action returns something called an Action Result, in response to a browser request.
- ASP.NET MVC supports several types of action results including below (inherit from the base ActionResult class)

1. ViewResult – Represents HTML and markup.
2. EmptyResult – Represents no result.
3. RedirectResult – Represents a redirection to a new URL.
4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
5. JavaScriptResult – Represents a JavaScript script.
6. ContentResult – Represents a text result.
7. FileContentResult – Represents a downloadable file (with the binary content).
8. FilePathResult – Represents a downloadable file (with a path).
9. FileStreamResult – Represents a downloadable file (with a file stream).

- In most cases, a controller action returns a ViewResult. When an action returns a ViewResult, HTML is returned to the browser.
- However the ViewResults is not returned directly. Instead, you call one of the following methods of the Controller base class to return the ViewResult.

1. View – Returns a ViewResult action result.
2. Redirect – Returns a RedirectResult action result.
3. RedirectToAction – Returns a RedirectToRouteResult action result.
4. RedirectToRoute – Returns a RedirectToRouteResult action result.
5. Json – Returns a JsonResult action result.
6. JavaScriptResult – Returns a JavaScriptResult.
7. Content – Returns a ContentResult action result.
8. File – Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.

6). What are HTML Helpers in MVC ?

- An HTML Helper is just a method that returns a string. The string can represent any type of content that you want.
- Below are few standard HTML Helpers (this is not a complete list):

- Html.ActionLink()
- Html.BeginForm()
- Html.CheckBox()
- Html.DropDownList()
- Html.EndForm()
- Html.Hidden()
- Html.ListBox()
- Html.Password()
- Html.RadioButton()
- Html.TextArea()
- Html.TextBox()


7). What are Filters in MVC ?
- The ASP.NET MVC framework supports four different types of filters:

  • Authorization filters -
    • Implements IAuthorizationFilter attribute.
    • Used to implement authentication and authorization for controller actions
  • Action filters
    • Implements  IActionFilter attribute.
    • Contain logic that is executed before and after a controller action executes.
    • You can use an action filter, for instance, to modify the view data that a controller action returns.
    • Few Action filters:
      • OutputCache – This action filter caches the output of a controller action for a specified amount of time.
      • HandleError – This action filter handles errors raised when a controller action executes.
      • Authorize – This action filter enables you to restrict access to a particular user or role.
  • Result filters
    • Implements IResultFilter attribute.
    • Contains logic that is executed before and after a view result is executed.
    • For example, you might want to modify a view result right before the view is rendered to the browser.
  • Exception filters
    • Implements IExceptionFilter attribute
    • Used to handle errors raised by either your controller actions or controller action results.
    • You also can use exception filters to log errors.


- Base class for all action filters is the System.Web.Mvc.FilterAttribute class.

  • To implement a particular type of filter, Then
    • You need to create a class that inherits from the Base Filter class (e.g. ActionFilterAttribute) and
    • Implements one or more of the IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces.



namespace MvcApplication1.ActionFilters
{
public class LogActionFilter : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
   Log("OnActionExecuting", filterContext.RouteData);     
  }

  public override void OnActionExecuted(ActionExecutedContext filterContext)
  {
   Log("OnActionExecuted", filterContext.RouteData);     
  }

  public override void OnResultExecuting(ResultExecutingContext filterContext)
  {
   Log("OnResultExecuting", filterContext.RouteData);     
  }

  public override void OnResultExecuted(ResultExecutedContext filterContext)
  {
   Log("OnResultExecuted", filterContext.RouteData);     
  }

  private void Log(string methodName, RouteData routeData)
  {
   var controllerName = routeData.Values["controller"];
   var actionName = routeData.Values["action"];
   var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
   Debug.WriteLine(message, "Action Filter Log");
  }

}
}

- Usage:
namespace MvcApplication1.Controllers
{
[LogActionFilter]
public class HomeController : Controller
{
  public ActionResult Index()
  {
   return View();
  }

  public ActionResult About()
  {
   return View();
  }
}
}














8). What is Output Caching in MVC?
- Achieved thru OutputCache Action Filter
- Uses to caches the output of a controller action for a specified amount of time.
- Cache the content returned by any controller method so same content does not need to be generated each time the same controller method is invoked.
- Reduces server round trips, reduces database server round trips, reduces network traffic, etc.


9). What is MVC Application Life Cycle?
- MVC application life cycle is not different it has two main phases, first creating the request object and second sending our response to the browser.
- Creating the request object includes four basic steps:

  • Step 1: Fill route
  • Step 2: Fetch route
  • Step 3: Request context created
  • Step 4: Controller instance created


10).Understanding the MVC Application Execution Process (C#)
- This is standard - Module Followed By Handler

  • Requests first pass thru UrlRoutingModule object, which is an HTTP module.
    • This module parses request and performs route selection. I.e Selects first Route Object that matches current request.
    •   (A route object is a class that implements RouteBase, and is typically an instance of the Route class.)  
  • From selected Route object, module obtains IRouteHandler object (MvcRouteHandler) that is associated with the Route object.
  • The IRouteHandler instance creates an IHttpHandler object (MvcHandler) and passes it the IHttpContext object.
    • This MvcHandler object then selects the controller that will ultimately handle the request.


11).What are different ways to store data like in Sessions
- ViewBag
- ViewData
- TempData


  • TempData - https://www.codeproject.com/Articles/786603/Using-TempData-in-ASP-NET-MVC
    • It's a dictionary object derived from TempDataDictionary.
    • TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request.
    • So, TempdData can be used to maintain data between controller actions as well as redirects.
    • An important thing about TempData is that it stores contents in Session object.
    • Diff With Session - TempData gets destroyed immediately after it’s used in subsequent HTTP request, so no explicit action required.


12).What is Validation Summary ? (https://www.aspsnippets.com/Articles/Display-Validation-Summary-in-ASPNet-MVC.aspx)

  • Generates an unordered list (UL element) of validation messages that are in the Model State Dictionary object.
  • Can be used to display all the error messages for all the fields.
  • Also can also be used to display custom error messages - For this you need to add custom errors into the ModelState in the appropriate action method
    • ModelState.AddModelError(string.Empty, "Student Name already exists.");
    • https://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary

 

Hope this helps...

Arun Manglick

Saturday, July 6, 2019

MS - ASP.NET WebAPI

Here we'll talk about ASP.NET WebAPI, can be build either thru .NET Framework or .NET Core

Project Structure:









































More Details:

1) What is Web API? 
WebAPI is a framework which helps you to build/develop HTTP services.
WebAPI support HTTP protocol
Web API is supported by NET 4.0 version
Web API uses JSON.NET library for JSON serialization.

2) Why is Web API required? Is it possible to use RESTful services using WCF?
  Yes, we can still develop RESTful services with WCF. However, there are two main reasons that prompt users to use Web API instead of RESTful services.
- Web API increases TDD (Test Data Driven) approach in the development of RESTful services.
- If we want to develop RESTful services in WCF, you surely need a lot of config settings, URI templates, contracts & endpoints for developing RESTful services using web API.

3) What is the benefit of using REST in Web API?
- REST is used to make fewer data transfers between client and server which make it an ideal for using it in mobile apps.
- Web API also supports HTTP protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for communication

4) What is SOAP?
- SOAP is an XML message format used in web service interactions.
- It allows to send messages over HTTP or JMS, but other transport protocols can be used.
- It is also an XML-based messaging protocol for exchanging information among computers.

4) What is the benefit of WebAPI over WCF?
 - WCF is designed to exchange standard SOAP-based messages using variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ, etc.
- On the other hand, ASP.NET Web API is a framework for building non-SOAP based services over HTTP only.
- WCF services use  SOAP protocol while HTTP never use SOAP protocol. This makes WebAPI lightweight since SOAP (XML Based) is not used.
- Being Non-XML ,reduces the data which is transferred to resume service.
- Moreover, WEBAPI never needs too much configuration like WCF.
- Therefore, the client can interact with the service by using the HTTP verbs.

4) Differences between MVC and WebAPI
- MVC framework is used for developing applications which have User Interface. For that, views can be used for building a user interface.
- WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.

4) What are the advantages of Web API?
- Support for OData
- Filters
- Content Negotiation
- Self-Hosting & IIS Hosting
- Routing
 - Model Bindings & Validation
-  Response generated in JSON or XML format using MediaTypeFormatter

4) Some New Features In ASP.NET Web API 2.0:
- Attribute Routing
- External Authentication
- CORS (Cross-Origin Resource Sharing)
- OWIN (Open Web Interface for .NET) Self Hosting
- IHttpActionResult
- Web API OData

4) What are main return types supported in Web API? 
- Void – It will return empty content
- HttpResponseMessage – It will convert the response to an HTTP message.
- IHttpActionResult – internally calls ExecuteAsync to create an HttpResponseMessage
- Other types – You can write the serialized return value into the response body

- Notes:
{
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("Testing", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};

return response;
}


5) Web API supports which protocol? HTTP

6) Which .NET framework supports Web API? - NET 4.0 and above version supports web API.

7) Web API uses which of the following open-source library for JSON serialization? - JSON.NET library for JSON serialization.

8) How Can assign alias name for ASP.NET Web API Action? 
- We can give alias name for Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:

[HttpPost]
[ActionName("SaveStudentInfo")]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}

[HttpPost]
[ActionName("SaveStudentInfo")]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}

9) How you can return View from ASP.NET Web API method?
- No, we can’t return a view from ASP.NET Web API Method.
- Web API creates HTTP services that render raw data. However, it’s also possible in ASP.NET MVC application.


10). How to register routes in WebAPI ?

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }


11). How to register Global Filters"

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}

12) What New Features comes with ASP.NET Web API 2.0?
- Attribute Routing
- Cross-Origin Resource Sharing
- External Authentication
- Open Web Interface NET
- HttpActionResult
- Web API OData

13) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?
- 500 – Internal Server Error
 - E.g.
[Route("CheckId/{id}")]
[HttpGet]
public IHttpActionResult CheckId(int id)
{
if(id > 100)
{
throw new ArgumentOutOfRangeException();
}
return Ok(id);
}





















14) What is the difference between ApiController and Controller?
- Use Controller to render your normal views.
- ApiController action only return data that is serialized and sent to the client.




























15) What is Attribute Routing in ASP.NET Web API 2.0?
- ASP.NET Web API v2 now support Attribute Routing along with convention-based approach.
- In convention-based routes, the route templates are already defined as follows:

Config.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{Controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

- But it’s really hard to support certain URI patterns using conventional routing approach like nested routes on same controller.
- For example, authors have books or customers have orders, students have courses etc.
- Such patterns can be defined using attribute routing i.e. adding an attribute to controller action as follows:

[Route("books/{bookId}/authors")]
public IEnumerable GetAuthorsByBook(int bookId) { ..... }


Quick Links:



Hope this helps.

Arun Manglick

.NET Project Types - Framework vs Core

Here is the quick difference between  two:












Hope This helps..

Arun Manglick

Wednesday, July 3, 2019

.NET Core Project Types

This is just to cover different Project Types in .NET Core.

Introduction:























Console App:












Class Library:











MS Test Project:




xUnit Test Project:












ASP.NET Core Web Application:






























A). Empty - ASP.NET Core Web Application


























B). API - ASP.NET Core Web Application

























C). Web Application - ASP.NET Core Web Application




D). Web Application (MVC- ASP.NET Core Web Application






E). Razor Class Library - ASP.NET Core Web Application

















F). Angular - ASP.NET Core Web Application



F). React.js - ASP.NET Core Web Application



F). React & Redux - ASP.NET Core Web Application




 Hope this helps...

Arun Manglick