Tag Archives: C#

Using EFProf and MiniProfiler simultaneously in an ASP.NET MVC 5.1, Entity Framework 5 Code-First Project

We’re already using the excellent Entity Framework Profiler (EFProf) to gauge EF performance in our application. However, we wanted more information about the overall application performance, and thus turned to MiniProfiler.

Installing MiniProfiler was easy enough, but upon running the application, I got an error:

Unable to determine the provider name for connection of type ‘HibernatingRhinos.Profiler.Appender.ProfiledDataAccess.ProfiledConnection`1[[System.Data.SqlClient.SqlClientFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]’.

Hmm. That’s weird. So I commented out my EFProf initialization code:

//EntityFrameworkProfiler.Initialize();

And MiniProfiler worked fine.

I then wrote a test application to try to isolate the problem, and got a different error:

System.NotSupportedException: Underlying ProfiledCommand is not cloneable

It turns out that MiniProfiler expects its DbCommand to implement ICloneable:

/// <summary>
/// clone the command, entity framework expects this behaviour.
/// </summary>
/// The .
public ProfiledDbCommand Clone()
{ // EF expects ICloneable
    var tail = _command as ICloneable;
    if (tail == null) throw new NotSupportedException("Underlying " + _command.GetType().Name + " is not cloneable");
    return new ProfiledDbCommand((DbCommand)tail.Clone(), _connection, _profiler);
}

Unfortunately, dotPeek reveals that EFProf’s ProfiledCommand does not implement ICloneable:

namespace HibernatingRhinos.Profiler.Appender.ProfiledDataAccess
{
  public class ProfiledCommand : DbCommand
  {
  // ...
  }
}

Fortunately, there is a workaround: initialize MiniProfiler before initializing EFProf. Or, in source code form, do this in Global.asax:

protected void Application_Start()
{
    // ...

    MiniProfiler.Settings.SqlFormatter = new StackExchange.Profiling.SqlFormatters.SqlServerFormatter();
    MiniProfilerEF.Initialize();

    EntityFrameworkProfiler.Initialize();
}

Instead of this:

protected void Application_Start()
{
    // ...

    EntityFrameworkProfiler.Initialize();

    MiniProfiler.Settings.SqlFormatter = new StackExchange.Profiling.SqlFormatters.SqlServerFormatter();
    MiniProfilerEF.Initialize();
}

And EFProf and MiniProfiler will coexist happily together.

(Note that this means EFProf initialization happens in Global.asax instead of in PreApplicationStartMethod installed by the EFProf NuGet package.)

Version information:

  • ASP.NET MVC 5.1.0
  • Entity Framework 5.0.0
  • EFProf Build 2225
  • MiniProfiler 2.1.0

Cannot find 'servicereferences.clientconfig' in the .xap application package

I’m new to Silverlight development.  I was banging my head against the wall, trying to figure out what I had done to break our Silverlight app.  After all, the only changes I made were to add a Service Reference to a new WCF service, and to initialize the WCF proxy in App.xaml.cs.

Fortunately, after a little Google sleuthing, I came upon the solution, as shared by David Sandor:

[The code] is trying to read from the ServiceReferences.config file that can not be read at that point in the Silverlight application’s lifecycle.

Bingo, that was it.  Moving my proxy initialization code to Application_Startup fixed the problem.

It makes sense now, but, man, these types of bugs can be maddening.

ImageCodecInfo: Encoder and Decoder information

If you’ve ever been curious about the GDI+ encoders and decoders available on your system, you can call ImageCodecInfo.GetImageEncoders() and ImageCodecInfo.GetImageDecoders(), respectively, to find out more:

Encoders:

ImageCodecInfo.GetImageEncoders().ToList().ForEach(
    enc =>
    {
        Console.WriteLine(enc.FormatDescription);
        Console.WriteLine("tCLSID: {0}", enc.Clsid);
        Console.WriteLine("tCodecName: {0}", enc.CodecName);
        Console.WriteLine("tFilenameExtension: {0}", enc.FilenameExtension);
        Console.WriteLine("tFlags: {0}", enc.Flags);
        Console.WriteLine("tFormatDescription: {0}", enc.FormatDescription);
        Console.WriteLine("tFormatID: {0}", enc.FormatID);
        Console.WriteLine("tMimeType: {0}", enc.MimeType);
        Console.WriteLine("tVersion: {0}", enc.Version);
    });

On my Windows Server 2008 machine, the above code returns the following:

BMP
        CLSID: 557cf400-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in BMP Codec
        FilenameExtension: *.BMP;*.DIB;*.RLE
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: BMP
        FormatID: b96b3cab-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/bmp
        Version: 1
JPEG
        CLSID: 557cf401-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in JPEG Codec
        FilenameExtension: *.JPG;*.JPEG;*.JPE;*.JFIF
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: JPEG
        FormatID: b96b3cae-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/jpeg
        Version: 1
GIF
        CLSID: 557cf402-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in GIF Codec
        FilenameExtension: *.GIF
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: GIF
        FormatID: b96b3cb0-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/gif
        Version: 1
TIFF
        CLSID: 557cf405-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in TIFF Codec
        FilenameExtension: *.TIF;*.TIFF
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: TIFF
        FormatID: b96b3cb1-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/tiff
        Version: 1
PNG
        CLSID: 557cf406-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in PNG Codec
        FilenameExtension: *.PNG
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: PNG
        FormatID: b96b3caf-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/png
        Version: 1

Decoders:

ImageCodecInfo.GetImageDecoders().ToList().ForEach(
    enc =>
    {
        Console.WriteLine(enc.FormatDescription);
        Console.WriteLine("tCLSID: {0}", enc.Clsid);
        Console.WriteLine("tCodecName: {0}", enc.CodecName);
        Console.WriteLine("tFilenameExtension: {0}", enc.FilenameExtension);
        Console.WriteLine("tFlags: {0}", enc.Flags);
        Console.WriteLine("tFormatDescription: {0}", enc.FormatDescription);
        Console.WriteLine("tFormatID: {0}", enc.FormatID);
        Console.WriteLine("tMimeType: {0}", enc.MimeType);
        Console.WriteLine("tVersion: {0}", enc.Version);
    });

Again, on my Windows Server 2008 box, the above code returns the following:

BMP
        CLSID: 557cf400-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in BMP Codec
        FilenameExtension: *.BMP;*.DIB;*.RLE
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: BMP
        FormatID: b96b3cab-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/bmp
        Version: 1
JPEG
        CLSID: 557cf401-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in JPEG Codec
        FilenameExtension: *.JPG;*.JPEG;*.JPE;*.JFIF
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: JPEG
        FormatID: b96b3cae-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/jpeg
        Version: 1
GIF
        CLSID: 557cf402-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in GIF Codec
        FilenameExtension: *.GIF
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: GIF
        FormatID: b96b3cb0-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/gif
        Version: 1
EMF
        CLSID: 557cf403-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in EMF Codec
        FilenameExtension: *.EMF
        Flags: Decoder, SupportBitmap, Builtin
        FormatDescription: EMF
        FormatID: b96b3cac-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/x-emf
        Version: 1
WMF
        CLSID: 557cf404-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in WMF Codec
        FilenameExtension: *.WMF
        Flags: Decoder, SupportBitmap, Builtin
        FormatDescription: WMF
        FormatID: b96b3cad-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/x-wmf
        Version: 1
TIFF
        CLSID: 557cf405-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in TIFF Codec
        FilenameExtension: *.TIF;*.TIFF
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: TIFF
        FormatID: b96b3cb1-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/tiff
        Version: 1
PNG
        CLSID: 557cf406-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in PNG Codec
        FilenameExtension: *.PNG
        Flags: Encoder, Decoder, SupportBitmap, Builtin
        FormatDescription: PNG
        FormatID: b96b3caf-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/png
        Version: 1
ICO
        CLSID: 557cf407-1a04-11d3-9a73-0000f81ef32e
        CodecName: Built-in ICO Codec
        FilenameExtension: *.ICO
        Flags: Decoder, SupportBitmap, Builtin
        FormatDescription: ICO
        FormatID: b96b3cb5-0728-11d3-9d7b-0000f81ef32e
        MimeType: image/x-icon
        Version: 1

ImageCodecInfo is located in System.Drawing.Imaging.

Why am I writing this? On more than one occasion, I have found myself writing code to enumerate these values; I’d rather just have a place to look them up.

Project Euler: Problem 1 (in F#)

I have already done Project Euler Problem 1 in C#. Since I am currently learning F#, I thought I’d give it another shot:

let rec sumMultiples(data) =
    match data with
    | [] -> 0
    | head::tail when (head % 3 = 0 || head % 5 = 0) -> head + sumMultiples(tail)
    | _::tail -> sumMultiples(tail)

It produces the correct result, but seeing as how LINQ considerably simplified the C# version, and since I am a complete F# and functional programming n00b, I suspected there must be a better way.

I hate it when I’m right.

This solution is better, in my opinion:

List.sum(List.filter (fun n -> n % 3 = 0 || n % 5 = 0) [1..999]);;

Anyhow, I know I have a lot left to learn, so I’m looking forward to exploring the functional side of programming in the coming months.

Update 2010-01-08: Ooh, better yet:

[1..999] |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0) |> List.sum;;

Pipelining FTW!

GuidHelper.TryParse

Microsoft has apparently added Guid.TryParse() to .NET 4.0, but if you’re stuck using an older version of the framework, you’re still kind of left flapping out in the wind.  Luckily, the great minds of the world have converged upon StackOverflow.com and provided a solution: call the Win32 function CLSIDFromString.

I have taken the code and created a little helper class with one public static method called TryParse.  Its usage is just like that of any other TryParse() method in the .NET Framework today.  Here is the code:

using System;
using System.Runtime.InteropServices;


/// <summary>
/// Class that encapsulates the Win32 function CLSIDFromString.
/// </summary>
public static class GuidHelper
{
    /// <summary>
    /// Converts the string representation of a GUID to its System.Guid equivalent.  A return value
    /// indicates whether the conversion succeeded.
    /// </summary>
    /// <param name="s">A string containing the GUID to convert.</param>
    /// <param name="value">When this method returns, contains the System.Guid value equivalent to
    /// the GUID contained in s, if the conversion succeeded, or Guid.Empty if the conversion
    /// failed. The conversion fails if the s parameter is null or is not of the correct format.
    /// This parameter is passed uninitialized.</param>
    /// <returns>true if s was converted successfully; otherwise, false.</returns>
    public static bool TryParse(string s, out Guid value)
    {
        if (string.IsNullOrEmpty(s))
        {
            value = Guid.Empty;
            return false;
        }


        // CLSIDFromString requires enclosing curly braces on its GUIDs.
        if (!s.StartsWith("{"))
        {
            s = "{" + s;
        }
        if (!s.EndsWith("}"))
        {
            s += "}";
        }


        int result = CLSIDFromString(s, out value);
        if (result >= 0)
        {
            return true;
        }
        else
        {
            value = Guid.Empty;
            return false;
        }
    }


    /// <summary>
    /// This function converts a string generated by the StringFromCLSID function back into the
    /// original class identifier.
    /// </summary>
    /// <param name="sz">String that represents the class identifier</param>
    /// <param name="clsid">On return will contain the class identifier</param>
    /// <returns>
    /// Positive or zero if class identifier was obtained successfully
    /// Negative if the call failed
    /// </returns>
    [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
    private static extern int CLSIDFromString(string sz, out Guid clsid);
}

Fair warning: I verified the author’s performance numbers, but I have not yet run this through a profiler or done any checking for memory leaks. Use it at your own risk.

I suppose since the original is licensed under the cc-wiki license with attribution required, this is, too.

Anyway, enjoy!

GraffitiCMS 1.2 export utility

Update 2010-09-29: This code has been moved to BitBucket: http://bitbucket.org/jonsagara/graffititoblogml

Disclaimer: This is a little one-off utility that I modified to export to mtimport, MovableType’s import format (the original version of the utility was written in VB.NET, and exported BlogML; this function still exists, though it is not called). It is not polished, it probably has a bug or two in it, and it likely does not do everything you need it to do. Unfortunately, I don’t have the time to make it do everything perfectly; I could only put in the time to make it good enough for me. That being said, the source code is available and is being released under the MIT License, so feel free to take it and modify it as you see fit.

Credit: This is a C# port and derivative of Curt C’s Graffiti To BlogML Exporter. He did the hard work of writing the original BlogML export routine. Thanks, Curt!

Dependencies: From your Graffiti CMS installation, you will need to copy DataBuddy.dll and Graffiti.Core.dll into the Solution Items folder of the attached Visual Studio 2008 solution. These are Telligent’s DLLs, and I’m pretty sure I don’t have rights to redistribute them, so you’ll need to get them yourself.  Also, you’ll obviously need Visual Studio 2008.

Usage:

  • Copy DataBudy.dll and Graffiti.core.dll from your Graffiti installation into the Solution Items folder
  • Open GraffitiToBlogML.sln in Visual Studio 2008
  • Edit the connection string in App.config to point to your Graffiti instance
  • Click the “…” button to select an output folder
  • Click the Run button
After execution finishes, you should have a viable mtimport.txt file that you can import into MovableType.  If you need a MovableType instance to test with, you can download one for free from JumpBox.
If WordPress is your final destination, then, after you have imported your data into MovableType, you can export it again (I recommend doing this extra step so that WordPress will be importing a file exported by MovableType itself, and not my little utility).  Once you have this new export file, WordPress can then import it.
If you’re an end user, I apologize for not providing a runnable executable, but time is money.  :)
If you have questions, please post them in the comments.  I will do my best to answer them, though I can’t guarantee any level of support.

Update 2009-09-22: The MovableType-to-WordPress importer built into WordPress does not appear to import tags. I found this tool that imports your tags after you have already done the main import from MovableType: http://www.simonecarletti.com/blog/2009/02/movable-type-to-wordpress-importer-utilities/