Musings<Biefeld>
- curiosities of development, life, the universe and everything -
November 16th, 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 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 simpleAsync = require('async');

//call the function
//handle errors and successful request
simpleAsync.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!


October 21st, 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 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);

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!

September 21st, 2011

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);
			}
		}
	}
}
September 9th, 2011

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!

February 1st, 2010

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

August 27th, 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 “JetBrains\ReSharper\v4.5\Bin” 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; “JetBrains\ReSharper\v4.5\Bin\Plugins\Machine.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:

MSpecReportExample


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


July 13th, 2009

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();
May 23rd, 2009


I am ramping up on my next personal project, No Fluff News. The site is going to be designed to sort out real news from non-news. The objective so far: Aggregate news, weed out non-news, link to true news, create an insightful, non-PC, sarcastic description and picture per item. For updates on the site follow on twitter, @nofluffnews.


May 16th, 2009


Just watched the Obama Deception, made by Alex Jones, it is very illuminating on the facade put up by international banking cartels that have been around for centuries, i.e. the Rothschild Family. It is incredible that people continue to believe politicians even though they continually lie.

Some of the best quotes from the film are of former presidents Abraham Lincoln and Thomas Jefferson:

“The money powers prey upon the nation in times of peace and conspire against it in times of adversity. It is more despotic than a monarchy, more insolent than autocracy, (and) more selfish than bureaucracy. It denounces, as public enemies, all who question its methods or throw light upon its crimes. I have two great enemies, the Southern Army in front of me and the bankers in the rear. Of the two, the one at my rear is my greatest foe…corporations have been enthroned, and an era of corruption in high places will follow, and the money power of the country will endeavor to prolong its reign by working upon the prejudices of the people until the wealth is aggregated in the hands of a few, and the Republic is destroyed.”Abraham Lincoln

“If the American people ever allow private banks to control the issue of their currency, first by inflation then by deflation, the banks and the corporations that will grow up around them, will deprive the people of all property until their children wake up homeless on the continent their fathers conquered.”Thomas Jefferson


Bush and Obama are one in the same, two figure heads of a serpent constricting the freedom and life out of our country. Our freedoms are slowly being taken from us, they are beginning to assault free people filming and taking pictures in public places, both in the U.K. and the U.S.

The Bilderberg Group is currently meeting outside of Athens, Greece. A writer for the The Guardian, Charlie Skelton has been arrested multiple times for taking pictures near where the group is meeting. Skelton is a very engaging and enlightening writer. Here are a few highlights from his posts:

“It wasn’t meant to end this way. I’d gone for a gentle sunset walk, up by the Bilderberg hotel, to relax before the big opening day of the elite globalist shindig, watch Phoebus plunge headlong into the western sea, and (yes) maybe sneak a couple of short-lens pictures of the mounting security…Over came the man with the machine gun. Over came the man with the special mirror-on-a-stick for car bombs. It was the first time in my life, and hopefully the last, that I’ve been intimidated by a mirror on a stick. They circled round me. One of them, the one in the photo with one hand up and the other on his pistol, kept prodding me in the shoulder, and shouting: ‘Give the camera! Just give the camera!’” – Charlie Skelton

“Bilderberg is all about control. It’s about “what shall we do next?” We run lots of stuff already, how about we run some more? How about we make it easier to run stuff? More efficient. Efficiency is good. It would be so much easier with a single bank, a single currency, a single market, a single government. How about a single army? That would be pretty cool. We wouldn’t have any wars then. This prawn cocktail is GOOD. How about a single way of thinking? How about a controlled internet…My confession is that being tailed today by Greek special branch, and doubling back through a cafe and catching them out, and buying them chilled water on a hot day like in Beverley Hills Cop, when Eddie Murphy has room service sent to their car – all this was pretty exciting…Bilderberg is about positions of control. I get within half a mile of it, and suddenly I’m one of the controlled. I’m followed, watched, logged, detained, detained again. I’d been put in that position by the “power” that was up the road. Likewise, the Bilderberg delegates occupy a position of power over the bobbing ignorance of the people patting beach balls in the sea, and me with my crappy little camera and my curiosity and my ill-formed sense of citizenship. I may not be very good at bearing witness here, but I’m doing my best. I haven’t shinned over the fence and shoved a camera in David Rockefeller’s face but I don’t want to be shot in the forehead.”- Charlie Skelton

“I walk into the far entrance of the cafe. I’m in an episode of The Wire. The cafe is long and thin. I double back on myself and stand, hidden, by the earlier entrance. I’m standing behind a shrub, clutching a laptop to my chest, my heart beating like a Phil Collins solo (on drums, not piano)…They’re watching me now. REALLY. They’re sitting on the wall outside the cafe Oceania or whatever this is called, watching me type this sentence. I asked them in for a coffee but they declined. They laughed sheepishly when I called them Starsky and Hutch.”- Charlie Skelton


Not only that, the youth of our country are being trained in tactical assault reminiscent of the Hitler Youth. They are gearing up to take our country hostage and handle any uprising that may occur against the self-appointed gods that these ruling elite view themselves as.

The best way to fight these narcissistic rulers is to spread information exposing who they are and what they are doing. Everyone must become a disseminator of information about secret/semi-secret organizations like the Bilderberg Group, the Council on Foreign Relations, and the Trilateral Commission. Freedom of information is the absolute enemy of the elite bankers, politicians, and corporations. Only through an information revolution exposing truth will we the people be able to usurp these fascistic, narcissistic, masochistic would-be rulers. The corruption is endemic in all levels of government and the citizen media is key to embarrassing and exposing the degradation of these so-called rulers. Resist the doublespeak and newspeak, don’t be sheeple, seek the truth and you shall be free.

The Obama Deception Film


May 12th, 2009


*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 = "phillip.fry@planetexpress.com";
	protected string _emailFrom = "hermes.conrad@planetexpress.com";
	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);
	}
}
Older Posts

Musings<Biefeld> is proudly powered by WordPress
Entries (RSS) and Comments (RSS).