Code Sprouts

Wholesome Bits Of Tech

View LINQ To SQL Statements Using A Debug TextWriter

clock December 2, 2009 17:02 by author ColinW

When developing a LINQ to SQL data access layer, a common debugging task is to view the actual SQL statements developed by the LINQ to SQL runtime.  There are a variety of ways to do it, such as running a SQL trace or using the LINQ to SQL Debug Visualizer, but the one I find most practical and easy to use is to write the T-SQL directly to the Visual Studio output window. 

The LINQ To SQL team had the foresight to allow the capture of statements, which is simply done by attaching a class implementing System.IO.TextWriter to the .Log property of the DataContext.

A simple implementation of this is the following DebugTextWriter:

public class DebugTextWriter : System.IO.TextWriter
{
    public override void Write(char[] buffer, int index, int count)
    {
        System.Diagnostics.Debug.Write(new String(buffer, index, count));
    }

    public override void Write(string value)
    {
        System.Diagnostics.Debug.Write(value);
    }

    public override Encoding Encoding
    {
        get { return System.Text.Encoding.Default; }
    }
}

To use the DebugTextWriter and direct the output to the window, all that is needed is to instantiate a DebugTextWriter object and set it to the .Log property:

#if DEBUG
            MyDataContext dataContext = new MyDataContext();
            dataContext.Log = new DebugTextWriter();
#endif

The purpose of the #if DEBUG ( and ending #endif ) is to ensure that this code is only compiled into the debug version of the assembly.  It is not compiled when the Release configuration is enabled. 

Once this code has been put in place, executing any LINQ to SQL query will result in the actual T-SQL statements executed being written in the output window when you attached to the debugger:

image

I find that enabling this code at the start of a project makes it a breeze to look at the native T-SQL being sent to the database during all of my debugging sessions.

- Colin



Resolve An Absolute Url To A Relative Url

clock November 4, 2009 16:33 by author ColinW

Typically Url resolving is done by going from relative to absolute, but there are a few cases where you need to go in the opposite direction.  One of those that I commonly see is when an application is using the Server.Transfer method, which only accepts relative Url’s.

To handle converting absolute url’s to relative ones, I’ve been using an extension method similar to the following:

public static string ResolveAbsoluteUrlToRelativeUrl(this Control control, string absoluteUrl)
{
    string relativeUrl = string.Empty;

    /* Build protocol + server name + port + application path */
    string protocol = control.Page.Request.ServerVariables["SERVER_PORT_SECURE"];
    if (protocol == null || protocol == "0")
        protocol = "http://";
    else
        protocol = "https://";

    /* If the port is null, default http or https, we don't need to add it */
    string port = control.Page.Request.ServerVariables["SERVER_PORT"];
    if (port == null || port == "80" || port == "443")
        port = "";
    else
        port = ":" + port;

    string server = control.Page.Request.ServerVariables["SERVER_NAME"];
    string applicationPath = control.Page.Request.ApplicationPath;

    string serverPath = protocol + server + port + applicationPath;

    /* If we don't find the serverPath at the beginning of the Url, 
     * we'll just return the passed in absolute */
    if (absoluteUrl.ToLower().StartsWith(serverPath.ToLower()))
        relativeUrl = "~" + absoluteUrl.Remove(0, serverPath.Length);
    else
        relativeUrl = absoluteUrl;

    return relativeUrl;
}

The code is relatively* straight-forward, and gracefully returns the absolute Url if the relative one cannot be formed.  Since the code requires access to the current request object, making the entire method an extension keeps the code a bit more elegant and enforces that it can only be called in the correct environment.

- Colin

* pun intended!



Mass-Delete Comments in DotNetBlogEngine

clock September 21, 2009 15:43 by author ColinW

I’ve recently been under heavy comment spam, and along with taking preventive steps to keep the spam from occurring ( posts are now moderated ), I also built an admin page to allow me to mass-delete comments:

image

Right now it’s just a simple aspx page w/ code-behind, all you need to do is drop it into the /admin/pages directory of your site, and if you’re logged in as an admin, you’ll be able to access it by going to http://www.yoursiteurl/admin/pages/CommentManager.aspx

The page files can be downloaded here.

Depending upon how you have your site configured, you may need to set the web.config to compile under 3.5, which can be done by adding the following to your web.config, nested directly in the <configuration> section:

<system.codedom>
  <
compilers>
    <
compilerlanguage="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,
              System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
"
              warningLevel="4">
      <
providerOption name="CompilerVersion" value="v3.5"/>
      <
providerOption name="WarnAsError" value="false"/>
    </
compiler>
    <
compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
              type="Microsoft.VisualBasic.VBCodeProvider, System,
              Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
"
              warningLevel="4">
      <
providerOption name="CompilerVersion" value="v3.5"/>
      <
providerOption name="OptionInfer" value="true"/>
      <
providerOption name="WarnAsError" value="false"/>
    </
compiler>
  </
compilers>
</
system.codedom>
<
runtime>
  <
assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <
dependentAssembly>
      <
assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
      <
bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
    </
dependentAssembly>
    <
dependentAssembly>
      <
assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
      <
bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
    </
dependentAssembly>
  </
assemblyBinding>
</
runtime>

If anyone is interested in using the comment manager as a plugin, let me know, it’d be a fun exercise to go through ( and blog about! ).

- Colin



ASP.Net MVC 2 Preview 1

clock August 3, 2009 15:11 by author ColinW

I’m a few days late with relaying the announcement, but Scott Guthrie posted up on preview 1 of ASP.Net MVC V2.  It’s quite early in the cycle, but I”m really looking forward to areas, data annotations, and editor templates.

Read more on ScottGu’s blog



Perform An Action Using The Thread Pool

clock July 31, 2009 12:48 by author ColinW

I ran across a scenario where I needed to call dynamically created Action’s in a threaded manner, and was surprised at how simple the code was to do it:

public static void QueueAction(Action action)
{
    System.Threading.WaitCallback callback = state => action();
    System.Threading.ThreadPool.QueueUserWorkItem(callback);
}

 

Which can then be called in a variety of ways:

Action action = delegate() { System.Threading.Thread.Sleep(1000); };
QueueThread(action);
            
QueueThread(() => System.Threading.Thread.Sleep(1000));
            
QueueThread(randomUnknownMethod);

 

I won’t make the claim that this is “production worthy” code, but if you’re looking for a quick way to execute an Action on a new thread, it does a pretty fine job.  One thing to note: I used the ThreadPool in this example as it’s typically safer than firing up new Threads from the Thread object, but feel free to improvise.

- Colin



The Exception Catcher

clock July 5, 2009 09:10 by author ColinW

Download the code here.

While working on a recent gig, one of the requirements for the code I was developing was to have extensive logging, on both new code being developed & on the existing codebase.   Due to the mix of new & old code, a lot of files ended up being cluttered with try…catch blocks:

try
{
    /* Relatively Simple Operation(s) */
}
catch (Exception ex)
{
    /* Logging Routines... */

    /* UI Error Display... */
}

While there’s nothing wrong with multiple try/catch blocks, in this particular application they were causing quite a bit of code duplication in the logging & UI display code.  To reduce the code duplication and make the code a bit more readable, I created an ExceptionCatcher class to wrap up the duplicated code and reduce most of the previous multiple line try/catch blocks to just a few lines ( typically turning into 1-liners). 

The ExceptionCatcher is fairly simple, as it is essentially just a single method call that takes an Action, which it executes in the context of its own try/catch block.

A typical line of code looks something like this:

ExceptionCatcher.Try<BusinessException>(() => { saveBusinessObject(); });

In this call, the ExceptionCatcher will catch BusinessExceptions and then perform any logic in its own Catch block.  The Try method does return an ExceptionCatcherResult to let the calling code know about any exception that occurred, however there typically wasn’t any necessity to do so.  There’s also an overload on the Try method to rethrow the Exception, to handle cases where you need to perform some action and then let the exception continue to bubble up through the code.

I’ve included a sample project that demo’s a simpler version of the ExceptionCatcher.  The core functionality is housed in the ExceptionCatcher class, and contains a few overloads to handle the scenarios above. 

You can download the code here.

Feel free to send any questions or comments to me using the comments link on this post!

- Colin



Implement An Interface With An Anonymous Object

clock June 1, 2009 14:06 by author ColinW

I’m a big fan of anonymous objects ( the ASP.Net MVC framework seems to beckon for their use, especially when working with asynchronous server calls that return objects to serialize in JSON ).  However, one of the drawbacks is that they can only really be defined & used within the context of a single method.  Because of this, if you need to call another function with the contents of the object, you’ll either have to create a custom object or settle with passing delegates or lambda’s in to that function.

I’ve frequently lamented to my fellow co-workers at Magenic that life would be oh-so-sweet if we were able to inherit interfaces with an anonymous object.  While I just assumed that I was at the mercy of the compiler team to make that happen, I realized that I can do it myself by dynamically building a type at runtime and populating it with the values inside my anonymous object.

As a proof of concept, I wrote the following code that creates a dynamic implementation of an interface, and then assigns the values of an anonymous object to that dynamic implementation.

The code is as follows ( commented for clarity! ):

public interface IRandom
{
    int Number { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            IRandom random = ConvertAnonymousTypeToInterface<IRandom>(new { Number = 3 });
            Console.WriteLine("Value of random = " + random.Number.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }

        Console.ReadLine();
    }

    static T ConvertAnonymousTypeToInterface<T>(object data) where T : class
    {
        // A little error checking
        if (!typeof(T).IsInterface)
            throw new InvalidOperationException("T must be an interface");

        if (!typeof(T).IsPublic)
            throw new InvalidOperationException("T must be a public interface");

        string typeName = typeof(T).Name;

        // We need an assembly to generate our type in
        AssemblyName assemblyName = new AssemblyName("AnonymousInterfaceAssembly");
        assemblyName.Version = new Version("1.0.0.0");

        // We need a few builders before we can build a type:
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly
            (assemblyName, AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule
            ("AnonymousInterfaceAssembly", "AnonymousInterfaceAssembly.dll");
        TypeBuilder typeBuilder = moduleBuilder.DefineType
            ("AnonymousInterfaceAssembly." + typeName, TypeAttributes.Public, typeof(object));

        // Now we can get on with building an object that implements the interface.
        // First we'll tell the runtime we want to implement the interface passed in
        typeBuilder.AddInterfaceImplementation(typeof(T));

        // We'll be fine with a default constructor
        typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);

        // Implement interface members :o

        // Pull the properties & loop through them
        PropertyDescriptorCollection interfaceProperties = 
            TypeDescriptor.GetProperties(typeof(T));

        foreach (PropertyDescriptor interfaceProperty in interfaceProperties)
        {
            // First we'll define a new field to hold our property
            FieldBuilder propertyFieldBuilder = typeBuilder.DefineField
                ("_" + typeName, interfaceProperty.PropertyType, FieldAttributes.Private);

            // Our get & set methods need a few attributes
            MethodAttributes getSetMethodAttributes = 
                MethodAttributes.Public | MethodAttributes.Virtual;

            // implementing our inteface requires a get method named 'get_PROPERTYNAME' 
            // ( where PROPERTYNAME is really the property name. )
            MethodBuilder propertyGetMethod = typeBuilder.DefineMethod(
                "get_" + interfaceProperty.Name, getSetMethodAttributes, 
                interfaceProperty.PropertyType, Type.EmptyTypes);
            
            ILGenerator getMethodGenerator = propertyGetMethod.GetILGenerator();

            // our get consists of loading the field & returning
            getMethodGenerator.Emit(OpCodes.Ldarg_0);
            getMethodGenerator.Emit(OpCodes.Ldfld, propertyFieldBuilder);
            getMethodGenerator.Emit(OpCodes.Ret);

            // that's it for the get method, on to the set
            MethodBuilder propertySetMethod = typeBuilder.DefineMethod(
                "set_" + interfaceProperty.Name, getSetMethodAttributes, 
                null, new Type[] { interfaceProperty.PropertyType });

            ILGenerator setMethodGenerator = propertySetMethod.GetILGenerator();

            // The code is basically the same ( just in the other direction ), 
            // however we'll have an actual argument coming in ( to set the value )
            setMethodGenerator.Emit(OpCodes.Ldarg_0);
            setMethodGenerator.Emit(OpCodes.Ldarg_1);
            setMethodGenerator.Emit(OpCodes.Stfld, propertyFieldBuilder);
            setMethodGenerator.Emit(OpCodes.Ret);

            // And we're finished!
        }

        // Let's build our object

        Type anonymousInterfaceType = typeBuilder.CreateType();

        // set values

        T instance = Activator.CreateInstance(anonymousInterfaceType) as T;

        foreach (PropertyDescriptor interfaceProperty in interfaceProperties)
        {
            PropertyInfo dataProperty = data.GetType().GetProperty(interfaceProperty.Name);
            object value = dataProperty.GetValue(data, null);

            // Find the set method we just built:
            MethodInfo setterMethod = anonymousInterfaceType.GetMethod(
                "set_" + interfaceProperty.Name);

            setterMethod.Invoke(instance, new object[] { value });
        }

        return instance;
    }
}

A couple things to note:

  • I created this code only as a proof that the concept, and there’s quite a bit of error checking left out ( and potentially quite a few bugs left in )
  • What I’ve written above is basically ‘mocked’ the interface, so the same thing could be achieved through the use of any of the various mocking frameworks available.

- Colin



Quick Tip: Injecting Script From C#

clock May 18, 2009 08:07 by author ColinW

I’ve developed quite a few extensions working with the ASP.Net MVC framework ( don’t worry, I’ll roll them out as I clean them up and make the more useful for mass-consumption ).  I almost always need to inject some javascript into the page in these extensions, and I’ve found literal strings ( using @ before a string ) to be quite handy for development.

For example, imagine a script block similar to the following:

<script type="text/javascript">
    $('#divToShow').show();
    $('#divToHide').hide();
</script>

Without using string literals, you’ll need to do something like the following:

"<script type=\"text/javascript\">" + Environment.NewLine +
" $('#divToShow).show();" + Environment.NewLine +
" $('#divToHide).hide();" + Environment.NewLine +
"</script>"

Using string literals:
 
@"<script type=""text/javascript"">
$('#divToShow').hide();
$('#divToHide').show();
</script>"

Much cleaner!
 
It may look subtle, but using string literals throughout the development of my extensions has made things much easier to enhance, refine, and (gasp!) debug.
 
What do you think?
 
- Colin


Sorting By String In LINQ

clock May 15, 2009 08:44 by author ColinW

When implementing a sorting feature in most UI’s, the sorting expression is typically string based.  When you’re using LINQ this becomes a problem due to the sorting methods requiring a lambda function with a typed field name.

While working on a project recently, a colleague and I came up with a pretty elegant solution that uses reflection to turn the fieldname in string form into an acceptable lambda expression. 

The code is pretty compact, so I’ve included it below and added comments to what’s going on:

public static class SortingExtensions
{
    public static IQueryable<T> OrderByFieldName<T>
        (this IQueryable<T> query, string fieldName, bool isSortAscending)
    {
        // Find the field we're sorting on and get it's type
        Type fieldType = typeof(T).GetProperty(fieldName).PropertyType;

        // Find the generic sort method. Note the binding flags 
        // since our particular sort method is marked as private & static
        MethodInfo sortItMethod = typeof(SortingExtensions)
            .GetMethod("SortIt", BindingFlags.Static | BindingFlags.NonPublic);

        // The method returned is an open generic, 
        // so let's close it with the types we need for this operation
        sortItMethod = sortItMethod.MakeGenericMethod(typeof(T), fieldType);

        // Now that we have our closed generic type, 
        // we can invoke it with the specified parameters 
        query = (IQueryable<T>)sortItMethod
            .Invoke(null, new object[] { query, fieldName, isSortAscending });

        return query;
    }

    private static IQueryable<T> SortIt<T, K>
        (IQueryable<T> query, string sortFieldName, bool isSortAscending)
    {
        // The orderby works by examining the lambda passed and looking that the body
        // for the property name and variable type.
        // In order to supply a lambda, we'll need to build one.

        // The parameter will be the left-hand side of the lambda expression
        ParameterExpression param = Expression.Parameter(typeof(T), "x");

        // The body will be the right-hand side of the lambda expression
        MemberExpression body = Expression.Property(param, sortFieldName);

        // We'll build our lambda expression, 
        // first passing in the body and then the parameter
        var sortExpression = Expression.Lambda<Func<T, K>>(body, param);

        // All that's left to do is calling the correct extension method for ordering
        if (isSortAscending)
            return query.OrderBy<T, K>(sortExpression);
        else
            return query.OrderByDescending<T, K>(sortExpression);
    }
}

The code works in all the situations we’ve tested it in ( LINQ to objects, LINQ to SQL ), and considering reflection is used in the operation, we’re rather proud of it.  A possible performance enhancement left out of this solution would be to cache the MethodInfo for the open generic type to avoid having to reflect every time to find the method, but the overhead is rather minimal in this situation.

Side Note:

After we developed our solution, we ran across a post from Scott Guthrie, that enlightened us to the existence of the Dynamic LINQ Library, which adds string-based support similar to what we’ve done here, however this code is more narrow focused for sorting operations, and is a bit different than the Dynamic LINQ Library.

- Colin



ASP.Net MVC Repeater Extension

clock May 8, 2009 05:58 by author ColinW

Download the code!

When working in the View of an MVC project, you’ll frequently need to iterate through a list of items.  If all you need to do is output the exact same markup for every item, a foreach will serve you well.  However, it’s extremely common that you’ll need to generate some sort of alternating sequence for those items, and the foreach quickly turns rather unwieldy ( normally turning into a simpler for loop and having quite a few conditional statements and temporary variables ).

Since I frequently run into the situation that I need to generate alternating ‘templates’ for collections of data, I’ve created a simple Repeater extension to handle the task.

The Repeater Extension

The Repeater is a relatively simple extension, however it does contain the following functionality:

  • Works with any enumerable class
  • Accepts a string or action to generate markup
  • Supports adding custom markup for the beginning & ending of an ‘item’, allowing you to use the same template for both all items.

Syntax:

<div style="width: 100px;">
    <% this.Html.Repeater((IEnumerable<string>)this.ViewData["ItemData"])
       .BeginTemplate("<div style='border: solid 1px blue;'>")
       .BeginAlternatingTemplate("<div style='border: solid 1px red;'>")
       .Template(item =>
       {
    %>
        <div style="margin: 2px; padding: 4px; border: dashed 1px black;">
            <%= item%>
        </div>
    <% 
        })
       .AlternatingTemplate(item =>
       {
    %>
        <div style="text-align: right;">
            <%= item %>              
        </div>
    <%
       })
       .EndTemplate("</div><br />")
       .Render();
    %>
</div>

Output from the above example:

image

While there’s support for a custom alternating template, I’ve found that any style changes you want to make between regular/alternating items can be done through BeginTemplate / BeginAlternatingTemplate.

Using The Repeater In Your Own Project

Download the code first.

The Repeater is contained in the MvcExtensions project.  You’ll need to either add the project to your solution or pull out the dll it generates and add then add a reference to the project or dll:

image

Add a namespace entry to your root web.config namespaces element:

<add namespace="MvcExtensions.Repeater"/>

After the reference has been added and the namespace is inserted into the web.config, you should see it show up in auto-complete when writing script code in the view ( might take a bit for autocomplete to recognize the extension):

image

And you’re ready to go!

If you have any questions or comments, feel free to leave a comment or send me an email!

- Colin