codeSMART

Entries tagged as ‘ASP.NET MVC’

InsertScript for ASP.NET MVC

January 13, 2009 · Leave a Comment

I recently had a situation where a custom control I was using in a page required jQuery.  Since I like the idea of keeping such controls self-contained, I added the usual <script type="text/javascript" src="jquery-1.2.6.min.js"></script> tag.

No problem – until I then loaded a page that included this control AND also had its own requirement for jQuery.  It seems that jQuery doesn’t like begin included twice, so I had a choice.  I could:

  • Include jQuery once in the header (or wherever) of each page (i.e. in the Master Page), hence breaking the self-containment of my control, or;
  • Write a helper method to keep track of which script files had been included in each page and hence allow a script file to only be included once per request.

It should come as no surprise (as otherwise there would be no point in this post) that I went for the second option.

The HttpContext object has an Items collection, and since the HttpContext has a lifetime of one request, we can use this Items collection to keep track of our included files.  Just add the following static method to a static class (Don’t you just love Extension Methods!):

public static string InsertScript(this HtmlHelper helper, string jsFile)
{
    const string RESID = "__resources";

    List<string> _resources = (List<string>)helper.ViewContext.HttpContext.Items[RESID];
    if (_resources == null)
    {
        _resources = new List<string>();
        helper.ViewContext.HttpContext.Items[RESID] = _resources;
    }

    string url = ScriptUrl(jsFile);
    if (!_resources.Contains(url.ToLower()))
    {
        _resources.Add(url.ToLower());
        return "<script type=\"text/javascript\" src=\"" + url + "\"></script>";
    }
    else
        return "";
}

Notice the call to ScriptUrl(jsFile) – this is just a static helper method to map javascript file names to the Scripts folder in my web app. It’s up to you whether you use such a method.

It’s now just a matter of calling this from your .aspx pages, replacing the usual
<script type="text/javascript" src="myjavascriptfile.js"></script>
with
<%= Html.InsertScript("myjavascriptfile.js") %>

Categories: Coding
Tagged: , ,

Profiling ASP.NET MVC using the EQATEC Profiler

November 28, 2008 · Leave a Comment

I recently have had a need to do some code profiling of an ASP.NET MVC site I have been working on and so, being the cheapskate I am, found the EQATEC .NET Profiler.

Now, there are a couple of caveats to using this profiler for ASP.NET applications.  The first is that the profiler outputs its XML data file to one of the following locations: /Storage Card, /SD Card, /Temp or /.  The best way around this is to create a Temp directory in the root directory of the drive that hosts your ASP.NET application (eg. C:\Temp if your site is located in C:\Inetpub\...).  Make sure the IIS User associated with the relevant App Pool has Write access to this dir, and you’re sweet.

The second caveat is slightly more difficult to get around.  The problem is that the profiler will only output its XML file either when the Main method exits, or when the TakeProfileSnapshot() method is called in the Profiler.Runtime library.  We don’t have a Main method in ASP.NET, so we’ll use the TakeProfileSnapshot() call.

While the following is particularly focussed on ASP.NET MVC, it should be useful for ’standard’ ASP.NET as well.

First, we need to create a page that will call the TakeProfileSnapshot() method.  In my site, I have a ‘Setup’ Controller for performing tasks that only I know about (such as initially populating databases, etc), so I added a TriggerProfile action to this method and added a simple view to display the output, as follows.

public ActionResult TriggerProfile()
{
    try
    {
        ViewData["Result"] = “Success”;
    }
    catch (Exception ex)
    {
        ViewData["Result"] = “Failed: ” + ex.Message + “

” + ex.ToString();
    }
    return View();
}

We’ll flesh it out in a bit.  The  TriggerProfile.aspx page simply has a <%= ViewData["Result"] %> tag to display the result.  Feel free to make this a bit prettier, but let’s face it – nobody but you should ever see this.

I didn’t want to include the EQATEC Profiler DLL in my project, as I don’t really like the idea of modifying a project for testing unless that change is transparent in production.

Reflection to the rescue!

Making sure you add a using System.Reflection; directive, add the following to that try {} block above, before the ViewData["Result"] = "Success"; line:

Assembly eqatec = Assembly.Load(“EQATECProfilerRuntime, Version=1.2.60.0, Culture=neutral, PublicKeyToken=f1beac79aa82eef6″);
Type runtime = eqatec.GetType(“EQATEC.Profiler.Runtime”);

MethodInfo takeSnapshot = runtime.GetMethod(“TakeProfileSnapshot”, new Type[] { });
takeSnapshot.Invoke(null, null);

So what’s happening here?

The EQATECProfilerRuntime.dll assembly is only present in the application once the bin folder has been profiled (the Profiler creates a bin (Profiled) folder – just rename this to bin and remember to restart IIS to activate the changes).  If the /Setup/TriggerProfile page is called in this case, it finds the dll, gets an instance of the TakeProfileSnapshot() method and invokes it, triggering a dump of the profiler output.  In the case that the code has not been profiled, EQATECProfilerRuntime.dll should not be present, and so the Assembly.Load(...) call will fail, and the output of the Exception will be displayed.

To use all of this, simply use the Profiler to profile the bin folder, rename the created folder back to bin, restart IIS and start browsing on those troublesome pages.  When you’re ready, make a call to the /Setup/TriggerProfile page (hopefully you’ll get a “Success” message), and check the C:\Temp folder for the resultant XML.

Happy profiling!

Categories: Coding
Tagged: ,

Web Development Helper

July 25, 2008 · 1 Comment

A while ago, I posted a quick note on my desire to use the new ASP.NET MVC framework to create a photo sales website.  In the end, it didn’t work out that way, and I am using the framework to build a new website for my church.

While a huge benefit to ASP.NET MVC is (IMHO) the ability to shed the ASP server side tags, and hence gain complete control over markup and layout within the page, I am amazed at the amount of Javascript I seem to be writing to keep the application ‘Web-2.0-ish’.  In fact, one particular page in the site probably contains more Javascript than the sum total of all Javascript I had written in many years before.

In this, jQuery has been a huge help, but sometimes it’s nice to see exactly what script calls are being made (this applies particularly to Ajax calls) and what is returned.

Enter Nikhil Kothari’s Web Development Helper.  In his words,

Web Development Helper is a free browser extension for Internet Explorer that provides a set of tools and utilities for the Web developer, esp. Ajax and ASP.NET developers. The tool provides features such as a DOM inspector, an HTTP tracing tool, and script diagnostics and immediate window.

My understanding is that Firefox now has a similar tool built in (Firebug) but I have not tried this yet, mainly because the VS2008 development system works with IE.  Tools of this calibre are more than welcome in my opinion.

Categories: Other Development
Tagged: ,

ASP.NET MVC Preview 4…

July 17, 2008 · Leave a Comment

Categories: Other Development
Tagged: