IIS, Visual Studio, unable to start debugging on the web server.

Background

So this is another logging this issue after some frustrating problem sovling process. This is to help future me when I forget the same windows configuration step in another 8-15 months, maybe it’ll help you too.

On Windows 8 you have go in and turn on many individual items to just get an ASP.NET IIS hosted web app running, I’ve a variation of this problem in the past and blogged about it.

This time round it’s basically the same problem, but with Visual Studio upon trying to spin up and attach to an IIS hosted web project kicks up 1 of 3 errors.

Issue

The most common one was:

Unable to start debugging on the web server. The debugger cannot connect to the remote computer. The debugger was unable to resolve the specified computer name.

Which is not helpful, and the posts I found were people trying to remote debug machines or some thing else not helpful.

Unable to start debugging on the web server

Other variations included:

… error occured on a send

Unable to start debugging on the web server.

If you dig further into the windows event store you’ll be sent down an even further wrong path with errors such as:

The program can’t start because SecRuntime.dll is missing from your computer. Try reinstalling the program to fix this problem.

Solution

Ensure that you turn on ‘Internet Information Services Hostable Web Core’ along with all the other .NET / IIS feautes you need that I mentioned in the previous post.

Windows Features

Advertisements

HTTP Error 500.19 – Internal Server Error with ASP.NET web on Windows 8 and IIS 8

I’m blogging this (again*) so next time I do a search I find my own post, it may also help you. I manage a few development VMs which I swear I have setup in the past correctly, but every so often I find one that’s got the following problem.

*Again: it’s in an older post in the trouble shooting part, but this time, the error is the title of the post to help indexing, as when I searched this time around, that post did not come up.

Scenario / Error

Windows 8 + IIS launching your ASP.NET web app, you get the following IIS error:

HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Error Code 0x80070021
Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=”Deny”), or set explicitly by a location tag with overrideMode=”Deny” or the legacy allowOverride=”false”.

Note the ‘locked at a parent level’, in the config error.

Solution

Turn on the Application Development Features. If they’re already on, then you have a different problem, there’s a few questions about ASP.NET IIS and 500.19 on Stack Overflow.

Enable IIS 8 App Dev Features

Hope this helps.

Cross subdomain ASP.NET Forms Authentication for local developement

I’ve had this issue twice now, and both times when I did my search I would end up this popular Stack Overflow question but adding an answer to a popular question that doesn’t directly* answer the question will get the attention of down vote police.

*For some values of direct.

So I’ll just have to blog it here, and maybe the comment will help someone out who is likely to end up on that question, at least until the comment is flagged as unconstructive or offensive because “somewhat related” isn’t in the spirit of StackOverflow.

So with the grievance aired.

Objective

To be able to have subdomain1.machine-name and subdomain2.machine-name share a cookie locally via forms authentication.

Steps

To go about achieving the saving of an authentication cookie valid across multiple domains locally under IIS.

Configurations

The most important thing here is to ensure that your local domain has at least ‘.’ in it. I often try to just have it be the machine name, this does not work, so I select something like the .app suffix.

Authentication configuration section in web.config:

   <authentication mode="Forms">
      <forms loginUrl="~/login" timeout="2880" domain="pic-nick.app" />
   </authentication>

IIS Setup

Will look like this:

iis settings

HOSTS File

hosts file

Done

There we go, with this set up you can go to red. and blue. and have it share the authentication cookie to be logged into your app across sub domains locally.

dashbaord blue

Troubleshooting

I also ran into some extra issues on Windows 8 similar to this StackOverflow question.

Exception from IIS:

HTTP Error 500.19 – Internal Server Error

The requested page cannon be access because the related configuration data for this page is invalid.


This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=”Deny”), or set explicitly by a location tag with overrideMode=”Deny” or the legacy allowOverride=”false.

To solve this you need to probably enable some Windows Features related to Security and .NET.

features toggle pointing

When you need to generate and send templated emails, consider mailzor

Mailzor is a basic utility library to help generate and send emails using the Razor view engine to populate email templates, designed to be quickly pluggable into your .NET app.

In our applications we send out HTML formatted emails, and seed them with a variety of data. I thought it would be easy to write them as razor files (cshtml) and then use the razor engine to generate them and send.

It’s up on NuGet and with the release of v1.0.0.11, it’s more stable.

For the most up to date info follow along with the usage sections of the readme.md file on the github repository.

How it works

I thought I would share some background about the development of it, and hiccups along the way. The original set of code came from Kazi Manzur Rashid, which solved the problem of making use of System.Web.RazorTemplateEngine, which I extended (with permission) to be usable as an injectable dependency and via NuGet.

The core elements are, the creation and management of the SMTP client, the building up of the MailMessage. Then all the compilation related work to get the RazorTemplateEngine up and running.

The RazorTemplateEngine logic boils down to taking the razor file stored on disk and using CSharpCodeProvider.CompileAssemblyFromDom. So if you’re curious about this code in particular dig into EmailTemplateEngine.cs in the project files.

Prior to version .10 where I went down the path of using ilmerge to solve conflicts of version mismatch with System.Web.Razor.

It seems easy seeing how I took an existing chunk of operational code and extended, and it only seems easy when it is working, but when it doesn’t work and you’ve got strange compilation errors, debugging this mechanism is not the greatest. I found myself hunting for temporary files and trying to have other compiler flags to output more information.

In the early versions it was heavily the case of “works on my machine”, but now its fine and seems to be feature complete…

Playing with AppHarbor, Twitter and WebAPI.

What?

This sample application is very contrived, and came out of a throw away twitter account creation joke.

what started it

Landing Page: usedguids.apphb.com

Usage Info: gist.github.com/3964492

Service Features

  1. Submit a Guid, have it reserved
  2. Will inform you if it’s taken, or ok.
  3. Tweets

Tech Details / Steps

  • File, New, Web Api Project
  • ASP.NET 4.5 Web Api Controller
  • PM> Install-Package TweetSharp (nuget link, github link)
  • Git push to remote repo on BitBucket
  • AppHarbor link to BitBucket account (this was great, very easy)
  • Select an app name usedguids.apphb.com

Api Controller Logic

    public class UsedGuidController : ApiController
    {
        public HttpResponseMessage Post(UsedGuidInputModel ug)
        {
            //check for duplicates,
            //twitter authenticate, tweet
            //save guid
            //return new HttpResponseMessage(what_happened)
        }
    }

Conclusion

It’s up and running, we’ll see how stable it is. In this case the code is very sloppy, the focus was to get this concept up and running, so I decided to host it on BitBucket where I have private repositories on a free account.

The AppHarbor experience was great, no fuss to get it up and running, via the authorise AppHarbor app action when I was taken to BitBucket. Even setting up a back end store was very easy.

app harbor ui

The hardest part was working out how to deal with the Twitter API, and that was only tricky because I was in a hurry to just get it working, without reading enough documentation.

It’s unlikely I’ll make time to tidy up that code so it can be of any reasonable use to anyone, there’s too many hack points to get it operational, in particular around twitter API keys, for the application that performs the posting, and the user linked to the account. Not to mention hard coded connection strings with passwords in them. Quite a long list of what-not-to-do.

I did like that the wizard does warn you of such bad behaviour. There’s some insight into the storage model on the back end 😉

EfDataModelCreation

Queuing ajax calls to ASP.NET WebApi Controllers

Objective

To halt processing of subsequent ajax calls after one causes an error.

Why

Any actions related to a similar set of data (or concept) will all go through the same queue. This way if something falls over during processing of any given request, halting the processing of further requests should help not worsen things, or at least avoid subsequent errors that are a direct result of the first error.

When something unexpected has happened it’s likely the underlying system data is not in a valid state. Further actions may complicate things, possibly making matters worse. But more likely further actions will also error and we shouldn’t subject the system to having to handle them. So the solution is to get the user to reload the application into a known good state, i.e. complete fresh request of data.

There’s a competing concern that particular user actions may be desirable to have processed even after particular unknown/unexpected errors occur, but for now we’re going to assume these are rarer and can be dealt with specifically simply by having them bypass this queue (or make use of an alternate queue).

How

A toggled case
– After an error set a flag that will keep prompting the user to reload the page after an error.

A fixed case
– Do not process items already queued up in the processing queue.

Queue entry management

This part is simple. Most of the code is plumbing around building up the ajaxQueue call.

#CoffeeScript
class ActionCommandQueue

    validState: true
    
    #todo: surface the console log issues to the user

    sendData: (url, data, type, settings) =>
        settings = settings || {}
        settings.url = url
        settings.data = JSON.stringify(data)
        settings.type = type
        settings.contentType = 'application/json; charset=utf-8'
        settings.error = @onError
        if @validState
            $.ajaxQueue(settings)
        else
            console.log "You need to reload the page to continue. (click here)."

    onError: (xhr, status, error) =>
        @validState = false
        console.log "Sorry that action failed. Please reload the page and try again"

Usage

    #CoffeeScript

    sendData '/api/Tasks', { description: "new task" }

http://api.jquery.com/queue/

The queue iteself

This part is also simple, seeing how the hard work in creating a jQuery .ajaxQueue() method has already been done by gnarf, and here’s the blog post outlining the code. This came out of a great stackoverflow answer and this one.

Except one modification

The .then( next, next ) call was replaced with a failure case, in production code it’s likely to be a silent failure because there’s an error handling function higher up in the call chain that will report the problem to the user (no need for repeating the message).

    function doRequest( next ) {

        fail = function () { console.log('cannot continue to process queue after an error');

        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, fail /*was next*/ );
    }

An added benefit here is not just around safety for the error case, but this queue approach ensures important user actions will get dispatched and arrive in a correct order.

Example

Scenario
1. Create a Task.
2. Update task details
3. Add Sub Task
4. Edit Sub Task [Fails]
5. Some other action (possibly related to the sub task)
6. 7. 8. 9. all same as 5.

At step 4, it fails, because something prevented the sub task being added. But before Task 4 failed, the user also issued action 5 very quickly. Step 5 is what the above code is preventing from running because we’re not sure what the impacts may be.

Before I release some Unit Tests to demonstrate this. I have a crude annotation on the Chrome Developer tools console output. The proof is lack of calls to ‘doneCb‘ after the error. Note the 500 error, then the 2 error messages that follow.

Ajax Queue Drop

Chrome debug output showing the error output.

Queues, Deferred and Promises

It’s beyond the scope of what I wanted to talk about here, but the jQuery.ajax wrapper jQuery.ajaxQueue makes use of Deferred, Deffered.then() and Promises, they’re worth looking into to gain a detailed understanding. Some reading about the queue itself.

Conclusion

So now a user can click to their hearts content on a variety of partially related actions on a page, having each fire off an ajax() request. If something goes wrong they can be alerted, and you can save a flood of subsequent errors happening.

Capturing client side JavaScript errors for later analysis

We’re getting close to pushing an application to a larger set of test users, and we’ll be interested in what happens when a larger variety of machine configurations (browsers and operating systems) and of course user actions encounter errors.

We started with simply catching any server side errors, and log them to a single database table (separate database to application).

To achieve this part of it, it is simple as having a very lightweight database connection mechanism to insert this log entry record, this way if there was an error with our applications standard database access mechanism we could also capture that.

In this fashion we can be reasonably sure that anything short of major production environment failure (network infrastructure / machine specific) that we’ll be able to capture errors while the system is being used. Those types of issues will be handled differently.

Then we realised it would be just as helpful to capture and store client side JavaScript errors in a similar fashion.

Capture

The JavaScript error handler looks like this, making use of window.error:

window.$debug.globalErrorHandler = function () {
  window.onerror = function (m, u, l) {
    
    $.ajax({
      url: '/Error/Occurred',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({ errorMsg: m, url: u, line: l, uri: window.location.href }),
      contentType: 'application/json; charset=utf-8',
    });
    
    return true;
  };
};

An extra note here is I came across a JS library that offered a common ‘printStackTrace()’ method. Created by Eric Wendelingithub project. Which doesn’t work how I would have hoped it would have worked in our global error handler, but that’s the nature of the error handler event.

Never the less it does look quite helpful, to make use of it you need to have a specific try { } catch { } block around something that may fail. Checkout the readme on the github project page.

Back to the main focus of this post…

We can also decide to call $debug.globalErrorHandler() method in some central part of the web application, so that later it doesn’t have to be always turned on.

Receive

The MVC side of this is even simpler, since our users are logged in while using the application, we have ‘context’ information about them, so that’s one extra useful piece of information we can capture as part of the error.

public class ErrorController
{
  public void Occurred(ClientSideJavaScriptException error)
  {
    // this context in our application represents the user, so we know who experienced the error.
    error.User = _userContext.UserName;

    // we send this off elsewhere to be persisted, you could simply persist it here
    _service.Handle(error);
  }
}

The ClientSideJavaScriptException class simply has the properties required to send over the information from the ajax post.

public class ClientSideJavaScriptException
{
  public string ErrorMsg { get; set; }
  public string Url { get; set; }
  public string Line { get; set; }
}

Process

Finally the persistence logic here is via the Micro.ORM NPoco selected because Adam said it was good 😉 and the Nuget Package helped.

//setup
Db = new Database("configuration_key_name");

Db.Insert(new Details
{
  OccurredWhere = "client-side-js",
  ExceptionMessage = errorDetails.ErrorMsg,
  When = DateTime.Now,
  StackTrace = errorDetails.Stack,
  Method = "Line Number:" + errorDetails.Line
}