Tuesday, January 29, 2013

Umbraco Full Text Search Razor Script File

We use the Umbraco Full Text Search package which is a great tool for simple full text site wide searching.  It does however use a XSLT macro to render its search results.  We have an extensive collection of Razor Macros and as such I wanted a Razor version of this package to simplify development.  One does not exist So i took the time to convert the XSLT macro into a Razor macro included below.  Just add it to you MacroScripts folder and then change the FullTextSearch Macro to use this instead of the original version.  The output should be identical to the XSLT version.


FullTextSearch.cshtml

@using FullTextSearch.XsltExtensions
@using System.Xml.XPath
@{
 /*
                            FullTextSearch.xslt
    ======================================================================
                            Full Text Search 
                                  V0.25
    ======================================================================
    
    This XSLT file sets up queries and sends them off to FullTextSearch's 
    XSLT helpers.
    
    Feel free to modify any part of it to your own needs. HTML is near
    the bottom in a couple of templates. 
    
    PARAMETERS:
    
    queryType 
    
    Type of search to perform. Possible values are:
    
    MultiRelevance ->
      The default.
      The index is searched for, in order of decreasing relevance
        1) the exact phrase entered in any of the title properties
        2) any of the terms entered in any of the title properties
        3) a fuzzy match for any of the terms entered in any of the title properties
        4) the exact phrase entered in any of the body properties
        5) any of the terms entered in any of the body properties
        6) a fuzzy match for any of the terms entered in any of the body properties
    
    MultiAnd ->
      Similar to MultiRelevance, but requires all terms be present
    
    SimpleOr->
      Similar to MultiRelevance again, but the exact phrase does not
      get boosted, we just search for any term
      
    AsEntered->
      Search for the exact phrase entered, if more than one term is present
    ______________________________________________________________________    
    
    titleProperties
    
    A comma separated list of properties that are part of the page title,
    these will have their relevance boosted by a factor of 10
    defaults to nodeName. Set to "ignore" not to search titles.
    ______________________________________________________________________    
    
    bodyProperties 
    
    A comma separtated list of properties that are part of the page body.
    These properties and the titleProperties will be searched. 
    
    defaults to using the full text index only
    ______________________________________________________________________
    
    summaryProperties
    
    The list of properties, comma separated, in order of preference,
    that you wish to use to create the summary to appear under
    the title. All properties selected must be in the index, cos that's
    where we pull the data from.
    
    Defaults to Full Text
    ______________________________________________________________________    
    titleLinkProperties
    
    The list of properties, comma separated, in order of preference,that you 
    wish to use to create the title link for each search result. 
    
    Defaults to titleProperties, or if that isn't set nodeName
    ______________________________________________________________________            
    rootNodes
    
    Comma separated list of root node ids
    Only nodes which have one of these nodes as a parent will be returned.
    Default is to search all nodes
    ______________________________________________________________________
    
    contextHighlighting
    
    Set this to false to disable context highlighting
    in the summary/title. You may wish to do this if you are having
    performance issues as context highlighting is (relatively)
    slow.
    Defaults to on.
    
    ______________________________________________________________________
    
    summaryLength
    
    The maximum number of characters to show in the summary.
    Defaults to 300
    
    ______________________________________________________________________
    
    pageLength
    
    Number of results on a page. Defaults to 20. Set to zero to disable paging.
    
    ______________________________________________________________________

    fuzzyness
    
    Lucene Queries can be "fuzzy" or exact.
    A fuzzy query will match close variations of the search terms, such as 
    plurals etc. This sets how close the search term must be to a term in
    the index. Values from zero to one. 1.0 = exact matching.
    Note that fuzzy matching is slow compared to exact or even wildcard
    matching, if you're having performance issues this is the first thing
    to switch off.
    
    Defaults to 0.8
    ______________________________________________________________________
    
    useWildcards
    
    Add a wildcard "*" to the end of every search term to make it match 
    anything starting with the search term. This is a slightly faster, but
    less accurate way of achieving the same ends as fuzzy matching. 
    Note that fuzzyness is automatically set to 1.0 if a wildcards are enabled.
    
    Defaults to off
    ______________________________________________________________________
 */
 
 /* Variables */
 var fullTextIndexName = "FullTextSearch";
 var getPostTerms = "Search";
 var getPostPage = "Page";
 var numNumbers = 15;
 
 /* Parameters */
 var titleProperties = String.IsNullOrEmpty(Parameter.titleProperties) ? "nodeName" : Parameter.titleProperties;
 if(titleProperties == "ignore") {
  titleProperties = "";
 }
 var bodyProperties = String.IsNullOrEmpty(Parameter.bodyProperties) ? fullTextIndexName : Parameter.bodyProperties;
 var summaryProperties = String.IsNullOrEmpty(Parameter.summaryProperties) ? fullTextIndexName : Parameter.summaryProperties;
 var titleLinkProperties = String.IsNullOrEmpty(Parameter.titleLinkProperties) ? (String.IsNullOrEmpty(titleProperties) ? "nodeName" : titleProperties) : Parameter.titleLinkProperties;
 var rootNodes = Parameter.rootNodes;
 var contextHighlighting = Parameter.contextHighlighting == "0" ? 0 : 1;
 int summaryLength;
 if(!int.TryParse(Parameter.summaryLength, out summaryLength) || summaryLength <= 0) {
  summaryLength = 300;
 }
 int pageLength;
 if(!int.TryParse(Parameter.pageLength, out pageLength) || pageLength <= 0) {
  pageLength = 20;
 }
 var queryType = String.IsNullOrEmpty(Parameter.queryType) ? "MultiRelevance" : Parameter.queryType;
 var fuzzyness = String.IsNullOrEmpty(Parameter.fuzzyness) ? "0.8" : Parameter.fuzzyness;
 var useWildcards = Parameter.useWildcards == "1" ? 1 : 0;
 
 /* Call Helpers */
 var pageNumber = String.IsNullOrEmpty(umbraco.library.RequestQueryString(getPostPage)) ? (String.IsNullOrEmpty(umbraco.library.Request(getPostPage)) ? 1 : int.Parse(umbraco.library.Request(getPostPage))) : int.Parse(umbraco.library.RequestQueryString(getPostPage)); 
 var searchTerms = String.IsNullOrEmpty(umbraco.library.RequestQueryString(getPostTerms)) ? (String.IsNullOrEmpty(umbraco.library.Request(getPostTerms)) ? "" : umbraco.library.Request(getPostTerms)) : umbraco.library.RequestQueryString(getPostTerms); 
 var searchTermsUrlEncoded = umbraco.library.UrlEncode(searchTerms);
 
 
 /* Run Search */
 var results = SearchExtension.Search(queryType,searchTerms,titleProperties,bodyProperties,rootNodes,titleLinkProperties,summaryProperties,contextHighlighting,summaryLength,pageNumber,pageLength,fuzzyness,useWildcards);
}
<div class="fulltextsearch">
 @if(results.Current.Evaluate("count(/results)") == 1) {
  var resultsItem = results.Current.Select("/results");
  <div class="fulltextsearch_results">
    <h1 class="fulltextsearch_results_heading">
  @String.Format(GeneralExtension.DictionaryHelper("SearchResultsFor"), searchTerms)
    </h1>
  @{
   int numPages = (int)resultsItem.Current.Evaluate("number(/results/summary/@numPages)");
  }
  @if(numPages > 1)
  {
   @Pagination(numPages, pageNumber, getPostTerms, searchTermsUrlEncoded, getPostPage, numNumbers)
  }
  
  @foreach(var searchResult in resultsItem.Current.Select("/results/nodes/*")) {
   var FullTextTitle = searchResult.Evaluate("string(./data [@alias='FullTextTitle'])");
   var FullTextSummary = searchResult.Evaluate("string(./data [@alias='FullTextSummary'])");
    
    <div class="fulltextsearch_result">
   <h2 class="fulltextsearch_title">
     <a class="fulltextsearch_titlelink" href="@umbraco.library.NiceUrl(1)">
    @Html.Raw(FullTextTitle)
     </a>
   </h2>
   <p class="fulltextsearch_summary">
    @Html.Raw(FullTextSummary)
   </p>
    </div>
  }
  @if(numPages > 1)
  {
   @Pagination(numPages, pageNumber, getPostTerms, searchTermsUrlEncoded, getPostPage, numNumbers)
  }
  <p class="fulltextsearch_info">
  @{
   var summary = String.Format(GeneralExtension.DictionaryHelper("SummaryInfoFormat"),
                      resultsItem.Current.Evaluate("string(/results/summary/@firstResult)"),
                      resultsItem.Current.Evaluate("string(/results/summary/@lastResult)"),
                      resultsItem.Current.Evaluate("string(/results/summary/@numResults)"),
                      resultsItem.Current.Evaluate("string(/results/summary/@timeTaken)"));
   var swinfo = resultsItem.Current.Evaluate("string(/results/summary/swinfo)");
  }
  @summary
  @Html.Raw(swinfo)
        </p>
  </div>
  
 } else  {
 string errorType = (string)results.Current.Evaluate("string(/error/@type)");
 string error = (string)results.Current.Evaluate("string(/error)");
 string dictionaryError = String.IsNullOrEmpty(errorType) ? "" : String.Format(GeneralExtension.DictionaryHelper(errorType), searchTerms, pageNumber);
 var errormsg = String.IsNullOrEmpty(dictionaryError) ? (String.IsNullOrEmpty(error) ? GeneralExtension.DictionaryHelper("UnknownError"): error) : dictionaryError;
   <div class="fulltextsearch_error">
  <p>
    @errormsg
  </p>
  </div>
 }
</div>

@helper Pagination(int numPages, int pageNumber, string getPostTerms, string searchTermsUrlEncoded, string getPostPage, int numNumbers)
{
    var langPrevious = GeneralExtension.DictionaryHelper("NavPrevious");
    var langNext = GeneralExtension.DictionaryHelper("NavNext");
 int startPage = (numNumbers / 2);
 startPage = (pageNumber < startPage + 1) ? 1 : pageNumber - startPage;
 
   <div class="fulltextsearch_pagination">
    <ul class="fulltextsearch_pagination_ul" style="list-style-type:none;margin-bottom:15px;">
  @if(pageNumber > 1) {
        <li class="fulltextsearch_previous">
          <a class="fulltextsearch_pagination_link" rel="prev" href="?@getPostTerms=@searchTermsUrlEncoded&@getPostPage=@(pageNumber - 1)">@langPrevious</a>
   </li>
  } else {
   <li class="fulltextsearch_previous fulltextsearch_previous_inactive">
          <a class="fulltextsearch_pagination_link">
             @langPrevious
          </a>
        </li>
  }
  
  @for(int curPage = startPage; curPage <= numPages && curPage < startPage + numNumbers; curPage++) {
   if(curPage == pageNumber) {
    <li class="fulltextsearch_page fulltextsearch_thispage" style="margin-left:5px;">
             @curPage
         </li>
   } else {
         <li class="fulltextsearch_page" style="margin-left:5px;">
           <a class="fulltextsearch_pagination_link"  rel="nofollow" href="?@getPostTerms=@searchTermsUrlEncoded&@getPostPage=@curPage">
      @curPage
     </a>
    </li>
   }
  }
 
  @if(pageNumber < numPages) {
   <li class="fulltextsearch_next" style="margin-left:5px;">
            <a class="fulltextsearch_pagination_link" rel="next" href="?@getPostTerms=@searchTermsUrlEncoded&@getPostPage=@(pageNumber + 1)">
     @langNext
    </a>
   </li>
  } else {
   <li class="fulltextsearch_next fulltextsearch_next_inactive" >
     <a class="fulltextsearch_pagination_link" style="margin-left:5px;">
    @langNext
     </a>
   </li>
  }
 </ul>
   </div>
}

@helper ShowErrors(XPathNodeIterator results, string searchTerms, int pageNumber)
{
 string errorType = (string)results.Current.Evaluate("string(/error/@type)");
 string error = (string)results.Current.Evaluate("string(/error)");
 string dictionaryError = String.IsNullOrEmpty(errorType) ? "" : String.Format(GeneralExtension.DictionaryHelper(errorType), searchTerms, pageNumber);
 var errormsg = String.IsNullOrEmpty(dictionaryError) ? (String.IsNullOrEmpty(error) ? GeneralExtension.DictionaryHelper("UnknownError"): error) : dictionaryError;
 
  <div class="fulltextsearch_error">
    <p>
      @errormsg
    </p>
  </div>
}

@helper SearchBox(string searchTerms, string getPostTerms)
{
 var searchString = GeneralExtension.DictionaryHelper("SearchButton");
 
 <form class="fulltextsearch_form" method="get" action="@umbraco.library.NiceUrl(Model.Id)">
      <input class="fulltextsearch_searchbox" name="@getPostTerms" type="text" value="@searchTerms" />
      <input class="fulltextsearch_searchbutton" type="submit" value="@searchString" />
    </form> 
}

Friday, December 21, 2012

Automatic Script/CSS Compression/Rollup in Umbraco

Note: This code is specific to .NET Master Page templates.  Here are instructions for using MVC Views available in Umbraco 4.10+.

When using Umbraco you may have noticed that the Backoffice Administrative interface uses the Client Dependency Framework to roll up and compress all the different scripts and css resources into two calls.  This leads to a big improvement in responsiveness as the server doesn't need to download as much data nor complete as many requests to render a web page in the admin area.

The good new here is that you can use this same system in your actual site with very little setup.  A few simple step to configure your main site templates to use the Client Dependency Framework also.

First of all add the following block to the top of evert template in your site just after the first line, Master Tag.

<%@ Register TagPrefix="umb" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %>

Next for all of you sites master templates add the following code someplace in the HEAD block.  Note that you don't want to put this on every templates, just those that are the top level templates.  The golden rule is that every page should call this one and only once.

<umb:ClientDependencyLoader runat="server" ID="ClientLoader">
  <Paths>
      <umb:ClientDependencyPath Name="Styles" Path="/Css" />
       <umb:ClientDependencyPath Name="Scripts" Path="/Scripts" />
  </Paths>
</umb:ClientDependencyLoader>

Now go through all your templates and change your Script and Css includes to the following sample blocks.

<umb:CssInclude runat="server" FilePath="jquery-ui-1.8.css" PathNameAlias="Styles" Priority="0" />
<umb:JsInclude runat="server" FilePath="jquery-1.8.3.js" PathNameAlias="Scripts" Priority="0" />
<umb:JsInclude runat="server" FilePath="jquery-ui-1.9.js" PathNameAlias="Scripts" />

Note that the Priority property is not required.  If set it will load those first in ascending numerical order then load any thing without a priority.  Also the system will detect duplicate inclusions of the same script/css file on the page and only include each one a single time.  You also won't see errors if a script is missing so watch for that as it can be hard to realize if you make a typo.

If you view the site now you will see two lines like this and if you inspect them they will contain all the compressed code.

<link href="/DependencyHandler.axd?s=RandmData&amp;t=Css&amp;cdv=41" type="text/css" rel="stylesheet">
<script src="/DependencyHandler.axd?s=RandmData&amp;t=Javascript&amp;cdv=41" type="text/javascript"></script>

A few other notes  This will not work when compilation/debug is set to True in the web.config.  You will need to disable debug mode to test it and also on the production environment.  Also when the code is compressed it is very hard to debug.  You will want to turn on debug mode on the development system when debugging CSS and Javascript issues or doing development.  The resources will just be loaded with individual script calls in this case.

Also once this is set up there is no reason to use minified scripts in your site anymore.  I suggest replacing them with the full versions for easier code review/editing.

On a final note if you want to include Scripts and CSS files from within macros you can do so still using the  Client Dependency Framework but it is a bit more complex.  I sugest adding the following helper methods in your App_Code directory.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web;
using ClientDependency.Core.Controls;
using ClientDependency.Core;

namespace JSP
{
    /// <summary>
    /// Client Dependency Loader helpers.
    /// </summary>
    public static class CDL
    {
        /// <summary>
        /// Custom version of the AddRange method that accepts no arguments and does not error out.
        /// </summary>
        /// <typeparam name="T">type</typeparam>
        /// <param name="self">parent collection</param>
        /// <param name="collection">new collection to add or null</param>
        public static void AddRangeOrNone<T>(this List<T> self, IEnumerable<T> collection)
        {
            if (collection != null)
                self.AddRange(collection);
        }

        #region Control Lookup
        /// <summary>
        /// Search recursivle down a control tree for all controls with the passed in Id
        /// </summary>
        /// <param name="self">Root control to search form.</param>
        /// <param name="id">Id to look for</param>
        /// <returns>List of all matched Controls.</returns>
        public static List<Control> SearchControl(this Control self, string id)
        {
            List<Control> results = new List<Control>();

            Control control = self.FindControl(id);

            if (control != null)
                results.Add(control);

            foreach (Control childControl in self.Controls)
            {
                results.AddRangeOrNone(childControl.SearchControl(id));
            }

            return results;
        }

        /// <summary>
        /// Search recursivle down a control tree for all controls of the passed in type
        /// </summary>
        /// <param name="self">Root control to search form.</param>
        /// <param name="type">Type to look for</param>
        /// <returns>List of all matched Controls.</returns>
        public static List<Control> SearchControl(this Control self, Type type)
        {
            List<Control> results = new List<Control>();

            foreach (Control childControl in self.Controls)
            {
                if (childControl.GetType() == type)
                    results.Add(childControl);

                results.AddRangeOrNone(childControl.SearchControl(type));
            }

            return results;
        }
        #endregion

        #region Client Dependencies
        /// <summary>
        /// Add another script to the dependency loader list to be compressed and combined with other resources.
        /// </summary>
        /// <param name="path">Path of the script to load from the pathNameAlias folder.</param>
        /// <param name="pathNameAlias">Folder alias to look for the script in.</param>
        public static void AddScript(string path, string pathNameAlias = "Scripts", int priority = 10)
        {
            Page page = (Page)HttpContext.Current.Handler;
            IEnumerable<ClientDependencyLoader> cdl = page.SearchControl("ClientLoader").Cast<ClientDependencyLoader>();

            if (cdl.Count() > 0)
            {
                cdl.First().RegisterDependency(priority, path, pathNameAlias, ClientDependencyType.Javascript);
            }
        }

        /// <summary>
        /// Add another stylesheet to the dependency loader list to be compressed and combined with other resources.
        /// </summary>
        /// <param name="path">Path of the stylesheet to load from the pathNameAlias folder.</param>
        /// <param name="pathNameAlias">Folder alias to look for the stylesheet in.</param>
        public static void AddStyle(string path, string pathNameAlias = "Styles")
        {
            Page page = (Page)HttpContext.Current.Handler;
            IEnumerable<ClientDependencyLoader> cdl = page.SearchControl("ClientLoader").Cast<ClientDependencyLoader>();

            if (cdl.Count() > 0)
            {
                cdl.First().RegisterDependency(10, path, pathNameAlias, ClientDependencyType.Css);
            }
        }
        #endregion
    }
}

Then you can use the following in a macro to add a resource. Note that this will not work on macros that use Cacheing, in those cases the scripts would need to be added to the templates instead.

@using JSP
@{
  CDL.AddScript("jquery-ui-1.9.js");
  CDL.AddCss("ContentTabbed.css");
}

Tuesday, December 11, 2012

Umbraco Using Courier to Deploy Multi-Node Tree Pickers

The same problem that I mentioned relating to the Deploying MultiType data occurs with other uComponets data types as well.  The Multi-Node Tree Picker for example has the same problem if you user XML as the storage method.  You could get around this by using CSV but that is harder to work with in macro code.  The following is another sample data provider to add support for deploying MNTP-XML Data(Data Editor GUID: 7e062c13-7c41-4ad9-b389-41d88aeef87c).


using Umbraco.Courier.Core;
using Umbraco.Courier.Core.Enums;
using Umbraco.Courier.Core.Helpers;
using Umbraco.Courier.DataResolvers;
using Umbraco.Courier.ItemProviders;

using System.Collections.Generic;
using System.Linq;

namespace JSP {
    /// <summary>
    /// Custm Data Resolver for use with Multi-Node Tree Picker data objects.  Will convers a list of xml nodes to guids for deployment and back again.
    /// </summary>
 public class MNTPXml : PropertyDataResolverProvider
 {
  /// <summary>
        /// The datatype guid of the multitype item we are running on.
        /// </summary>
        public override Guid DataTypeId
        {
            get { return new Guid("7e062c13-7c41-4ad9-b389-41d88aeef87c"); }
        }

        /// <summary>
        /// Run when a property of the specified type is packaged up.
        /// </summary>
        public override void PackagingProperty(Item item, ContentProperty propertyData)
        {
            string nodeXpath = "//nodeId";

            // Document References
            List<string> replacedIds = new List<string>();
            propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), nodeXpath, IdentifierReplaceDirection.FromNodeIdToGuid, out replacedIds);

            // List all id's found and make them dependencies.
            foreach (string guid in replacedIds)
            {
                // Add as a dependency. (working?)
                item.Dependencies.Add(guid, ProviderIDCollection.documentItemProviderGuid);
            }
        }

        /// <summary>
        /// Run when a property of the specified type is extracted.
        /// </summary>
        public override void ExtractingProperty(Item item, ContentProperty propertyData)
        {
            string nodeXpath = "//nodeId";

            // Document References
            List<string> replacedIds = new List<string>();
            propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), nodeXpath, IdentifierReplaceDirection.FromGuidToNodeId, out replacedIds);
        }
}

Thursday, October 4, 2012

Load Umbraco nodes by Guid and print Guid's in Razor

Umbraco internals provide methods for accessing objects by Guid instead of ID.  This is necessary when using multiple environments and moving files around with Courier.  The reason being that ID's are not unique across instances and as items are moved around they will get assigned new ID's.  The following for example will not work as expected when deployed with Courier.

@Model.NodeById("Some static pageId").myVariable

To do this properly the Guid is needed instead. The problem though is that the Razor DynamicNode object doesn't expose or let you load nodes by the Guid.  The included class can be added to your App_Code directory to allow the following code samples to work in Razor.

using JSP;
// Get a object by the Guid
@Model.NodeByGuid("someGuid").myVariable
// Print a object's Guid
@Model.UniqueId()


GuidExtensions.cs
using System;
using umbraco;
using umbraco.MacroEngines;
using umbraco.cms.businesslogic;

namespace JSP
{
    /// <summary>
    /// Extensions to the umbraco framework.
    /// </summary>
    public static class GuidExtensions
    {

        /// <summary>
        /// Get a node by the unique Guid.  This is needed for sites where courier is in use.
        /// </summary>
        /// <param name="self">Current Page</param>
        /// <param name="guid">Guid to load.</param>
        /// <returns>DynamicNode</returns>
        public static DynamicNode NodeByGuid(this DynamicNode self, string guid)
        {
            return self.NodeByGuid(new Guid(guid));
        }

        /// <summary>
        /// Get a node by the unique Guid.  This is needed for sites where courier is in use.
        /// </summary>
        /// <param name="self">Current Page</param>
        /// <param name="guid">Guid to load.</param>
        /// <returns>DynamicNode</returns>
        public static DynamicNode NodeByGuid(this DynamicNode self, Guid guid)
        {
            return self.NodeById(new CMSNode(guid).Id);
        }

        /// <summary>
        /// Get the unique ID for a selected node.
        /// </summary>
        /// <param name="self">Node</param>
        /// <returns>guid</returns>
        public static string UniqueId(this DynamicNode self)
        {
            return new CMSNode(self.Id).UniqueId.ToString();
        }
    }
}

Edit Macros that are Cached in Umbraco

One of the really annoying problems in Umbraco is that is when editing Macro Scripting Files for Macros that are cached your changes will not appear until the cache expires and is rebuilt.  To get around this you have to go and turn off caching on the macro that you are working on and then remember to turn it back on when done.

A much nicer solution to this problem is simply to clear out the cached versions of the macro whenever its script file is saved.  In this way the new version of the macro will always be displayed when refreshing the page after any changes.  This code can be added to the App_Code directory of an umbraco install to do jus that.

ClearMacroCache.cs
using System.Web;
using umbraco.BusinessLogic;
using umbraco.IO;
using System.IO;
using System.Web.Hosting;
using ClientDependency.Core.Config;
using System.Text.RegularExpressions;
using System.Linq;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.cache;

namespace JSP
{
    public class ClearMacroCache : ApplicationBase
    {
        public ClearMacroCache()
        {
            // Get the macro folder.
            var macroPath = HttpContext.Current.Server.MapPath(SystemDirectories.MacroScripts);

            // Watch for file changes ot any macros.
            HttpContext.Current.Application.Add("macroWatcher", new FileSystemWatcher(macroPath));
            var macroFsw = (FileSystemWatcher)HttpContext.Current.Application["macroWatcher"];
            macroFsw.EnableRaisingEvents = true;
            macroFsw.IncludeSubdirectories = true;

            // Trigger an event on any change.
            macroFsw.Changed += new FileSystemEventHandler(expireClientDependency);
            macroFsw.Created += new FileSystemEventHandler(expireClientDependency);
            macroFsw.Deleted += new FileSystemEventHandler(expireClientDependency);
        }

        /// <summary>
        /// This method is called each time a macro file is saved/updated and will clear out and cached versions 
        ///     of the macro to eliminate cacheing problems when developing macros.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void expireClientDependency(object sender, FileSystemEventArgs e)
        {
            // If this is a real macro file.
            Regex reg = new Regex(@"\d+_");
            if(!reg.Match(e.Name).Success)
            {
                var macro = Macro.GetAll().SingleOrDefault(i => i.ScriptingFile.ToLower() == e.Name.ToLower());

                if (macro != null)
                    Cache.ClearCacheByKeySearch("macroHtml_" + macro.Alias);
            }
        }
    }
}