Profile and debug your ASP.NET MVC app with Glimpse

by Rick Anderson

Glimpse is a thriving and growing family of open source NuGet packages that provides detailed performance, debugging and diagnostic information for ASP.NET apps. It's trivial to install, lightweight, ultra-fast, and displays key performance metrics at the bottom of every page. It allows you to drill down into your app when you need to find out what's going on at the server. Glimpse provides so much valuable information we recommend you use it throughout your development cycle, including your Azure test environment. While Fiddler and the F-12 development tools provide a client side view, Glimpse provides a detailed view from the server. This tutorial will focus on using the Glimpse ASP.NET MVC and EF packages, but many other packages are available. Where possible I will link to the appropriate Glimpse docs which I help maintain. Glimpse is an open source project, you too can contribute to the source code and the docs.

Installing Glimpse

You can install Glimpse from the NuGet package manager console or from the Manage NuGet Packages console. For this demo, I'll install the Mvc5 and EF6 packages:

install Glimpse from NuGet Dlg

Search for Glimpse.EF

Glimpse.EF from NuGet install dlg

By selecting Installed packages, you can see the Glimpse dependent modules installed:

Installed Glimpse packages from DLg

The following commands install Glimpse MVC5 and EF6 modules from the package manager console:

PM> Install-Package Glimpse.MVC5
PM> Install-Package Glimpse.EF6

Enable Glimpse for localhost

Navigate to http://localhost:<port #>/glimpse.axd and click the Turn Glimpse On button.

Glimpse axd page

If you have your favorites bar displayed, you can drag and drop the Glimpse buttons and add them as bookmarklets:

IE with Glimpse bookmarklets

You can now navigate your app, and the Heads Up Display (HUD) is shown at the bottom of the page.

Contact Manager page with HUD

The Glimpse HUD page details the timing information shown above. The unobtrusive performance data the HUD displays can notify you of a problem immediately - before you get to the test cycle. Clicking on the "g" in the lower right corner brings up the Glimpse panel:

Glimpse panel

In the image above, the Execution tab is selected, which shows timing details of the actions and filters in the pipeline. You can see my Stop Watch filter timer start at stage 6 of the pipeline. While my light weight timer can provide useful profile/timing data, it misses all the time spent in authorization and rendering the view. You can read about my timer at Profile and Time your ASP.NET MVC app all the way to Azure.

The Timeline tab

I've modified Tom Dykstra's outstanding EF 6/MVC 5 tutorial with the following code change to the instructors controller:

public ActionResult Index(int? id, int? courseID, int ? eager)
{
    var viewModel = new InstructorIndexData();

    viewModel.Instructors = db.Instructors
        .Include(i => i.OfficeAssignment)
        .Include(i => i.Courses.Select(c => c.Department))
        .OrderBy(i => i.LastName);

    if (id != null)
    {
        ViewBag.InstructorID = id.Value;
        viewModel.Courses = viewModel.Instructors.Where(
            i => i.ID == id.Value).Single().Courses;
    }

    if (courseID != null)
    {
       ViewBag.CourseID = courseID.Value;
       // Eager loading
       if (eager != null && eager > 0)
       {
          ViewBag.eagerMsg = "Eager Loading";

          viewModel.Enrollments = viewModel.Courses.Where(
              x => x.CourseID == courseID).Single().Enrollments;

       }
       else { 
        // Explicit loading
          ViewBag.eagerMsg = "Explicit Loading";

        var selectedCourse = viewModel.Courses.Where(x => x.CourseID == courseID).Single();
        db.Entry(selectedCourse).Collection(x => x.Enrollments).Load();
        foreach (Enrollment enrollment in selectedCourse.Enrollments)
        {
            db.Entry(enrollment).Reference(x => x.Student).Load();
        }

        viewModel.Enrollments = selectedCourse.Enrollments;
       }
    }

    return View(viewModel);
}

The code above allows me to pass in query string (eager) to control eager or explicit loading of data. In the image below, explicit loading is used and the timing page shows each enrollment loaded in the Index action method:

explicit loading

In the following code, eager is specified, and each enrollment is fetched after the Index view is called:

eager is specified

You can hover over a time segment to get detailed timing information:

hover to see detailed timing

Model Binding

The model binding tab provides a wealth of information to help you understand how your form variables are bound and why some are not bound as would expect. The image below shows the ? icon, which you can click on to bring up the glimpse help page for that feature.

glimpse model binding view

Routes

The Glimpse Routes tab will can help you debug and understand routing. In the image below, the product route is selected (and it shows in green, a Glimpse convention). product name selected Route constraints, Areas and data tokens are also displayed. See Glimpse Routes and Attribute Routing in ASP.NET MVC 5 for more information.

Using Glimpse on Azure

The Glimpse default security policy only allows Glimpse data to be displayed from local host. You can change this security policy so you can view this data on a remote server (such as a web app on Azure). For test environments on Azure, add the highlighted mark up to the bottom of the web.config file to enable Glimpse:

<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
    <runtimePolicies>
      <ignoredTypes>
        <add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet"/>
      </ignoredTypes>
    </runtimePolicies>
  </glimpse>
</configuration>

With this change alone, any user can see your Glimpse data on a remote site. Consider adding the markup above to a publish profile so it's only deployed an applied when you use that publish profile (for example, your Azure test profile.) To restrict Glimpse data, we will add the canViewGlimpseData role and only allow users in this role to view Glimpse data.

Remove the comments from the GlimpseSecurityPolicy.cs file and change the IsInRole call from Administrator to the canViewGlimpseData role:

public class GlimpseSecurityPolicy : IRuntimePolicy
{
    public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
    {
        var httpContext = policyContext.GetHttpContext();
        if (!httpContext.User.IsInRole("canViewGlimpseData"))
        {
            return RuntimePolicy.Off;
        }

        return RuntimePolicy.On;
    }

    public RuntimeEvent ExecuteOn
    {
        get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
    }
}

Warning

Security - The rich data provided by Glimpse could expose the security of your app. Microsoft has not performed a security audit of Glimpse for use on productions apps.

For information on adding roles, see my Deploy a Secure ASP.NET MVC 5 web app with Membership, OAuth, and SQL Database to Azure tutorial.

Additional Resources