Monday, October 1, 2012

Automatic Unobtrusive Binding of Labels to Form Elements

One commonly forgotten feaure in HTML is that when creating web forms the labels related to input elements should be related to them.  In the simplest terms it is done like so:

<label for="myItem">My Label</label><input id="myItem">
The benifit to doing this is that browser will automatically focus the input element when the label is selected.  A little thing I know but it's not use in most sites doe to inconvenience.

Thus I have the following bit of javascript to automatically do the same thing.  It looks for any unbound  labels and binds them to the next input, text area, or select item down the DOM tree from them.  That is the next matching element within the same parent that the label is in.  This method will also work if the input fields don't have ID's associated with them as an added bonus.

 To use just include this in a global script running on your site and it will do the work with no noticeable overhead.  This does require jQuery to work.
$(document).ready(function () {
  $("form label").each(function() {
    if (typeof $(this).attr("for") == "undefined" || $("#" + $(this).attr("for")).length == 0) {
      nextControl = $(this).next("input,textarea,select");
      if (nextControl.length > 0) {
        if (typeof nextControl.attr("id") != "undefined") {
          $(this).attr("for", nextControl.attr("id"));
        } else {
          $(this).removeAttr("for");
          $(this).click(function() {
            $(this).next("input,textarea,select").focus()
          });
        }
      }
    }
  });
});

Monday, September 24, 2012

LINQ OrderBy sorting without a Strong Typed parameter expression.

When setting up a simple ASPX page with a DataGrid to quickly display a LINQ to SQL result without having to write a bunch of paging and sorting code I ran into a bit of an issue. The loading and paging worked perfectly with the following sample but I could not get sorting to work and a clean and concise manner.

<asp:DataGrid ID="Data" runat="server" AllowPaging="True" AllowSorting="True" 
    onpageindexchanged="Data_PageIndexChanged" onsortcommand="Data_SortCommand">
</asp:DataGrid>
FormLandingPageRepository repo = new FormLandingPageRepository();

protected void Page_Load(object sender, EventArgs e)
{
    Data.DataSource = repo.Find().OrderByDescending(i => i.dateAdded);
    Data.DataBind();
}

protected void Data_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
    Data.CurrentPageIndex = e.NewPageIndex;
    
    Data.DataSource = repo.Find().OrderByDescending(i => i.dateAdded);
    Data.DataBind();
}

protected void Data_SortCommand(object source, DataGridSortCommandEventArgs e)
{     
    repo.Find().OrderBy(e.SortExpression);
    Data.DataBind();
}

The problem turned out to be that the OrderBy operations in LINQ require strong types clauses in Expressions but my DataGrid is returning a simple string as the order by expression.  I could get around this by creating a switch statment and converting to a Strong Typed expression but that would require a lot of hard coded logic for every table.

Instead I found this Extensions after much searching and testing that adds the ability to do OrderBy statements in LINQ with a string value instead.  Thus after adding the Extension code the above sort by works as exacted. (Note that the sort expression will need to be stored in the ViewState and sorting logic applied in PageIndexChanged as well for Paging+Sorting to work.)

SortExstensions.cs
using System;
using System.Text.RegularExpressions;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace JSP
{
    public static class SortExtensions
    {
        /// <summary>
        /// Sort Directions.
        /// </summary>
        enum SortMode
        {
            OrderBy,
            OrderByDescending,
            ThenBy,
            ThenByDescending
        }

        /// <summary>
        /// Sorts the elements of a sequence in ascending order according to a key.
        /// </summary>
        /// <typeparam name="T">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to order.</param>
        /// <param name="property">Property name to sort on.</param>
        /// <returns>An System.Linq.IOrderedQueryable<T> whose elements are sorted according to a key.</returns>
        public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
        {
            // If this is a sort list then OrderBy the first element and then ThenBy the rest.
            if (property.Contains(','))
            {
                string[] parts = property.Split(new char[] {','}, 2);
                return ApplyOrder<T>(source, parts[0], SortMode.OrderBy).ThenBy(parts[1]);
            }
                
            return ApplyOrder<T>(source, property, SortMode.OrderBy);
        }

        /// <summary>
        /// Sorts the elements of a sequence in descending order according to a key.
        /// </summary>
        /// <typeparam name="T">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to order.</param>
        /// <param name="property">Property name to sort on.</param>
        /// <returns>An System.Linq.IOrderedQueryable<T> whose elements are sorted according to a key.</returns>
        public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
        {
            // If this is a sort list then OrderBy the first element and then ThenBy the rest.
            if (property.Contains(','))
            {
                string[] parts = property.Split(new char[] { ',' }, 2);
                return ApplyOrder<T>(source, parts[0], SortMode.OrderByDescending).ThenByDescending(parts[1]);
            }

            return ApplyOrder<T>(source, property, SortMode.OrderByDescending);
        }

        /// <summary>
        ///  Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.
        /// </summary>
        /// <typeparam name="T">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to order.</param>
        /// <param name="property">Property name to sort on.</param>
        /// <returns>An System.Linq.IOrderedQueryable<T> whose elements are sorted according to a key.</returns>
        public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
        {
            // If ther are multiple sort items then sort by each in order.
            if (property.Contains(','))
            {
                string[] parts = property.Split(new char[] { ',' }, 2);
                return ApplyOrder<T>(source, parts[0], SortMode.ThenBy).ThenBy(parts[1]);
            }

            return ApplyOrder<T>(source, property, SortMode.ThenBy);
        }

        /// <summary>
        ///  Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.
        /// </summary>
        /// <typeparam name="T">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to order.</param>
        /// <param name="property">Property name to sort on.</param>
        /// <returns>An System.Linq.IOrderedQueryable<T> whose elements are sorted according to a key.</returns>
        public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
        {
            // If ther are multiple sort items then sort by each in order.
            if (property.Contains(','))
            {
                string[] parts = property.Split(new char[] { ',' }, 2);
                return ApplyOrder<T>(source, parts[0], SortMode.ThenByDescending).ThenByDescending(parts[1]);
            }

            return ApplyOrder<T>(source, property, SortMode.ThenByDescending);
        }

        /// <summary>
        /// Apply a custom Order By statment to an IQueryable.
        /// </summary>
        /// <typeparam name="T">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to order.</param>
        /// <param name="property">Property name to sort on.</param>
        /// <param name="methodName">Sort method to use.</param>
        /// <returns>An System.Linq.IOrderedQueryable<T> whose elements are sorted according to a key.</returns>
        static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, SortMode methodName)
        {
            string[] props = property.Split('.');

            Type type = typeof(T);
            ParameterExpression arg = Expression.Parameter(type, "x");
            Expression expr = arg;

            foreach (string prop in props)
            {
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }

            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

            object result = typeof(Queryable).GetMethods().Single(
                    method => method.Name == methodName.ToString("g")
                            && method.IsGenericMethodDefinition
                            && method.GetGenericArguments().Length == 2
                            && method.GetParameters().Length == 2)
                    .MakeGenericMethod(typeof(T), type)
                    .Invoke(null, new object[] { source, lambda });
            return (IOrderedQueryable<T>)result;
        }
    }
}

Friday, September 7, 2012

Thursday, August 30, 2012

Maximum File Upload Size in IIS 7

I have investigated and done a lot of testing as the information online is somewhat inaccurate/misleading.  In the end i Determined that the following setting all need to be configured to allow for large file uploads.  If not the default settings will stop uploads greater then about 20 MB.

The following change need made to the web.config file.
<system.web>
    <httpRuntime requestValidationMode="2.0" executionTimeout="600" maxRequestLength="2000000" />
  <system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2000000000" />
      </requestFiltering>
    </security>
  </system.webServer>

The executionTimeout is extending the maximum script execution to 10 minutes witch will be required for larger uploads.  The maxRequestLength is the maximum size in kilobytes while the maxAllowedContentLength is the same maximum size but in bytes.  So maxAllowedContentLength should be 1000 times the maxRequestLength.

These numbers of course can be adjusted as needed.

On a final note you may want to check C:\Windows\System32\inetsrv\config\applicationHost.config and verify that the following line is present and set to Allow.
<section name="requestFiltering" overrideModeDefault="Allow" />

Umbraco Using Courier to Deploy MultiType Data

When using Umbraco and doing production deployments with the Courier package I ran into an issue.  We have had the process working fine with built in components but recently I deployed a new property that used the MultiType DataType which  allows for arrays of data fields grouped together.  For example we have the following grouping and multiple images can be added to the one parameter in Umbraco.

RotatingImages
  Item
    ImageSrc(Media Picker)
    MobileSrc(Media Picker)
    AltText(Text)
    LinkTo(Content Picker)

The problem comes in when we publish this item, the content and media pickers contain the node id's and the data is stored as XML.  As such Courier will not process the ID's when it does the deployment process.  To fix this a custom PropertyDataResolverProvider is needed.  The following code can be included in the App_Code directory to fix this problem.



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 MultiType data objects.  Will convers a list of xml nodes to guids for deployment and back again.
    /// </summary>
    public class MultiType : PropertyDataResolverProvider
    {
        /// <summary>
        /// The datatype guid of the multitype item we are running on.
        /// </summary>
        public override Guid DataTypeId
        {
            get { return new Guid("f17bb230-3941-4813-a923-e7c3efd067d8"); }
        }

        /// <summary>
        /// Get the xpath elements from the data types that contain document or media id's.
        /// </summary>
        /// <param name="propertyData">Property to examin.</param>
        /// <param name="documentXPath">XPath string to select all fields with document ID's.</param>
        /// <param name="mediaXPath">XPath string to select all fields with media ID's.</param>
        private void GetXPath(ContentProperty propertyData, out string documentXPath, out string mediaXPath)
        {
            // Get the data definition for this item.
            var dataDefinition = new umbraco.cms.businesslogic.datatype.DataTypeDefinition(propertyData.DataType);
            
            // Get the item configureation and locate the preValue property.
            var preValue = umbraco.library.GetPreValues(dataDefinition.DataType.DataTypeDefinitionId);
            preValue.MoveNext();
            var preValueIterator = preValue.Current.SelectChildren("preValue", "");
            preValueIterator.MoveNext();

            // Deserialize the preValue data.
            dynamic data = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(preValueIterator.Current.Value);
            // Get the MultiType Children properties.
            var mprop = ((object[])((Dictionary<string, object>)data)["MultiTypes"]).Cast<Dictionary<string, object>>();
            
            // Get all content picker properties and add the alias to the list.  Resutls: //Node1 | //Node2 | ...
            documentXPath = String.Join(" | ", mprop.Where(i => Convert.ToInt32(i["Type"]) == (int)_4Ben.DataTypes.MultiType.ControlType.ContentPicker).Select(i => "//" + i["Alias"].ToString()));
            // Get all media picker properties and add the alias to the list.  Resutls: //Node1 | //Node2 | ...
            mediaXPath = String.Join(" | ", mprop.Where(i => Convert.ToInt32(i["Type"]) == (int)_4Ben.DataTypes.MultiType.ControlType.MediaPicker).Select(i => "//" + i["Alias"].ToString()));
        }

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

            // Get the elements from this data type that need to be converted.  This could be hard coded but the queries are quick.
            GetXPath(propertyData, out documentXpath, out mediaXpath);

            // Document References
            List<string> replacedIds = new List<string>();
            propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), documentXpath, 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);
            }

            // Media References
            //dataXpath = ConfigurationManager.AppSettings["courierMultiTypeMediaNodes"].ToString();
            replacedIds = new List<string>();
            propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), mediaXpath, 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.mediaItemProviderGuid);

                // Could add as a resource but in reality the entire node is needed witch wil transwer the resource so this line should not be run.
                //item.Resources.Add(new umbraco.cms.businesslogic.media.Media(new Guid(guid)).getProperty("umbracoFile").Value.ToString());
            }
        }

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

            // Get the elements from this data type that need to be converted.  This could be hard coded but the queries are quick.
            GetXPath(propertyData, out documentXpath, out mediaXpath);

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

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

        }
    }
}