Social Media Html Helpers

I'm currently in the process of writing the next to tutorials in my Windows Phone 7 tutorial series and thought I'd share these snippets of code.

public static class SocialMediaExtensions

{

    public static HtmlString DotNetShoutOut(this HtmlHelper htmlHelper, string url)

    {

        url = HttpUtility.UrlEncode(ToAbsolute(htmlHelper.ViewContext.HttpContext.Request, url));

 

        var img = new TagBuilder("img");

 

        img.Attributes["src"] = "http://dotnetshoutout.com/image.axd?url=" + url;

        img.Attributes["alt"] = "Shout It";

        img.Attributes["style"] = "border: 0px;";

        img.Attributes["width"] = "82";

        img.Attributes["height"] = "18";

 

        var a = new TagBuilder("a");

 

        a.Attributes["rev"] = "vote-for";

        a.Attributes["href"] = "http://dotnetshoutout.com/submit?url=" + url;

 

        a.InnerHtml = img.ToString(TagRenderMode.SelfClosing);

 

        return new HtmlString(a.ToString(TagRenderMode.Normal));

    }

 

    public static HtmlString DotNetKicks(this HtmlHelper htmlHelper, string url)

    {

        url = HttpUtility.UrlEncode(ToAbsolute(htmlHelper.ViewContext.HttpContext.Request, url));

 

        var img = new TagBuilder("img");

 

        img.Attributes["src"] = "http://dotnetkicks.com/services/images/kickitimagegenerator.ashx?url=" + url;

        img.Attributes["alt"] = "Kick It";

        img.Attributes["style"] = "border: 0px;";

        img.Attributes["width"] = "82";

        img.Attributes["height"] = "18";

 

        var a = new TagBuilder("a");

 

        a.Attributes["rev"] = "vote-for";

        a.Attributes["href"] = "http://dotnetkicks.com/kick/?url=" + url;

 

        a.InnerHtml = img.ToString(TagRenderMode.SelfClosing);

 

        return new HtmlString(a.ToString(TagRenderMode.Normal));

    }

 

    public static HtmlString Reddit(this HtmlHelper htmlHelper, string url)

    {

        url = HttpUtility.UrlEncode(ToAbsolute(htmlHelper.ViewContext.HttpContext.Request, url));

 

        var img = new TagBuilder("img");

 

        img.Attributes["src"] = "http://reddit.com/static/spreddit7.gif";

        img.Attributes["alt"] = "submit to reddit";

        img.Attributes["style"] = "border: 0px;";

 

        var a = new TagBuilder("a");

 

        a.Attributes["rev"] = "vote-for";

        a.Attributes["href"] = "http://reddit.com/r/programming/submit?url=" + url;

 

        a.InnerHtml = img.ToString(TagRenderMode.SelfClosing);

 

        return new HtmlString(a.ToString(TagRenderMode.Normal));

    }

 

    private static string ToAbsolute(HttpRequestBase request, string url)

    {

        if(request == null)

            throw new ArgumentNullException("request");

 

        if(url == null)

            throw new ArgumentNullException("url");

 

        var format = request.IsSecureConnection ? "https://{0}{1}" : "http://{0}{1}";

 

        return String.Format(format, request.Url.Host, url);

    }

They're pretty simple little helpers and can be used for any urls. The only thing that may need to change is the ToAbsolute method which is only for the root application. To the use the helpers in my blog I have the following.

<p>

    <%: Html.DotNetShoutOut(Url.Action("Posts", new { slug = Model.Slug.ToLower() })) %>

    <%: Html.DotNetKicks(Url.Action("Posts", new { slug = Model.Slug.ToLower() })) %>

    <%: Html.Reddit(Url.Action("Posts", new { slug = Model.Slug.ToLower() })) %>

</p>

Shout It Kick It submit to reddit

Using JQuery to embed Silverlight

Embeding Silverlight xaps in a page can be a pain in the ass, it's very verbose if you try and do it manually. I'm already using JQuery on the Compiled Experience Website so anything where I can use JQuery to simply this would be great.

The best example I've found of doing this is on the Silverlight Forums and is a great simple little plugin that lets you embed Silverlight xaps. I've modifed the example one slightly (mostly method names). Once you've included both JQuery and the plugin js file it's as simple as this to embed your Silverlight.

<script type="text/javascript">

    $(function () {

 

        $("#focus-panel").silverlight("../../clientbin/controls.focuspanel.xap", {

            width: 560,

            height: 300

        });

    });

</script>

Shout It Kick It submit to reddit

Unit of Work per Action

Most of the time I do any database interaction I follow a "Unit of Work" pattern. This allows good control over when work is submitted to the database, in terms of the Entity Framework, the Unit of Work controls the lifetime of the ObjectContext.

The implementation is pretty simple, we have a UnitOfWork static class that provides easy access to the current UOW as well as starting and disposing. We then have our IUnitOfWork which is where the work of accessing repositories and submitting changes to the database will be done. We then implement that with EntityUnitOfWork.

I like to follow the approach of "Unit of Work per Request" for web applications and usually handle this with an IHttpModule that manages it for me. However for MVC I wanted to try something different. One of the reasons I didn't like Module approach for MVC was that the UnitOfWork was still active during the rendering of the View. This meant that any complex lazy loaded queries could still be evaluated which could leave me vulnerable to N+1 problems.

public class UnitOfWorkAttribute : ActionFilterAttribute

{

    public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

        UnitOfWork.Start();

    }

 

    public override void OnActionExecuted(ActionExecutedContext filterContext)

    {

        if(UnitOfWork.IsStarted)

            UnitOfWork.Dispose();

    }

}

In the end I created a UnitOfWorkAttribute which inherits from ActionFilterAttribute, this enables me to dispose of the current unit of work after the action is completed but before the view is processed. It means that if the view triggers anything that causes database access it throws an error. I can now enforce the convention that all data must be loaded by the action.

[HttpPost, UnitOfWork, ActionName("sign-in")]

public ActionResult SignIn(SignInViewModel details, string returnUrl)

Shout It Kick It submit to reddit

Gothcha when creating your own Client Side Data Annotation Validators

For the new version of the website I'm using the Data Annotations validators for validating view models posted to the controllers. As I'm sure everyone who starts down this road does one of the first things I wanted to create was an EmailAttribute by extending RegularExpressionAttribute. The mighty Scott Gu goes through this process in his blog post on Model Validation. Unfortunately his solution stops just short of everything that's required.

public class EmailAttribute : RegularExpressionAttribute

{

    public EmailAttribute()

        : base(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")

    {

 

    }

 

    public override string FormatErrorMessage(string name)

    {

        return String.Format("{0} is an invalid email address", name);

    }

}

 

The EmailAttribute works correctly on the server but doesn't trigger any validation on the client side. What you need to do is inform the DataAnnotationsModelValidatorProvider (phew) that the EmailAttribute acts in exactly the same way as the RegularExpressionAttribute. This can be achieved with this simple bit of code in Application_Start.

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));

 

Shout It Kick It submit to reddit

Don't return Action Result (if you can help it)

A while ago I was looking into dynamic languages (in particular Iron Python) and an idea presented in a talk stuck with me. I wish I could remember who it was to credit them. In essence it was that in dynamic languages unit tests verify what the compiler can't enforce and that we can think of the compiler as simply another unit test in the system. This was obviously framed in a way that meant that the type safety wasn't necessary but lets approach it from a different direction.

Don't unit test what you can use the compiler to enforce.

A common thing I see in MVC examples is a unit testing verifying that some controller action returned the correct type of ActionResult e.g IndexReturnsViewResult. While this test is useful, we can remove it by changing the return type of Index to ViewResult, now the compiler enforces our test for us! This clearly won't work for actions that return different types of result depending on context (this is where unit testing should be testing). But if we can have our compiler enforce some of our specification then I think we should.

Shout It Kick It submit to reddit