Archive

Archive for the ‘C#’ Category

Useful Moq Extension Method

November 24th, 2009
Comments Off

I have been working with ASP .NET MVC and I use the Moq mocking library to help test the code I write.   Often in ASP MVC anonymous objects are passed around as function arguments.  This is especially common in calls to RouteUrl.  Since I want to be able to test this and verify that it is called correctly I wrote a handy extension method to make it easier called AsMatch.

To be able to test the UrlHelper (since it doesn't have an interface or virtual methods) I wrote a simple wrapper around it with an interface to enable testing.  Using that with this extension method makes testing route generation a breeze.

Given a call to generate a Url like this:

var url = Url.RouteUrl("Show", new { projectName="matt" });

You can write a setup on your Mock of the Url helper using a similar syntax:

UrlHelperMock
.Setup(x => x.RouteUrl("Show",new{ projectName="matt"}.AsMatch()))
.Return("someUrlToTest");

Here is the code that defines the AsMatch extension method:

    public static class ObjectMoqExtensions
    {
        public static object AsMatch(this object @object)
        {
            return Match<object>.Create(testObject => DoObjectsMatch(@object, testObject));
        }
        private static bool DoObjectsMatch(object object1, object object2)
        {
            var props1 = ToDictionary(object1);
            var props2 = ToDictionary(object2);
            var query = from prop1 in props1
                        join prop2 in props2 on prop1.Key equals prop2.Key
                        select prop1.Value.Equals(prop2.Value);
            return query.Count(x => x) == Math.Max(props1.Count(), props2.Count());
        }
        public static Dictionary<string, object> ToDictionary(object @object)
        {
            var dictionary = new Dictionary<string, object>();
            var properties = TypeDescriptor.GetProperties(@object);
            foreach (PropertyDescriptor property in properties)
                dictionary.Add(property.Name, property.GetValue(@object));
            return dictionary;
        }
    }
Author: MattManela Categories: ASP .NET MVC, C#, Moq Tags:

Converting RTF to HTML

September 28th, 2009
Comments Off

Have you ever had the desire to convert some RTF text into HTML? Probably not. But if you do, then you are in luck! I recently had the need to do this conversion and after some searching found out a way to do it by enhancing a sample distributed in the MSDN library.  The sample is called: XAML to HTML Conversion Demo

The sample has code which converts HTML to and from a XAML Flow Document.  But this doesn’t make things easier until you realize that there is a way to convert RTF to XAML easily. The key is to use System.Windows.Controls.RichTextBox which can load RTF from a stream and save it as XAML.  This conversion is shown below:

        private static string ConvertRtfToXaml(string rtfText)
        {
            var richTextBox = new RichTextBox();
            if (string.IsNullOrEmpty(rtfText)) return "";
            var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (var rtfMemoryStream = new MemoryStream())
            {
                using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream))
                {
                    rtfStreamWriter.Write(rtfText);
                    rtfStreamWriter.Flush();
                    rtfMemoryStream.Seek(0, SeekOrigin.Begin);
                    textRange.Load(rtfMemoryStream, DataFormats.Rtf);
                }
            }
            using (var rtfMemoryStream = new MemoryStream())
            {
                textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                textRange.Save(rtfMemoryStream, DataFormats.Xaml);
                rtfMemoryStream.Seek(0, SeekOrigin.Begin);
                using (var rtfStreamReader = new StreamReader(rtfMemoryStream))
                {
                    return rtfStreamReader.ReadToEnd();
                }
            }
        }

With this code we have all we need to convert RTF to HTML. I modified the sample to add this RTF To XAML conversation and then I run that XAML through HTML converter which results in the HTML text. I added an interface to these conversion utilities and converted the sample into a library so that I would be able to use it from other projects.  Here is the interface:

 public interface IMarkupConverter
    {
        string ConvertXamlToHtml(string xamlText);
        string ConvertHtmlToXaml(string htmlText);
        string ConvertRtfToHtml(string rtfText);
    }
    public class MarkupConverter : IMarkupConverter
    {
        public string ConvertXamlToHtml(string xamlText)
        {
            return HtmlFromXamlConverter.ConvertXamlToHtml(xamlText, false);
        }
        public string ConvertHtmlToXaml(string htmlText)
        {
            return HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, true);
        }
        public string ConvertRtfToHtml(string rtfText)
        {
            return RtfToHtmlConverter.ConvertRtfToHtml(rtfText);
        }
    }

With this I am now able to convert from RTF to HTML.  However, there is one catch - the conversion uses the RichTextBox WPF control which requires a single threaded apartment (STA).  Therefore in order to run your code that calls the ConvertRtfToHtml function, it must also be running in a STA.  If you can’t have your program run in a STA then you must create a new STA thread to run the conversion. Like this:

MarkupConverter markupConverter = new MarkupConverter();
private string ConvertRtfToHtml(string rtfText)
{
   var thread = new Thread(ConvertRtfInSTAThread);
   var threadData = new ConvertRtfThreadData { RtfText = rtfText };
   thread.SetApartmentState(ApartmentState.STA);
   thread.Start(threadData);
   thread.Join();
   return threadData.HtmlText;
}
private void ConvertRtfInSTAThread(object rtf)
{
   var threadData = rtf as ConvertRtfThreadData;
   threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
}
        
private class ConvertRtfThreadData
{
   public string RtfText { get; set; }
   public string HtmlText { get; set; }
}

Here is the zip contain the code for the Markup converter: MarkupConverter.zip

Author: MattManela Categories: C#, HTML, RTF, WPF, XAML Tags:

I finally got fed up with Enum.Parse

July 24th, 2009
Comments Off

I don’t know why I didn’t do this long ago, but I am done writing this:

var val = (SomeEnum)Enum.Parse(typeof(SomeEnum),”someString”);

I have typed this too many times and it annoys me. 

I wrote a small extension method on the string type to make this better:

public static class StringExtensions
{
    public static T ToEnum<T>(this string @string)
    {
        return (T)Enum.Parse(typeof (T), @string);
    }
}

With this I can now write the previous line as:

var val = "someString".ToEnum<SomeEnum>()

It is a bit shorter and I think much more readable.
Author: MattManela Categories: C#, Programming Tags:

My xUnit.net Visual Studio Code Snippets

March 2nd, 2009
Comments Off

The xUnit .Net codeplex page lists one useful Visual Studio code snippet for creating a Fact.  As you can tell I am fairly fond of code snippets so I created a few more which I use when writing xUnit.net facts. These are one line snippets that I find very convenient when writing my assertions.

Below is a table which shows the shortcut you use to access the snippet and the code the snippet generates

Shortcut Snippet
ae Assert.Equal($expected$,$actual$)
ane Assert.NotEqual($expected$,$actual$)
an Assert.Null($actual$)
ann Assert.NotNull($actual$)
at Assert.True($actual$)
af Assert.False($actual$)

I have included a zip containing these snippets.   Enjoy!

Author: MattManela Categories: C#, Snippets, Visual Studio Tags:

Inline Regular Expression Options

January 1st, 2009
Comments Off

I was using attributes from the System.ComponentModel.DataAnnotations   namespace for model validation.  This namespace includes a few very useful validation attributes such as

    1. Required Attribute – Validates the field has a value
    2. Range Attribute – Validates the field is within a given range
    3. RegularExpression Attribute – Validates the field matches a given regular expression.

 

The regular expression attribute is very useful since you can describe exactly what format you want a string property to be in.  While using this though I ran into a problem.  The attribute doesn’t let you specify RegexOptions.  This was an issue for me since I wanted to use the regex to validate that the users input was between 5 and 200 characters long , so I had attribute that property as such:

   1: [RegularExpression(@".{5,200}")]
   2: public string Text{get;set;}

 

However this doesn’t work since by default the wildcard . does not match new lines (which I am allowing in the input).  The way to fix this is to specify the RegexOptions.SingleLine option to either the Regex constructor or Match function.  The problem is I have no way of doing that here, and there is no argument on the attribute constructor to specify those options.  I was considering overriding the attribute to create one that allows specifying the attribute but then I stumbled upon this:

Regular Expression Options

You are able to specify the regex option inside of the regular expression text! (which I thought was a huge discovery until my co-worker said he knew this all along but never let me know!). 

So I just changed the expression to look like this:

   1: [RegularExpression(@"(?s).{5,200}")]
   2: public string Text{get; set;}

The (?s) is the inline regex option definition so say I want this in SingleLine mode! And now the validation works the way I wanted!

Author: MattManela Categories: C#, Regular Expression Tags: