Tuesday 27 December 2016

Different methods used to render the views and Partial views in ASP.Net MVC


1. RenderPartial  - RenderPartial method is useful when the displaying data in the partial view is already in the corresponding view model.
@{Html.RenderPartial("_partialView");}
This method returns void. And simple to use and no need to create any action.
This method is faster than Partial method since its result is directly written to the response stream which makes it fast.

2. Partial - Like RenderPartial method, Partial method is also useful when the displaying data in the partial view is already in the corresponding view model.
@Html.Partial("_partialView")
Simple to use and no need to create any action.This method result can be stored in a variable, since it returns string type value.
Renders the partial view as an HTML-encoded string.

3. RenderAction - RenderAction method is useful when the displaying data in the partial view is independent from corresponding view model.
@{Html.RenderAction("Action_Name","Controller-Name");}
For this method, we need to create a child action for the rendering the partial view.
This method is the best choice when you want to cache a partial view.
This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast.

4. Action - Action method is useful when the displaying data in the partial view is independent from corresponding view model.
@Html.Action("Action_Name","Controller-Name");
For this method, we need to create a child action for the rendering the partial view.This method result can be stored in a variable, since it returns string type value.
Renders the partial view as an HtmlString .

This method is also the best choice when you want to cache a partial view.

5. Direct return from Controller 


public ActionResult Action()
        {
            return PartialView("PartialViewName");
OR
            return View("ViewName");

        }

For More check Views Partial Views

Saturday 24 December 2016

What is Caching? Explain Output Cache.

Caching is a most important aspect of high-performance web application. Caching provides a way of storing frequently accessed data and reusing that data. Practically, this is an effective way for improving web application’s performance.
Output Cache can dramatically improve the performance of an ASP.NET MVC application. The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked.
The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made to this action then ASP.NET MVC will cache the output again.
Enabling Output Caching
You enable output caching by adding an [OutputCache] attribute to either an individual controller action or an entire controller class as below.
[OutputCache(Duration=10, VaryByParam="none")]
        public ActionResult Index()
        {
            return View();
        }
Output Caching Location
By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You can control the content's cached location by changing the location parameter of the OutputCache attribute to any of the following values: 
  • Any (Default): Content is cached in three locations: the web server, any proxy servers, and the web browser.
  • Client: Content is cached on the web browser.
  • Server: Content is cached on the web server.
  • ServerAndClient: Content is cached on the web server and and the web browser.
  • None: Content is not cached anywhere.
[OutputCache(Duration=3600, VaryByParam="none", Location=OutputCacheLocation.Client, NoStore=true)]
        public string GetName()
        {
            return "Hi " + User.Identity.Name;
        }
Varying the Output Cache
In some situations, you might want different cached versions of the very same content, So for that we use "VaryByParam" as in above code.
In case we have multiple action methods across controllers needing the same caching behavior, we can put this caching values in the web.config and create a cacheprofile for it.
<caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="MyCacheProfile"
               duration="30"
               varyByParam="id"
               location="Any" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
And to use these values in the action methods we just need to specify the CacheProfile name in the action method.
[OutputCache(CacheProfile = "MyCacheProfile")]
public ActionResult Dummy()
{  
    return View();
}
For more Cache MSDN Cache

Monday 19 December 2016

Different techniques to handle Exceptions in ASP.NET MVC


There are many ways to handle exceptions. We will discuss here some of them.

1. Try - Catch Block


public ActionResult SomeError()
{
try
{}
catch(Exception ex)
{return View("Error");}
}

2. By Overriding 'OnException' method.

In this we override the 'OnException' method of controller and specify error page.
public class HomeController : Controller
 {
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

     var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

     filterContext.Result = new ViewResult()
{
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
     };

        }
}
and in view we have to use
@Model.Exception;

but this way does not provide code re-usability across multiple controllers.

3. HandleError Attribute

1. we put this attribute on action in controller as below.
public class HomeController : Controller
 {
        [HandleError()]
        public ActionResult SomeError()
        {
            throw new Exception("test");
        }
}
2. Add custom error code in web config.
<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web> 

If you want different views for different exception types then modify 'HandleError' attribute as below.
public class HomeController : Controller
{
[HandleError(ExceptionType=typeof(ArithmeticException),View="Arthimetic")]
[HandleError(ExceptionType = typeof(NotImplementedException),View ="Error1")]
public ActionResult SomeError()
{
    
}
}

4. Create separate class Inheriting from 'ErrorHandleAttribute'.

In this way we can use code re-usability concept across all controller. we create separate class that inherit from 'ErrorHandleAttribute' class and then we use this 'Errorclass' as an Attribute for Actions in controllers.
public class ErrorClass : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error1",
                ViewData = new ViewDataDictionary(model)
            };
        }
    }

5. Handling Http Errors

There are many error like 'FileNotFound', Http 500 error etc . for these we use customer error in web config.
<system.web>
<customErrors
                  mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.web> 

6. Global Error handling 
We write code in Global.asax file in Application_Error event.
protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/Home/Error");
        }


Important links for .NET Core


I am providing some important links for .NET Core as below.

.NET Core  - .NET Core

Official release of .NET Core -  Official release

GitHub Repository  - GitHub dotnet core

ASP.NET Core  - ASP.NET Core

ASP.NET Core Tutorial - Tutorial

.NET Core Rad-map - Road Map

.NET Core Api - Core api

What is .NET Core and it's characteristics?

.NET Core - 

.NET Core is a general purpose, modular, cross-platform and open source implementation of the .NET Platform. It contains many of the same APIs as the .NET Framework (but .NET Core is a smaller set) and includes run-time, framework, compiler and tools components that support a variety of operating systems and chip targets. The .NET Core implementation was primarily driven by the ASP.NET Core workloads but also by the need and desire to have a more modern run-time. It can be used in device, cloud and embedded/IoT scenarios.

.NET Core has following main characteristics.
1. Cross-Plateform - .NET Core provides key functionality to implement the app features you need and reuse this code regardless of your platform target.
2. Open Source -  Having .NET Core as an open source project promotes a more transparent development process and is available on GitHub.
3. Flexible Deployment - there are two main ways to deploy your app: framework-dependent deployment or self-contained deployment. With framework-dependent deployment, only your app and third-party dependencies are installed and your app depends on a system-wide version of .NET Core to be present. With self-contained deployment, the .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions. For more information, see .NET Core Application Deployment.
4. Modular - Modular means collection of small modules so .NET Core is modular because it is released through NuGet in smaller assembly packages. Rather than one large assembly that contains most of the core functionality, .NET Core is made available as smaller feature-centric packages. This enables a more agile development model for us and allows you to optimize your app to include just the NuGet packages you need. The benefits of a smaller app surface area include tighter security, reduced servicing, improved performance, and decreased costs in a pay-for-what-you-use model.
5. Compatible - .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.

For More refer DotNet Core  .NET Core


Monday 12 December 2016

$apply, $watch, $digest methods in AngularJS

There are many methods in AngularJs some of them are give below.
$watch - Registers a listener callback to be executed whenever the watchExpression changes.
The watchExpression is called on every call to $digest() and should return the value that will be watched. (watchExpressionshould not change its value when executed multiple times with the same input because it may be executed multiple times by $digest().
The listener is called only when the value from the current watchExpression and the previous call to watchExpression are not equal. example - 
scope.$watch('name', function(newValue, oldValue) {
  scope.counter = scope.counter + 1;
});
$watchgroup - A variant of $watch() where it watches an array of watchExpressions. If any one expression in the collection changes the listener is executed.
$apply - $apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handlingexecuting watches.
function $apply(expr) {
  try {
    return $eval(expr);
  } catch (e) {
    $exceptionHandler(e);
  } finally {
    $root.$digest();
  }
}
Scope's $apply() method transitions through the following stages:

  1. The expression is executed using the $eval() method.
  2. Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
  3. The watch listeners are fired immediately after the expression was executed using the $digest() method.
$digest - Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest()keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10.
Usually, you don't call $digest() directly in controllers or in directives. Instead, you should call $apply() (typically from within a directive), which will force a $digest().
var scope = ...;
scope.name = 'misko';
scope.counter = 0;

expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
  scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);

scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);

scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);

scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
$destroy - Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop.
$eval - Executes the expression on the current scope and returns the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating Angular expressions.
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;

expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
$evalAsync- Executes the expression on the current scope at a later point in time.
The $evalAsync makes no guarantees as to when the expression will be executed, only that:
  • it will execute after the function that scheduled the evaluation (preferably before DOM rendering).
  • at least one $digest cycle will be performed after expression execution.

For other methods click  $digest $eval $destry, $apply etc