b.logrythmik

{ independency injection }

TemplifyWith Extension Method

I created a super-simple extension-method for doing class-based token replacement on strings, using reflection. You can just pass a C# object to this function and it will replace tokens matching the object's property values in a straight-forward, easy way.

So, given this class:

class Car 
{
    public string Name { get; set; }
}
var car = new Car { Name = "Mazda" };
var message = "Hello [Name]!".TemplifyWith(car);

The resulting string (message) will be "Hello Mazda!"

Here's the code:

New Version of NLog.MongoDB Shipped

Long time, no blog.

I finally had some free time to do a little house-keeping on my NLog.MongoDB project.

Changes:

- Added the ability to use a connection string or an existing connection string name.

- Fixed the serialization issue with exceptions.

Feel free to check it out on GitHub here: https://github.com/Logrythmik/NLog.MongoDB

Also, the project is also now available on Nuget!

https://nuget.org/packages/NLog.MongoDB

NLog.MongoDB - A MongoDB Target for NLog

I've been playing with MongoDB quite a bit lately to wrap my head around it. 

We use NLog at work, and I thought MongoDB would be a great way to store NLog entries so I threw this MongoDB target to connect the two.

To install, place the binaries in your bin, and configure NLog like so: 

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<extensions>
		<add assembly="NLog.MongoDB"/>
	</extensions>

	<targets>
		<target name="Mongo" type="MongoDB" host="localhost" port="27017"/>
	</targets>
	<rules>
		<logger name="*" minLevel="Info" appendTo="Mongo"/>
	</rules>
</nlog>

Fork it on GitHub

or

Get the binaries here:

NLog.MongoDB.Binaries.zip (728.05 kb)

Zipped Source here:

NLog.MongoDB.zip (14.99 mb)

A Script-Block Templated Delegate for Inline-Scripts in Razor Partials

One of the best-practices recommendations I have struggled with is to have all your <script> tags at the bottom of the page. This is easily accomplished from a standard view; Create a section in your layout called "scripts" that renders just below where you load the libraries and use this section wherever you need scripting. No problem.

Notice I said, "standard view"? What happens if you have a partial that requires some script to run? Some would argue that the scripts should not be in the partial, but I have had a few special cases where this simply isn't possible.

I have a common "Message" partial, who's job is to render messages to the page. Most of these messages are HTML and display normally, but some messages are actually "growl" type notification messages and the partial needs to execute a function on rendering. HERE is the problem. You can't write to a section from a partial, plus partials are sometimes rendered via AJAX.

I needed a way to get the script block from my partial rendered after the scripts are loaded if part of an entire view, but I want to load the scripts inline, should I render the partial using AJAX (since the libraries will be loaded already at this point).

Sure, I could use a Head.js or some other script loading library, but some of these break the "unobtrusive" libraries that come with MVC and I didn't want to lose that functionality.

Templated Delegates to the Rescue

I created a ScriptBlock extension-method that accepts a templated delegate from anywhere in a view. The extensions method determines if the request is AJAX or not and writes the script back to the view if it is. If the partial is part of an entire view page, the script is captured in a StringBuilder, stored in HttpContext. A counterpart extension method "WriteScriptBlocks" can then be included in my layout, wherever I want the scripts to render.

Check it out.

Extention Methods:

Using the templated delegate as a parameter is great, because any model-view-binding is executed before the content is delivered to this function. Since it's a template, Intellisense and code coloring also works.  Here it is, in use:

Partial:

@model ViewMessage
 
@if (Model.Type == MessageType.Success || Model.UseNotification)
{     
    var message = Model.Message.FixForJson();
    if(Model.HasLink)
    {
        message += "<br/><a href='{0}'>{1}</a>".ToFormat(Model.LinkUrl, Model.LinkText);
    }   
    // My Script Block Extension Method, notice all the code-coloring and binding is still functional
    @this.ScriptBlock(
    @<script  type='text/javascript'>
        $(document).ready(function () {
            notify('@message''@Model.Type.ToString()''@Model.Type.ToString().ToLower()');
        });
    </script>)
 
} else {
<div class="message @Model.DisplayType clear">
 
    @if (this.Model.ShowCloseButton) { <span class="jq-close">close [x]</span>  } 
    
    <img src="/content/images/icons/@Model.Type.ToString()_Large.png" alt="@Model.Type.ToString()" />
    <h2 class="messageTitle">@Model.Message</h2>
    @if (Model.HasLink) { <p><a href="@Model.LinkUrl">@Model.LinkText</a></p> }        
    @Html.Raw(Model.ErrorList)
</div>
<div class="clear"></div>

Layout:

   ... Content

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
    <script type="text/javascript" src="//ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>
    
 
    <script type="text/javascript" src="@Links.Scripts.Site_js"></script>
 
    @RenderSection("Scripts"false)
    @this.WriteScriptBlocks()
</body>
</html>

Enjoy!

Human Friendly File-size Extension Method

I am sharing some cool extension methods I have picked up or created along the way -- here is one that comes in handy if dealing with files.

This will output the double file-size value in Bytes, KB, MB and GB.

Using Policy Injection with ASP.NET MVC and Unity

There are a million and a half articles out there about Policy Injection and the Policy Injection Blocks (from Enterprise Library). Most of them are by my new favorite blogger, David Hayden. If you aren't familiar with Unity, check out these posts first.

The articles span the life-cycle of Unity from before Policy Injection was introduced and some of the actual type names change from article to article, so it wasn't as straight forward as I am going to make it here.

First of all, I didn't want to use a config file - I wanted to configure my policies in the same place I was configuring my dependencies; in the Global.asax code-behind.

It turns out that this is super easy!

Assuming you already have a reference to the Unity library "Microsoft.Practices.Unity", all you need to add is a reference to the "Microsoft.Unity.Interception" library, found in Microsoft Enterprise Library 4.1

You probably already have a place where you are configuring your dependencies:

// Register for Dependency Injection

container.RegisterType<IDataContextProvider, DataContextProvider>();

Now all you need to do is setup the container with an extension that's called 'Interception' then configure each of the Interfaces you want to intercept with Policies. Like so:

// Register for Policy Injection

container.AddNewExtension<Interception>().Configure<Interception>()

    .SetDefaultInterceptorFor<IDataContextProvider>(new TransparentProxyInterceptor());

Now, when you use Unity to resolve your objects, it will detect if any policies are decorated on the interface or the concrete class. If there are policies, Unity creates a transparent proxy object and executes your policies like it does in the Policy Application Blocks. Check out this article to see how to create handlers.

Now you are ready to place your "Policy Attributes" on your classes. Later, I will show you some of my favorite policies I have written for MVC.

In-Class AOP | Using Action<T> Delegates to Reduce Redundant Code

I am a recent fanboy of AOP (aspect oriented) design patterns, so maybe this isn't anything new to you, but MAN it's changed my life. Staying hard-and-fast on the "DRY" principle (don't repeat yourself) is an awesome concept, but it isn't always easy. Take for instance the "Try/Catch/Finally" block. When accessing external resources, you sometimes need to wrap each call in a this block to manage the resource in the event of a failure. Something like, the following:

public void DoSomething()

{

    try

    {

        // Perform the action

        _service.Do();

    }

    catch (Exception exc)

    {

        // Log exception, etc.

        Log(exc);

        _service.Abort();

    }

    finally

    {

        // Clean up resources

        _service.Close();

    }

}

Now it isn't terribly obvious how you can get around this (at least it wasn't for me). If only we could have every call to this service wrapped in the same try/catch/finally block... Enter the Action<T> delegate. With this guy, you can create a method within this class (or a base blass) that provides this block as a wrapper for your action. For instance:

private void Invoke(Action<IService> action)

{

    try

    {

        // Perform the action

        func(_service);

    }

    catch (Exception exc)

    {

        // Log exception, etc.

        Log(exc);

    }

    finally

    {

        // Clean up resources

        _service.Close();

    }

}

Then, you could make your calls like through the "Invoke" method and everything would be wrapped in the common Try/Catch/Finally block. Check it out:

public void DoSomething()

{

    Invoke(s=>

        s.Do()

        );

}

It's that easy! Now, if you are going to be returning values, then you may want to create an overload using the Func<> delegate, like this:

private TReturnType Invoke<TReturnType>(Func<IService, TReturnType> action)

{

    try

    {

        // Perform the action

        return func(_service);

    }

    catch (Exception exc)

    {

        // Log exception, etc.

        Log(exc);

    }

    finally

    {

        // Clean up resources

        _service.Close();

    }

}

Then it could be used like so:

public string DoSomething()

{

    return Invoke(s=>

        s.Do()

        );

}

As you can see, this kind of thinking could have a major impact on your code and increase your code's reusability.

Enjoy.