October 29, 2013

Lesson From Frog

Human Beings and frogs are the two creatures in nature who have tremendous power to adjust. Put a frog in a vessel of water and start heating the water. As the temperature of the water rises, the frog is able to adjust its body temperature accordingly. The frog keeps on adjusting with increase in temperature. Just when the water is about to reach boiling point, the frog is not able to adjust anymore. At that point the frog decides to jump out. The frog tries to jump but is unable to do so, because it lost all its strength in adjusting with the water temperature. Very soon the frog dies.

What killed the frog? Many of us would say the boiling water.

But the truth is what killed the frog was its own inability to decide when it had to jump out.

We all need to adjust with people and situations, but we need to be sure when we need to adjust and when we need to face. There are times when we need to face the situation and take the appropriate action.

If we allow people to exploit us physically, emotionally or financially, they will continue to do so. We have to decide when to jump. Let us jump while we still have the strength!

October 25, 2013

6 Ways To Handle The Exceptions In Asp.Net MVC 4

Handling exceptions and presenting them to the user in appropriate way instead of default error message is best approach to tell end user "What to do when it happen?"

I found several ways to handle errors but I'm posting the popular ones.

1. Redirect to Custom Error - Simplest Approach

In try..catch block, if you want to redirect to custom error page on the basis of specific conditions you can use HandleErrorInfo class to do so. Example is

// Define variable of type Exception & HandleErrorInfo Exception exception; HandleErrorInfo errorInfo; // Do something like you filter the Client with Id // And clientPresent is a variable which hold Client data which // is use futher to insert its Customers if (clientPresent != null) { // Add its Customer } else { exception = new Exception("Unable to recognize the Client!"); errorInfo = new HandleErrorInfo(exception, "Home", "Index"); return View("Error", errorInfo); }

In above code, you define the appropriate message, add it to HandleErrorInfo class. HandleErrorInfo class contains three parameters.
  • Exception           : Custom format of message
  • Controller Name  : Where this exception raise
  • Action Name       : Action name contains exception

2. Writing try..catch

A classic approach to catch any exception. You use this inside the controller code and handle the exceptions that may occur. Here the only thing you have to take into account is what is the controller action is returning. Here you have two approaches & choose one to follow. First approach is "If you return a view, when you catch an exception you should redirect to an error page." is define above and second approach is "when you return JSON you should return a JSON with the exception message and handle it on the client side" is define here:

public ActionResult Index() { try { //Do stuff here } catch (Exception e) { //Redirect to an error page Response.Redirect("URL to the errror page"); } return View(); } public JsonResult GetJson() { try { } catch (Exception e) { //Return the exception message as JSON return Json(new { error = e.Message }); } return Json("Return data here"); }

The main disadvantage of this approach is that you have to use it everywhere and you bloat the code.

3. Override OnException method inside the Controller

You can handle all the exceptions inside a controller is by overriding the OnExeception method. With this approach you code only one exception handling routine per

Controller and you don`t bloat the code. Example is:

protected override void OnException(ExceptionContext filterContext) { //If the exeption is already handled we do nothing if (filterContext.ExceptionHandled) { return; } else { //Determine the return type of the action string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType(); var method = controllerType.GetMethod(actionName); var returnType = method.ReturnType; //If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { filterContext.Result = new JsonResult() { Data = "Return data here" }; } //If the action that generated the exception returns a view if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { filterContext.Result = new ViewResult() { ViewName = "URL to the errror page" }; } } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; }

But same disadvantage that you have to override the OnExecption method inside every controller it`s not the best approach. You need to react in a different way if your exception throwing action returns a view or returns JSON. Also, you have to make sure that you specify that the exception was handled. Skipping this will throw the exception further.

4. Using the HandleError attribute

You can use HandleError attribute. When you provide this attribute to your controller class or to your action method, when an unhandled exception is encountered MVC will look first for a corresponding view named Error in the controller`s view folder. If it can`t find it there, it will look inside the shared view folder and redirect to that view.

[HandleError] public ActionResult Index() { return View(); }

You can also filter the type of error you want to handle

[HandleError(ExceptionType = typeof(SqlException))] public ActionResult Index() { return View(); }

5. Extending the HandleError attribute

You can code your own logic to handle errors using attributes. All you have to do is to extend the existing HandleErrorAttribute and override the OnException method. All you need to create a custom HandleErrorAttribute using the logic mentioned above.

public class HandleCustomError : System.Web.Mvc.HandleErrorAttribute { public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //If the exeption is already handled we do nothing if (filterContext.ExceptionHandled) { return; } else { //Determine the return type of the action string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType() ; var method = controllerType.GetMethod(actionName); var returnType = method.ReturnType; //If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { filterContext.Result = new JsonResult() { Data = "Return data here" }; } //If the action that generated the exception returns a view //Thank you Sumesh for the comment if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { filterContext.Result = new ViewResult { ViewName = "URL to the errror page" }; } } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; } }

You use this custom implementation like this

[HandleCustomError] public ActionResult Index() { return View(); }

6. Handle all errors inside Global.asax

This method uses a global error handling that captures all exceptions into a single point. The only problem is to determine if we have to return a view or some JSON in case of AJAX request. Included in the snippet below there is a method that uses reflection to do all this.

public class MvcApplication : System.Web.HttpApplication { void Application_Error(object sender, EventArgs e) { //We clear the response Response.Clear(); //We check if we have an AJAX request and return JSON in this case if (IsAjaxRequest()) { Response.Write("Your JSON here"); } else { //We don`t have an AJAX request, redirect to an error page Response.Redirect("Your error page URL here"); } //We clear the error Server.ClearError(); } //This method checks if we have an AJAX request or not private bool IsAjaxRequest() { //The easy way bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest") || ((Request.Headers != null) && (Request.Headers["X-Requested-With"] == "XMLHttpRequest")); //If we are not sure that we have an AJAX request or that we have to return JSON //we fall back to Reflection if (!isAjaxRequest) { try { //The controller and action string controllerName = Request.RequestContext. RouteData.Values["controller"].ToString(); string actionName = Request.RequestContext. RouteData.Values["action"].ToString(); //We create a controller instance DefaultControllerFactory controllerFactory = new DefaultControllerFactory(); Controller controller = controllerFactory.CreateController( Request.RequestContext, controllerName) as Controller; //We get the controller actions ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); ActionDescriptor[] controllerActions = controllerDescriptor.GetCanonicalActions(); //We search for our action foreach (ReflectedActionDescriptor actionDescriptor in controllerActions) { if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper())) { //If the action returns JsonResult then we have an AJAX request if (actionDescriptor.MethodInfo.ReturnType .Equals(typeof(JsonResult))) return true; } } } catch { } } return isAjaxRequest; } //snip }

Hope you understand every approach clearly. You can use any of them which well suite you.

October 24, 2013

The Interview Question That Reveals a Born Leader

Today, I read an article of MARC BARROS, the co-founder and former CEO of Contour, a hands-free camera company. He enlighten the criteria to pick up the great leader. I really inspire with Marc's post. 

If you are the CEO of your/any organization, then building a great leadership team is one of your most important job. But it can also be the hardest one.

He said:

What makes it so hard is that you not only have to find a domain expert but a strong leader who inspires results far beyond your team's abilities. More confusing is the fact that most experienced domain experts are often terrible leaders, while great leaders often have resumes that won't make it past your screening process.

And today's hiring process doesn't make things easier. Sites like LinkedIn feature inflated resumes, making it hard to tell how much value the candidate brought his previous employer. Legal barriers prevent references from spilling the beans, forcing employers to read between the lines. Studies show that 30 to 40 percent of executive hires don't make it past the 18 month mark, which might feel like a failure to some CEOs given how painful it is to remove an executive.

So how can you find the right leader? Well, you can start by asking one simple question, "Tell me about the last person you fired." Of all the ways I interviewed executive candidates, this question and the discussion that followed proved to be the strongest indicator of the candidate's leadership ability.

If he says, "I haven't fired anyone," it's obvious this person's a bad fit. You can't build a great team without occasionally deconstructing and rebuilding it. And while every leader makes mistakes, if he can't admit, correct, or move on from them, you don't want him or her at your start-up.

If the candidate did fire someone, then find out how it happened. As the story unfolds you will learn something key: how well he or she communicates. If he says the candidate was surprised, find out why. More likely than not, he did a poor job of communicating where the employee stood, which is hard to do, but awfully necessary.

If he says the candidate wasn't surprised, let him walk you through the termination process. Great leaders are often like coaches, providing consistent and honest feedback. Do you find the candidate fits this description?

Be sure to find out why the employee didn't work out. Explore what mistakes were made in the hiring process and how they fixed those mistakes afterward. You want a self-reflective leader who is constantly evaluating himself as well as his processes.

Before the story is finished, ask one final question, "What did you do after they were let go?" This will show you their level of empathy. Average leaders tend to do the bare minimum, offering severance and a positive reference. But great leaders often do what they can to help the ex-employee get back on her feet. 

Pay attention to body language, as you want leaders who make quick decisions and follow through. At the same time you don't want a robot, so if he shows no emotion, think twice about hiring. That's not to say leading without emotion is a bad thing, but it certainly isn't for everyone.

Regardless of the process you use to build teams, you should spend as much time talking about what went wrong as well as the things that went right. Finding great leaders is incredibly hard, but if you find some, they will help your company experience incredible success.

October 8, 2013

Getting Started with ASP.NET MVC 5

Start by installing and running Visual Studio Express 2013 RC for Web or Visual Studio 2013 RC. Visual Studio is an IDE, or integrated development environment. Just like you use Microsoft Word to write documents, you'll use an IDE to create applications. 

In Visual Studio there's a tool bar along the top showing various options available to you. There's also a menu that provides another way to perform tasks in the IDE. (For example, instead of selecting New Project from the Start page, you can use the menu and select File > New Project.)


Creating Your First Application

You can create applications using either Visual Basic or Visual C# as the programming language. Click New Project, then select Visual C# on the left, then Web and then select ASP.NET  Web Application. Name your project "MvcMovie" and then click OK.



In the New ASP.NET Project dialog, click MVC and then click Create Project.



Click OK. Visual Studio used a default template for the ASP.NET MVC project you just created, so you have a working application right now without doing anything! This is a simple "Hello World!" project, and it's a good place to start your application.



Click F5 to start debugging. F5 causes Visual Studio to start IIS Express and run your web application. Visual Studio then launches a browser and opens the application's home page. Notice that the address bar of the browser says localhost and not something like example.com. That's because localhost always points to your own local computer, which in this case is running the application you just built. When Visual Studio runs a web project, a random port is used for the web server. In the image below, the port number is 1234. When you run the application, you'll see a different port number.



Right out of the box this default template gives you  Home, Contact and About pages. The image above doesn't show the Home, About and Contact links. Depending on the size of your browser window, you might need to click the navigation icon to see these links.




Stay tune :)

Asp.Net and Web Tools for Visual Studio 2013 RC Enhancements

Microsoft provides the new features of the ASP.NET and Web Tools for Visual Studio 2013 RC. Click here to download and install the Visual Studio 2013 RC today. Please check for release notes, documentation, and tutorials. This post includes both the new RC features and the features that already announced in the ASP.NET and Web Tools for VS 2013.

Visual Studio Web Tooling Enhancements

1. One ASP.NET

Visual Studio team made a simple UI for creating projects that offer support for multiple ASP.NET frameworks (Web Forms, MVC, and Web API). New features are available for Web Forms that used to be offered only for MVC, such as automatic test project creation different authentication configurations.



Different authentication configurations can be chosen, and authentication works the same in all ASP.NET frameworks and in web hosting software other than IIS.

All of the ASP.NET project templates now use use Bootstrap to provide responsive design and theming capabilities. The Single Page Application template has been updated with support for OAuth 2.0 and a Web API based account controller that can be used from JavaScript and also from native mobile applications.

For more information about the new process for creating web projects, see Creating ASP.NET Web Projects in Visual Studio 2013 RC.

2. Browser Link – SignalR channel between browser and Visual Studio

A new feature, Browser Link, uses a SignalR channel between browsers and Visual Studio 2013 RC. It allows manually refreshing all connected browsers by clicking the toolbar refresh button. You can connect multiple browsers to your development site, including mobile emulators, and click refresh to refresh all the browsers all at the same time. In RC, we also introduced Browser Link Dashboard where you can refresh individual browser. You enable the Browser Link Dashboard from the refresh icon as shown in the following image:


Team also released API to write browser link extensions. Mads’ web essentials for Visual Studio 2013 (source) contains a few extensions that one can find really useful.


In the Browser Link Dashboard, you can see each active connection listed under the Connections node. You can use the down arrow for each browser to choose a task, such as refresh each individual browser manually, or manual actions with the extensions that you’ve installed, such as “Design Mode”, “Inspect Mode”, “Snapshot Page”, “Start Recording” web essential extension commands.


The Problems node lists the possible reasons why the browser link might not work and offers suggestions to correct the problem.

3. New HTML editor

In VS2013 RC, a new HTML editor is released for Razor files and HTML files. Web Forms .aspx, .master and user control .ascx files are still using the legacy editor for various reasons. The new HTML editor provides a single unified HTML5-based schema. It has some improvement such as automatic brace completion, jQueryUI and AngularJS attribute IntelliSense, attribute IntelliSense Grouping etc. In RC, team makes CSS class attribute intelliSense working even if bundling and minification is used.


The Tools\Options\Text Editors settings are different for legacy and new HTML editors. They are named “HTML” (for HTML files, Razor files, and Windows 8 Modern JavaScript apps) and “HTML (Web Form)” (for Web Forms files) respectively.



4. Azure website tooling with Azure SDK 2.1

With installation of Azure SDK 2.1, you can create Windows Azure web sites from VS2013 RC’s server explorer.



You can easily configure the website, add a new Web Site, and import the subscription file (which is used to publish to Windows Azure from the Visual Studio).

5. Scaffolding

VS 2013 RC has completely rewritten MVC Scaffolding. Please visit here for more information.


team removed WebForm Scaffolding from this release because it's not ready yet. We’ll put the new bits in future release, possibly targeting update 1.

6. ASP.NET Framework Enhancements

a. ASP.NET MVC 5

MVC projects are now standard Web Applications and do not use their own project GUID. An MVC 5 project is created if the MVC checkbox is checked in the One ASP.NET new project dialog. For more information see Getting Started with ASP.NET MVC 5.

b. ASP.NET Web API 2

ASP.NET Web API 2 includes a variety of new features including:
  • Attribute routing
  • OData improvements
  • Request batching
  • Improved unit testability
  • CORS
  • Support for portable libraries
  • OWIN integration.

For details on ASP.NET Web API 2 features, please see the RC release notes or refer to the ASP.NET Web API 2 documentation here.

c. ASP.NET SignalR

SignalR 2.0.0-rc1 is included with VS2013 RC. It includes support for MonoTouch and MonoDroid, portable .NET client, and the self-hosting package Microsoft.AspNet.SignalR.SelfHost, and it is backwards compatible for servers. For more SignalR 2.0.0-rc1 release notes, please visit.

d. Entity Framework

Entity Framework 6.0.0-rc1 is included with VS2013 RC. See for detail.

e. Microsoft OWIN Components

The Microsoft OWIN components (also known as the Katana project) integrates support for the Open Web Interface for .NET (OWIN), deep into ASP.NET. OWIN defines a standard interface between .NET web servers and web applications. Any OWIN based application or middleware can run on any OWIN capable host, including ASP.NET on IIS.

You host OWIN-based middleware and frameworks in ASP.NET using the Microsoft.Owin.Host.System Web NuGet package. The Microsoft.Owin.Host.System Web package has been enhanced to enable an OWIN middleware developer to provide hints to the System Web server if the middleware needs to be called during a specific ASP.NET pipeline stage (ex during the authentication stage). The Microsoft OWIN Components also includes an HttpListener-based server, a self-host API and an OwinHost executable for running OWIN applications without having to create a custom host. With the OwinHost 2.0.0-rc1 NuGet package, VS2012 RC can now easily convert an IIS Express based WebAPI or SignalR project to a project that is run from OwinHost.exe.


ASP.NET authentication is now based on OWIN middleware that can be used on any OWIN-based host. Microsoft OWIN Components includes a rich set of middleware components for authentication including support for cookie-based authentication, logins using external identity providers (like Microsoft Accounts, Facebook, Google, Twitter), and logins using organizational accounts from your on-premise Active Directory or Windows Azure Active Directory. Also included is support for OAuth 2.0, JWT and CORS. For more information see An Overview of Project Katana.

f. ASP.NET Identity

ASP.NET Identity is the new membership system for building ASP.NET applications. ASP.NET Identity makes it easy to integrate user specific profile data with the application data. With ASP.NET Identity you control the persistence model of your application. For example, you can store your user data in a SQL Server database or any other persistence store.

For information about using ASP.NET Identity with Individual User Accounts authentication, see.

g. NuGet

NuGet 2.7 is included with VS2013 RC. See.

7. Summary

Today’s Visual Studio 2013 RC has a lot of useful features for developers using ASP.NET. Read the release notes to learn even more, and install it today! Stay tune:)