First Post On New Blog Engine

6.23.2013

Moved servers, switching to static blog engine, Poet, written in JavaScript, served up by Node!

Old posts to be loaded soon... =^)

Simple Async HTTP Module for Appcelerator.

11.7.2011

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

10.21.2011

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 filegetcontents() 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 simplexmlloadstring() 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);

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!

Dynamic View Page, MVC without a View Model

6.23.2010

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!

Serving Images from an Image Controller

6.23.2010

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);
            }
        }
    }
}

A Rhyme for Cordialities.

2.1.2010

A rhyme for cordialities

How are things…

Things are things

People are people

I am neither

Things nor people

I am me

you are you

Next time ask

How do you do

Hope you enjoyed that brief break of levity.

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

8.26.2009

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 This is the report generated from the example specs:

Alt text

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