Using the Strategy Pattern to Reduce Complexity in Your JavaScript


    Problem:

    Do you ever find yourself writing a lengthy switch statements or if statements structured like a switch. Luckily there is the Strategy Pattern to help alleviate this complex, sometimes unintelligible code. You may have also noticed that this code can have quite a high Cyclomatic Complexity.

    Let’s take a look at an example of a lengthy switch statement. The code below is checking a user’s role and if they have read or write permissions. Now this is a contrived example but the pattern still applies.

    JS Bin

    Here we can see the complexity is becoming unweildy, sure there are ways to clean this code up more with string manipulation of the urls and roles/permissions. The permissions check should be a single function call as well. Humor me and let’s pursue the Strategy Pattern for now and we’ll clean up the permissions check along the way.

    Solution:

    The Strategy Pattern will be our weapon of choice for tackling the problem above. So what is the Strategy Pattern, you may ask? Essentially it is a way to evaluate an input at runtime and execute predefined code based off of that input. This is JavaScript, a dynamic language so we won’t have to go the full polymorphic, implenting interfaces like in C# to use this pattern. As an aside, you could actually do it that way in JavaScript if you’d like. Check out this implentation to see how to do it that way.

    For our solution we are going to utilize the fact that the JavaScript Object is essentially a dictionary, note the bracket notation to get object properties by a string. We are not handling super complex logic so a dictionary will suffice as our strategy implementation.

    Implementation

    First we will start off laying out the basic structure for our strategy. We will define a UserRoleStrategy class with functions for each role and a default handler.

    We are creating a function to handle each user role, similar to our switch statement. Now let’s go ahead and add the logic for each user role. We will pull the logic out of our switch and place it in the appropriate user role function.

    That’s still pretty messy, so let’s refactor the permissions logic. This step is not strategy pattern related but will make the code more readable. Our strategy object allows us to refactor easily and contain the logic within it.

    JS Bin

    Refactor complete, now we have a strategy object with two private functions to handle our permission/url logic and our logging. We no longer rely on a switch statement to handle our user role logic but a full blown object that can be extended as needed. Note on line 53 we are instantiating our strategy object, currentRoleHandler, and passing in the user. We then use the square brackets to pass in our user role on line 57, currentRoleHandler[user.role](). Resulting in a call to the correct function on our strategy object.

    That’s it, thanks for reading!

    tl;dr

    Reduce cyclomatic complexity in your JavaScript with the Strategy Pattern and utilize the fact that JavaScript objects can be used as a dictionaries.

    Simple Async HTTP Module for Appcelerator


    Hello techies,

    I have been using Appcelerator recently. It is a pretty cool tool, it allows you to create cross platform mobile applications for iOS and Android, writing JavaScript.

    Appcelerator’s Titanium Framework uses the CommonJS API so you can reference javascript files as “modules”, it is very reminiscent of node.js which also implements CommonJS.

    Below is a simple async module I wrote, inspired by codeboxed’s gist, to make requests to a web server. Stick it in a file named SimpleHttpAsync.js

      //////////////////////////////////////////////
     //                Simple Http Async         //
    //////////////////////////////////////////////
    
    exports.call = function (options) {
        //create the titanium HTTPClient
        var httpClient = Titanium.Network.createHTTPClient();
    
        //set the httpclient's properties with the provided options
        httpClient.setTimeout(options.timeout);
        httpClient.onerror = options.error;
           
        //if and when response comes back
        //the success function is called
        httpClient.onload = function(){
            options.success({
                data: httpClient.responseData, 
                text: httpClient.responseText
            });
        };
            
        //open the connection
        httpClient.open(options.type, options.url, true);
    
        //send the request
        httpClient.send();
    };

    The following is example code of importing and using the module

    //import the module
    var simpleHttpAsync = require('simpleHttpAsync');
    
    //call the function
    //handle errors and successful request
    simpleHttpAsync.call({
        type : "POST",
        url : "http://www.someurl.com?somekey=somevalue",
        error : function (error) {
            //do something to handle error
        },
        success : function (response) {
            //do something with the response data from the server
        },
        timeout : 10000
    });
    

    It’s nothing special, but the documentation for Appcelerator is pretty sparse and I thought it might be useful for those new to the Appcelerator Titanium Framework.

    As always enjoy and let me know if you have any comments/suggestions/questions. Thanks!

    Simple XML to JSON with PHP


    Hello all, it’s been a while since I have blogged anything, been extremely busy with personal events in my life. So to get back into the swing of things I am going to KISS this post. I recently needed to convert XML to JSON in PHP. Thankfully, PHP has built in functionality to handle precisely this task. First we need to get contents of the XML file, we need to use _file\_get\_contents()_ and pass it the URL to the XML file. We remove the newlines, returns and tabs.
    $fileContents = file_get_contents($url);
    
    $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
    Next I replace double quotes with single quotes and trim leadign and trailing spaces, this helps to ensure the simple XML function can parse the XML appropriately. Then we call the _simplexml\_load\_string()_ function.
    $fileContents = trim(str_replace('"', "'", $fileContents));
    
    $simpleXml = simplexml_load_string($fileContents);
    The final step we need is to convert the XML to JSON, for that we will use the _json_encode()_ function.
    $json = json_encode($simpleXml);</pre>
    
    
    

    That’s it! All together now:

    <?php
    
    class XmlToJson {
    
    	public function Parse ($url) {
    
    		$fileContents= file_get_contents($url);
    
    		$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
    
    		$fileContents = trim(str_replace('"', "'", $fileContents));
    
    		$simpleXml = simplexml_load_string($fileContents);
    
    		$json = json_encode($simpleXml);
    
    		return $json;
    
    	}
    
    }
    
    ?>
    

    Now if we want to utilize our creation we can create a file which uses the class we created above, assuming we store the XmlToJson class in a file named XmlToJson.php. We can create a file for a specific XML web service, include our class and call it XmlToJson::Parse($url). Just for fun we’ll point to the XML for the NFL scorestrip.

    <?php
    
    include 'XmlToJson.php';
    
    print XmlToJson::Parse("http://www.nfl.com/liveupdate/scorestrip/ss.xml");
    
    ?>

    Now we can call our new file, say we name it getNflDataAsJson.php, it will return the converted JSON. Calling it from jQuery below:

    $.getJSON('getNflDataAsJson.php', function(data) { 
    	//do something
    });

    Thats all I’ve got, let me know if you have any questions, things you would do differently or general comments.

    Thanks much!

    </article>

    Serving Images from an Image Controller


    Found this solution rather simple when you want to serve images from your database.

    public class ImageController
    {
    	readonly IImageQueries Queries;
    
    	public ImageController(IImageQueries queries)
    	{
    		Queries = queries;
    	}
    
    	public FileResult Show(int id)
    	{
    		DateTime? dateCreated = Queries.GetDateCreatedById(id);
    
    		//invalid image, return 404
    		if (dateCreated == null)
    		{
    			HttpContext.Response.StatusCode = 404;
    
    			return null;
    		}
    		else
    		{
    			string ifModifiedSince = HttpContext.Request.Headers["If-Modified-Since"];
    
    			//check if image has been modified
    			if (ifModifiedSince != null && dateCreated.Value <= DateTime.Parse(ifModifiedSince))
    			{
    				HttpContext.Response.StatusCode = 304;
    				return null;
    			}
    			else
    			{
    				HttpContext.Response.Cache.SetLastModified(dateCreated.Value);
    
    				dynamic image = Queries.GetById(id);
    
    				return new FileContentResult(image.Bytes, image.MimeType);
    			}
    		}
    	}
    }
    

    Dynamic View Page, MVC without a View Model


    Hello fellow techies on this roller coaster called life. It has been a while since my last post, I have been focusing on some other more important aspects of my life.

    What I want to talk about in this post is the idea of a dynamic view page which removes the need for a View Model data transfer object. I have started to try this out on project that I am working on, for views that are essentially read only. All these views are concerned about is displaying data/information.  I do not yet know how useful this is but I thought it was novel and will be exploring it’s usefulness. Plus, the lazy side of me likes the idea of not creating data transfer objects if possible.

    Two side effects of this approach are the loss of the strongly typed Model on your view, which is a non-issue for a page without inputs.  The second is the loss of intellisense (the very first time a member is used on a dynamic) when working with the Model in the view, which could be a minor loss in that you wont know something is wrong until you run it, but thats the way it goes.

    To accomplish this you start off by creating a DynamicViewPage that inherits ViewPage.  Have some overrides and new up some properties and you should be set.

    public class DynamicViewPage : ViewPage
    {
    	private ViewDataDictionary<dynamic> _viewData;
    
    	public override void InitHelpers()
    	{
    		base.InitHelpers();
    		Ajax = new AjaxHelper<dynamic>(ViewContext, this);
    		Html = new HtmlHelper<dynamic>(ViewContext, this);
    	}
    
    	protected override void SetViewData(ViewDataDictionary viewData)
    	{
    		_viewData = new ViewDataDictionary<dynamic>(viewData);
    		base.SetViewData(_viewData);
    	}
    
    	public new AjaxHelper<dynamic> Ajax { get; set; }
    
    	public new HtmlHelper<dynamic> Html { get; set; }
    
    	public new dynamic Model
    	{
    		get
    		{
    			return ViewData.Model;
    		}
    	}
    
    	public new ViewDataDictionary<dynamic> ViewData
    	{
    		get
    		{
    			if (_viewData == null)
    			{
    				SetViewData(new ViewDataDictionary<dynamic>());
    			}
    			return _viewData;
    		}
    		set
    		{
    			SetViewData(value);
    		}
    	}
    }

    Now your view needs to inherit from DynamicViewPage.

    Inherits="Web.Views.DynamicViewPage"

    In your controller you can ask your persistence abstraction of choice for some data and return it to the view.

    public ActionResult Index()
    {
    	IEnumerable<dynamic> foos = FooQueries.GetAll();
    	return View(foos);
    }

    Where this can get interesting is when you have a linq provider that returns dynamic objects. Then essentially your domain model is king and you eliminate a lot of DTOs. That’s all I’ve got for now. I attached a sample application that demonstrates the dynamic view, enjoy!

    Step by Step to Using MSpec (Machine.Specifications) with ReSharper


    Whilst researching using MSpec with ReSharper I found it difficult to find all the resources I needed in one place. This is an attempt to condense everything into that one place and facilitate those seeking to accomplish the same task.

    Step 1 – Git It:

    First thing’s first, grab the latest Machine Spec source from github.

    $ git clone git://github.com/machine/machine.specifications.git mspec

    Step 2 – Build It:

    Next, open it up in Visual Studio, set it to build in release mode and build it. Now the binaries will be ready for you.

    Step 3 – Setup ReSharper:

    Now we need to setup ReSharper to be able to utilize the MSpec framework and run the tests in ReSharper’s test runner. To do this we need to add a plugins directory to the “JetBrainsReSharperv4.5Bin” directory or the where ever the bin directory for your ReSharper is located. In the Plugins create a Machine.Specifications directory, so you should now have a path similar to; “JetBrainsReSharperv4.5BinPluginsMachine.Specifications”. Place the following dlls in the newly created folder: Machine.Specifications.ReSharperRunner.4.5.dll and Machine.Specifications.dll.

    Step 4 – Write some Specifications:

    Coolio, now to test some behaviors, the dlls needed in our test project; Machine.Specifications.dll, Machine.Specifications.NUnit.dll or Machine.Specifications.XUnit.dll, and the appropriate test framework dll.

    Let’s take a look at a couple of examples to get used to the syntax. The most common keywords you want to pay attention to are Subject, Establish, Because and It. Declare the Subject of your Spec, Establish a context of the spec, Because x occurs, It should do something. For more complex scenarios you can use the keyword, Behaves_like and the Behaviors attribute which allows you to define complex behaviors. If you need to perform some cleanup use the Cleanup keyword.

    Now for a couple of simple contrived examples…

    This first specification looks at adding two numbers:

    [Subject("adding two operands")]
    public class when_adding_two_operands
    {
    	static decimal value;
    
    	Establish context = () =>
    		value = 0m;
    
    	Because of = () =>
    		value = new Operator().Add(42.0m, 42.0m);
    
    	It should_add_both_operands = () =>
    		value.ShouldEqual(84.0m);
    }

    The second specification looks at adding multiple numbers:

    [Subject("adding multiple operands")]
    public class when_adding_multiple_operands
    {
    	static decimal value;
    
    	Establish context = () =>
    		value = 0m;
    
    	Because of = () =>
    		value = new Operator().Add(42m, 42m, 42m);
    
    	It should_add_all_operands = () =>
    		value.ShouldEqual(126m);
    }

    The code being tested:

    public class Operator
    {
    	public decimal Add(decimal firstOperand, decimal secondOperand)
    	{
    		return firstOperand + secondOperand;
    	}
    
    	public decimal Add(params decimal[] operands)
    	{
    		decimal value = 0m;
    
    		foreach (var operand in operands)
    		{
    			value += operand;
    		}
    
    		return value;
    	}
    }

    Step 5 – Create Templates to Improve Your Efficiency:

    Using ReSharper templates is a good way to improve your spec writing efficiency, the following are templates I have been using.

    This first one is for your normal behaviors:

    [Subject("$subject$")]
    public class when_$when$
    {
    	Establish context =()=>	{};
    
    	Because of =()=> {};		
    	
    	It should_$should$ =()=> $END$;
    }

    This one’s for assertions by themselves:

    It should_$should$ =()=> $END$;

    Step 6 – Run the Report

    The report generated is pretty much the exact same as the SpecUnit report. The easiest thing to do is place the following MSpec binaries and file in the directory where your test binaries are placed; CommandLine.dll, Machine.Specifications.ConsoleRunner.exe, Machine.Specifications.dll and CommandLine.xml. The command to run the report goes a little something like:

    machine.specifications.consolerunner --html <the location you want the html report stored> <your test dll name>

    This is the report generated from the example specs:

    Well, that’s about all for now, let me know if you have any questions.

    Configuring Fluent NHibernate with an External NHibernate Config File


    A while ago I was having issues using configuring fluent NHibernate with an external configuration file. I kept running into the issue of mappings not being registered. I was finally able to get it working appropriately and thought I would share my solution. The key is to configure the normal mappings first and then pass that configuration in when configuring fluent NHibernate.

    string configFile = "hibernate.cfg.xml";

    //setup the normal map configuration
    Configuration normalConfig = new Configuration().Configure(configFile);

    //setup the fluent map configuration
    Fluently.Configure(normalConfig)
    .Mappings(
    m => m.FluentMappings
    .ConventionDiscovery.Add(DefaultLazy.AlwaysFalse())
    .AddFromAssemblyOf<UserMap>())
    .BuildConfiguration();

    Testing with a Compiled Class that Doesn’t Implement an Interface – Adapter Pattern


    *UPDATE: Per sean chambers, this is an example of the adapter pattern

    I recently ran into an issue where I needed to implement a simple email service to send users a randomly generated PIN when they are first entered into the system. To accomplish this I decided to just use the System.Net.Mail implementation.  To create and send an email you have to use the SmtpClient class which does not implement an interface. All I really wanted to test was that the Send() method was called, I did not want to write an integration test that actually sends an email.

    One way to work around this problem is to create an interface containing the elements you need to mock from the compiled class.  After this, create your own class that inherits the compiled class and implements your interface. Now when testing, you can seemingly mock up the non-interfaced compiled class, which is exactly what I wanted to achieve. I am not sure whether this is the appropriate way to handle the issue, if anyone has any thoughts on a better way to do this, I would be grateful for the advice.

    My specification ended up looking like this:

    public class EmailServiceSpecs : ContextSpecification
    {
    	protected IEmailService _emailService;
    	protected ISmtpClient _smtpClient;
    	protected string _emailTo = "[email protected]";
    	protected string _emailFrom = "[email protected]";
    	protected string _emailSubject = "New Process to Improve Morale";
    	protected string _emailBody = "From now on all employees will be required to have Brain slugs, remember, a mindless worker is a happy worker.";
    
    	protected override void SharedContext()
    	{
    		DependencyInjection.RegisterType<IEmailService, EmailService>();
    
    		_emailService = DependencyInjection
    			.GetDependency<IEmailService>(_emailTo, _emailFrom, _emailSubject, _emailBody);
    
    		_smtpClient = MockRepository.GenerateMock<ISmtpClient>();
    
    		DependencyInjection.RegisterInstance(_smtpClient);
    	}
    }
    
    [TestFixture]
    [Concern("Email Service")]
    public class when_sending_an_email : EmailServiceSpecs
    {
    	protected override void Context()
    	{
    		_smtpClient.Stub(smptClient => smptClient.Send(new MailMessage()))
    			.IgnoreArguments()
    			.Repeat.Any();
    
    		_emailService.Send();
    	}
    
    	[Test]
    	[Observation]
    	public void should_send_email()
    	{
    		_smtpClient.AssertWasCalled
    			(smtpClient => smtpClient.Send(new MailMessage()),
    			assertionOptions => assertionOptions.IgnoreArguments());
    	}
    }
    

    Below are my email classes:

    public interface ISmtpClient
    {
    	void Send(MailMessage message);
    }
    
    [MapDependency(typeof(ISmtpClient))]
    public class SubsideSmtpClient : SmtpClient, ISmtpClient { }
    
    public interface IEmailService
    {
    	void Send();
    }
    
    [MapDependency(typeof(IEmailService))]
    public class EmailService : IEmailService
    {
    	public EmailService(string to, string from, string subject, string body)
    	{
    		Email = new MailMessage(from, to, subject, body);
    	}
    
    	protected MailMessage Email
    	{
    		get; set;
    	}
    
    	private ISmtpClient _smptClient;
    
    	protected ISmtpClient Smtp
    	{
    		get
    		{
    			_smptClient = DependencyUtilities
    				.RetrieveDependency(_smptClient);
    			return _smptClient;
    		}
    	}
    
    	public void Send()
    	{
    		Smtp.Send(Email);
    	}
    }
    

    Updated MonoChrome Firefox theme


    Hey just wanted to let everyone know that I updated my Firefox theme, MonoChrome, for version 3.5b4pre.
    You can grab it from the link below:

    https://addons.mozilla.org/en-US/firefox/addon/8791

    Screen shot:

    If you would like to contribute or grab the source, it is hosted on google code:

    http://code.google.com/p/monochrometheme

    My Visual Studio Twilight theme


    I just finalized my text color theme for visual studio. Just thought I would share it with everyone. It is geared towards those of you who have resharper installed, but it should still work fine without it.

    The theme is based off of the textmate twilight theme. I was going for a low contrast theme that is easy on the eyes.  I have tried the Vibrant Ink theme and it is too abrasive for me. My goal was to make warnings and errors blatantly obvious and distinguish classes from interfaces. I also love how the comments are dark and do not draw attention, I am not a big fan of comments.  I think the code along with BDD tests should be self-explanatory of what is going on.

    All resharper warnings show up as red text. Build errors have red squiggly lines under them.  Breakpoints have red background.

    Here is a c# example:

    Here is an example of an aspx page:

    Style sheet example:

    JavaScript example:

    Let me know if you have any suggestions.

    Grab the Visual Studio settings file here!

subscribe via RSS