Showing posts with label error. Show all posts
Showing posts with label error. Show all posts

Getting ASP.NET MVC action exception message on jQuery $.ajax fail error callback

While testing an app I came across an error: I passed a string parameter to an action method responsible for loading an existing object by name on the database side. The problem is that there was no such object on the database. To make things even more difficult to handle this action method returns a PartialView that gets loaded in the view side using jQuery $.ajax. So how and what should I return to the caller if an exception happens while processing the request inside that action method? That’s a good question.

I tried something like this:

public ActionResult SubCatList(string subcat)
{
    var sub = Database.GetLogSubCategory(subcat);

    if(sub == null)
    {
        throw new EntryNotFoundException(String.Format("SubCategory {0} does not exist", subcat));
    }

    var subcatItems = Database.GetListItemsForSubCategory(sub);

    return PartialView(subcatItems);
}

My intention was to get that beautiful formatted exception message inside $.ajax fail callback using the error parameter like this:

$.ajax({
        url: '/api/subcatlist/subcatlist?subcat=' + subcat,
        type: 'GET',
        cache: false,
        success: function(html)
        {
            $("body").prepend(html);

// Do something more here...
} }).fail(function(xhr, textStatus, error) { displayMessage(error, 'danger'); }); }

This definitely DOES NOT WORK out of the box! So what’s the problem? The problem is that when checking/debugging the JavaScript using Firebug or Google Chrome,  the error parameter is set with a default IIS error message: Internal Server Error for the standard 500 error code. The exception message gets populated inside the xhr parameter instead in the middle of the standard page’s HTML code used by IIS.

Looking around I found something that could help in this case:

Handling Exceptions using jQuery and ASP.NET MVC

Improving the code shared on the above post, the basic idea is to have a common JsonResult action method in a BaseController for example that sets the Response.StatusDescription directly like this:

public JsonResult ThrowJsonError(Exception e)
{
    Logger.Error(e.Message, e);

    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
    Response.StatusDescription = e.Message;

    return Json(new { Message = e.Message }, JsonRequestBehavior.AllowGet);
}

Now let’s use this beauty:

public ActionResult SubCatList(string subcat)
{
    var sub = Database.GetLogSubCategory(subcat);

    if(sub == null)
    {
        return ThrowJsonError(
            new EntryNotFoundException(String.Format("SubCategory {0} does not exist", subcat)));
    }

    var subcatItems = Database.GetListItemsForSubCategory(sub);

    return PartialView(subcatItems);
}

Now that beautiful formatted exception message is populated in the error parameter in $.ajax fail callback.

Objective achieved! Hope it’s useful it the future. Happy coding and 2014 for everyone…

Debugging Microsoft Web Deploy Visual Studio publishing errors

This post is intended for starters with MS Web Deploy as is my case… Shifty

Microsoft Web Deploy is so awesome that I think it’s one of the best features one has at their disposal when developing with the .NET Framework and for the Web with ASP.NET MVC for example. It’s so powerful that it can even publish a database.

Once upon a time (let’s say before 2010) there was no Web Deploy and you had to FTP to the server to deploy the application. This was a tiresome task and led to many errors because one had to be extremely careful of what files needed to be updated, added, removed, etc while installing the application on the server. Backup methods should be in place in case something went wrong. I used to use compressed files (.zip or .rar) to send the app’s files to the server. It was still a big upload in some cases. I had to wait patiently. Once there I had to uncompress the file. Everything needed to be moved into place to make things easier. I even created a step by step readme file to help other peers do the deploy on the server. This readme detailed the workflow that should be followed in order to get things working.

Thanks God today there’s Web Deploy and it changed things drastically: only new or updated files are uploaded to the server. No more long waiting periods to start using the application. As a bonus you also have the option of removing additional files on the server (files/folders that aren’t used anymore). All this happens automatically (could we say automagically) with the click of a button inside Visual Studio 2010 or 2012. You can also run a .cmd file in the command line. This .cmd file is created as part of the Web Deploy Package publish method that you can choose once inside Visual Studio. There’s so many awesome features (read Preview menu option in Figure 4 bellow) that they would not fit in this post… To get a full understanding about Web Deploy look at this post: Visual Studio 2012 RC Deployment Docs.

Well, 2 weeks ago I tried to solve a problem related to Web Deploy. You can read the full history here:

Visual Studio 2012 Web Deploy to Windows Server 2008 R2 with IIS 7 and /msdeploy.axd 404 error

The above problem wasn’t solved but I can tell you that I learned a LOT about IIS administration during that weekend. As a result it was worth the effort. I think that a clean install of Windows Server 2008 is necessary in that case…

Today I was facing a different error (again working against Windows Server 2008 R2) and I followed a simple path to solve it. So here are the basic steps you need to follow to detect the problem’s origin:

Visual Studio 2012 Publish project with Web Deploy and Validate Connection errorFigure 1 - Visual Studio 2012 Publish project with Web Deploy and Validate Connection error

As you see when I clicked the Validate Connection button I got a message: ERROR COULD NOT CONNECT TO REMOTESVC.

If you click the error message, there’s some more info about the error but it doesn’t really tell you what’s causing the problem.  It’s kind of a generic message you get: go check the Web Management Service on your server… I think I don’t need to tell you that it’s started already! Steaming mad

Figure 2 - Visual Studio 2012 Publish project with detailed ERROR informationFigure 2 - Visual Studio 2012 Publish project with “detailed” ERROR information

To really get to the problem, you’ll need to access the server you’re trying to deploy to. Once there go to this folder:

C:\inetpub\logs\wmsvc\W3SVC1

This is the standard path where Web Management Service logs what’s going on…

When I opened the latest .log file I saw this:

#Software: Microsoft Internet Information Services 7.5
#Version: 1.0
#Date: 2012-07-26 15:50:30
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-status time-taken
2012-07-26 12:50:30 192.168.100.77 HEAD /msdeploy.axd site=Default%20Web%20Siste 8172 - 189.24.83.277 - 401 2 5 1918
2012-07-26 12:50:33 192.168.100.77 HEAD /msdeploy.axd site=Default%20Web%20Siste 8172 develop
189.24.83.277 - 550 0 0 2761

As you see highlighted in orange is my developer machine IP address. This let’s me know that my connection to server is working as expected. Port 8172 is not blocked by the firewall, etc.
Highlighted in yellow is a sc-status = 550. This is the key part while debugging errors related to web deploy on the server. Now it’s far easier to know what’s the problem. It’s only a matter of Googling about the 550 status code. The first post that mentions this status code was this one:

Status code 550 when using Msdeploy

The guy lost 1 day to find what was going on and it took me only 1 minute to figure out the error I had with his help. He talks about the site’s name displayed in IIS manager. So I went check mine and to my surprise I had a small mistake in the Site/application name field shown in Figure 1. I typed Default Web Siste instead of only Default Web Site. What a silly mistake!

This is the kind of error that can bother you more than it should… believe it or not. You can go the wrong way while trying to get things working as expected.

After correcting this mistyped named I clicked the Validate Connection button again and to my delight and surprise I got this beautiful green check mark:

Visual Studio 2012 Publish project with Web Deploy and successful connection validationFigure 3 - Visual Studio 2012 Publish project with Web Deploy and successful connection validation

Now if you desire select the Preview menu option to glance at what’s going to the server…

Visual Studio 2012 Publish project with Web Deploy and Previewing the changes
Figure 4 - Visual Studio 2012 Publish project with Web Deploy and Previewing the changes

You can select just the files you want to deploy. This is super useful let’s say when you discover a bug in production and want to change something in whatever file to correct that bug. You already have more changes to pull to the server but you just want to correct that bug. With the Preview tab you can do this: select just the file(s) you changed to correct the bug and deselect all the others. Isn’t this awesome? Of course it is!

If it’s OK, just hit the Publish button and you’re good to go.

I hope this simple post helps you find the root cause of what’s causing errors while you’re trying to deploy your application using MS Deploy.

References
Configuring a Web Server for Web Deploy Publishing (Remote Agent)

Installing and Configuring Web Deploy

Web Deploy error codes