Tuesday, March 12, 2013

Monday, March 11, 2013

Using LINQ to SQL for clean and quick Database Access/Interactions.

Update: October 26, 2016 - I would now recomend using this replacement guide using the built in PetaPoco instead of this method as it is much cleaner and requires significantly less DBA code and produced much smaller binaries.  There are also T4 Templates that will generate models form your database so you can design in code and generate database constructs automatically, or create tables and then auto-generate code form those, whichever way you prefer.  I still use the Columns features below for when creating forms.

This post is a demonstration/instructions for very easily and cleanly working with SQL data in a .NET application using LINQ to SQL.  There are lots of resources out there about this technology but my goal here is to present a very clean and thin interface to utilizing LING to SQL.  Read on for explanations and samples.

Thursday, January 31, 2013

jQuery Vertical Totem Ticker Plugin - Updated

I found this nice jQuery plugin Totem Animated Vertical Ticker.  but it doesn't seam to have some options I needed.  As it does not appear to be to active I made some customizations myself to add the following options.

- Added support for mouse whee scrolling.
- Tickers now all get the vTicker class for css markup.

- If a row height is specified that the items are now actually restricted to that height. Add the following css to make longer items scroll properly.
.vTicker li { overflow: hidden; }

- Added helper methods for easy scripting of the ticker.
$(selector).totemticker("start");
$(selector).totemticker("stop");
$(selector).totemticker("previous");
$(selector).totemticker("next");

The new version is available on GitHub at https://github.com/pynej/totem.

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");
}