8
Jul/10
0

Developing for Open Source Languages on Windows the Better Way

When working with php, rails, python, etc, windows is sufficient, but definitely leaves something to be desired. The ports of these languages are definitely second class. With Microsoft’s backing php support with IIS is improving, but it’s not the same. And usually you are going to deploy those apps on a linux/bsd web server, so it’s nice to know if there are any nuances. A lot of developers opt for a mac if they are developing in these types of languages. But macs can be pricey, and buying a new machine to work on other platforms seems overkill.

Now I do have a mac, but have a windows 7 laptop at work, and sometimes I do work in ruby on various projects. So I have worked out a way that I think is worth sharing. At it’s core, the idea is to use a vm, but there are some other tweaks that make this method even better.

Install VirtualBox. It’s from Sun Oracle and it’s freely available.

Create a virtual machine with Ubuntu. Or your favorite flavor of linux or bsd. I used the server version of ubuntu.

Setup Networking (Optional). You can use bridge mode, but for added security I used NAT for the adapter on the virtual machine. To then access the machine locally, forward your local ssh port to the virtual machine using the following instructions.

Install Putty with Tools and XMing in Windows. Available here and here, these tools will let you do ssh with X forwarding in windows.

Setup a Connection in Putty.
connection info

Enable X-Forwaring in Connection.
X-Forwarding

Setup SSH Tunnels.
ssh tunnel

Setup a Proxy connection in Firefox
proxy

Create your user and install your language platforms in the virtual machine. For example in ubuntu, you’re looking for “sudo apt-get install ruby-1.8″.

Install your preferred editor in the virtual machineEmacs, Vim, Eclipse, Netbeans, etc.

Your environment is now setup. I’ll give an example with ruby:

  • Start the virtual machine
  • Start XMing
  • Connect with Putty
  • Start your editor (for example “emacs &”)
  • Open Firefox
  • Start your app (for example “ruby script/server”)
  • Go to http://localhost:3000 in Firefox

This virtual machine does not require a lot of software installed, and a small amount of ram (like 128mb) should be sufficient. And by backing up your virtual machine (which should be pretty small), you have backed up your entire development environment without getting the documents, media, etc that you have on the windows side.

Hopefully you find this helpful if you want to develop in environments that lend themselves to this environment.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
9
Jun/10
0

Datalayer Decisions (Repository, DAO, Services) in Domain-Driven-Design Applications

I have been working several applications lately at work that use Domain-Driven Design.

I had a couple of questions about design choices I saw made in the applications I’m working with. I recently talked to an architect who uses DDD a lot (Model first), and had the chance to pick his brain. Here’s what I came up with. I’d be curious to hear other opinions via comments:

1. Why choose Repository vs DAO pattern or vice-versa? I even found some Spring posts recommending both.

Answer: Repository fits nicely on a legacy schema. If you’re domain objects do not match the database, then there this pattern works better. For green field, DAO choice means you can simplify mapping, because your schema is under your control.

One additional consideration: DAO model first means that your database may not be normalized and / or friendly for reporting tools etc. If you are in an enterprise setting, that reporting should be done off of a separate schema anyway (data warehouse). The warehouse records can be written in the service layer (see question 2) or extracted via an ETL process batch job. If this is overkill, then you may want to use Repository and map to a friendlier schema.

In the case of using both repository and DAO, this seems to be of value when you are not using an ORM. The DAO simply manages CRUD for one table, and the Repitory layer handles joining and translating entities into domain objects.

2. What is the purpose of a service layer that encapsulates a DAO or Repository?

Answer: There are various concerns that relate to the application, but not the domain model. For example, a Product model will have validation that is true in and of itself. For example, it must have a name, and that name is 50 characters or less. But in the context of an order, there may be additional validation rules that involve various domain models in the context.

So the service layer should provide a single interface for various actions related to domain that the User Interface layer should call. So for instance, a web application has an admin section where I want to delete a product. And a product can only be deleted without orders.

Top to bottom, the stack looks like the following:

  • Web application: Sends request to Product Service to delete a product
  • Product Service:
    • Calls OrderRepository to validate there are no related orders
    • Calls ProductRepository to delete Product

That is rather simple logic in the service, but why should the product repository know about the order repository? These services serve as single endpoints for user interface programmers. They can simply request a product deletion and handle appropriate validation messages / errors. They don’t care about context validation, model validation, and all the sub steps involved, that is handled for them.

And each class follows the single responsibility rule.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
9
Jun/10
0

NHibernate and Auto Properties

I’ve been working through the NHibernate with ASP.NET ProblemDesignSolution (Wrox Blox), with some small changes. I’m writing my sample in C# using the .Net framework 3.5. I prefer to use auto-properties.

It’s common that fields have private setters and only nhibernate can map using the backing field (set via reflection).

public String City { get; private set; }

The problem is telling NHibernate how to find the backing field. When you have an explicit field, you end up with something like:

<property access=”field.camelcase-underscore” name=”City” />

But with no backing field, that is a problem. I started looking around on the net and found the following:

StackOverflow discussion without much good info
and a blog post with an interesting response from Ayende Rahien.

Ayende is saying to not worry about the issue, NHibernate will still be able to set via reflection. That’s fine, but it feels a little “magical”, especially to a new developer coming along.

Why not set protected? It’s not unreasonable to expect a maintaining developer to understand that NHibernate sub-classes your class.

public String City { get; protected set; }

Now the mapping stays simple too:

<property name=”City” />

And there is no need to expect a maintaining developer to know that reflection magic is setting the property.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
26
Apr/10
2

Equals, ==, and MSTest


  public class SampleClass
    {
        public int X { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (obj.GetType() != typeof(SampleClass)) return false;
            var s = obj as SampleClass;
            return this.X == s.X;
        }
    }

Tests:
        [TestMethod()]
        public void EqualsTest()
        {
            var sc = new SampleClass { X = 1 };
            var sc_copy = sc;
            var sc2 = new SampleClass { X = 1 };

            Assert.IsFalse(sc.Equals(null));
            Assert.IsTrue(sc.Equals(sc));
            Assert.IsTrue(sc == sc_copy);
            Assert.IsFalse(sc == sc2);
            Assert.IsTrue(sc.Equals(sc2));
            Assert.IsTrue(sc2.Equals(sc));
            Assert.IsTrue(sc.Equals(sc_copy));

            Assert.AreEqual(sc, sc2);
            Assert.AreEqual(sc, sc_copy);
            Assert.AreSame(sc, sc_copy);
            Assert.AreNotSame(sc, sc2);
            Assert.AreNotSame(sc_copy, sc2);
        }
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
5
Apr/10
0

External Tools in Visual Studio

If you use subversion or git, bouncing over to source control is something you have to do a lot from Visual Studio. Here’s how to make it easier. In Visual Studio, go to Tools -> External Tools and setup Explorer if you use TortoiseSVN, or GitBash if you use that.

Explorer
GitBash

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
29
Mar/10
0

Handling Persistance in Asp.Net with Dynamic Controls

I worked on a project a couple of years ago using dynamic controls in an Asp.Net WebForms environment. Managing dynamic controls can be a real hassle.

So when I read Dave Reed’s great article about Viewstate, I wondered if I could do it better now. I worked up a simple example using no Viewstate where values persist across postbacks. Going to the page new resets everything.

The one piece I don’t like is that it uses session for a control count. But it’s a single Int32 per user that get’s stored in session, so it could be worse. Anyway, here’s the code…

Note: the aspx page has a placeholder (phOne) and two buttons (btnAdd) and (btnRemove). EnableViewstate is false on phOne.


using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web
{
    public partial class Dynamic : System.Web.UI.Page
    {
        private const string KeyNumControls = "DynamicPage_NumControls";
        private const int DefaultControlCount = 2;

        protected override void OnInit(EventArgs e)
        {
            CreateControls(NumberOfControls);
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CreateControls(DefaultControlCount);
            }
        }

        private void CreateControls(int controlCount)
        {
            NumberOfControls = controlCount;
            while(phOne.Controls.Count > NumberOfControls)
            {
                RemoveLastControl();
            }
            while(phOne.Controls.Count < NumberOfControls)
            {
                CreateControl();
            }
        }

        private void RemoveLastControl()
        {
            phOne.Controls.RemoveAt(phOne.Controls.Count - 1);
        }

        private void CreateControl()
        {
            phOne.Controls.Add(new TextBox { EnableViewState = false });
        }

        protected int NumberOfControls
        {
            get
            {
                Session[KeyNumControls] = Session[KeyNumControls] ??
                                        DefaultControlCount;
                return (int)Session[KeyNumControls];
            }
            set { Session[KeyNumControls] = value; }
        }

        protected void BtnAddClick(object sender, EventArgs e)
        {
            NumberOfControls += 1;
            CreateControl();
        }

        protected void BtnRemoveClick(object sender, EventArgs e)
        {
            NumberOfControls -= 1;
            RemoveLastControl();
        }
    }
}

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
26
Feb/10
0

Passing in “this” in StructureMap

I’ve been working with StructureMap lately, and struggled when I need to pass this in. The following code is an example of resolving that issue…

namespace StateMachine
{
  public class StateRegistry : StructureMap.Configuration.DSL.Registry
  {
    public StateRegistry ()
      {
        For<IState>.Use<StateA>.Named("FirstState");
        For<IState>.Use<StateB>.Named("SecondState");
      }
  }

  public interface IStateMachine
  {
    void ChangeState(IState state);
  }

  public interface IState
  {
    void DoWork();
  }

  public class StateA : IState
  {
    IStateMachine _machine;
    public StateA(IStateMachine machine)
      {
        _machine = machine;
      }
    public void DoWork() { // do stuff }
  }

  public class Machine : IStateMachine
  {
    public IState FirstState {get;set;}
    public IState SecondState {get;set;}
    public IState CurrentState {get; private set;}
    public Machine()
      {
        FirstState = ObjectFactory.With<IStateMachine>(this).GetInstance<IState>("FirstState");
        SecondState = ObjectFactory.With<IStateMachine>(this).GetInstance<IState>("SecondState");
        ChangeState(FirstState);
      }
    public void ChangeState(IState state) { CurrentState = state; }
  }
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
24
Feb/10
0

Namespace, Encapsulation in JavaScript

I’ve had several discussion recently some of the more advanced features of JavaScript, such as functions as return values, namespaces, encapsulation, etc. In order to demonstrate some of these things, I contrived a simple example of a dependency injection tool.

Never mind that dependency injection is not really a relevant pattern in JavaScript or other dynamic languages. It just fit all the pieces I wanted to demo. The Rhino JavaScript engine was used to run and test the example.

For more on how this stuff works, check out Douglas Crockford’s JavaScript: The Good Parts

//ObjectMap namespace
var ObjectMap = function (){
    var that = this;

    that.container = function () {
        var registry = {};
        var fact = {};

        fact.register = function (name, constructor) {
            registry[name] = constructor;
        };

        fact.getObject = function (theType) {
            return registry[theType]();
        };
        return fact;
    }();

    return that;
}();

//Dog constructor, with encapsulated private name
var Dog = function () {
    var d = {};
    var name = "spot";
    d.getName = function () {return name;};
    d.setName = function (val) {name=val; return d;};
    d.speak = function () {return d.getName() + " barks";};
    return d;
};

//register Dog with the DI tool
ObjectMap.container.register("Dog", Dog);

//get and use an object function the DI tool
var munson = ObjectMap.container.getObject("Dog");
munson.setName("Munson");
print(munson.speak());
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
8
Feb/10
1

Function Name Instead of Lambda in Linq Functions

I did not realize that functions can fill in for predicates directly without lambda notation. To illustrate, consider the following:

void Main()
{
	var words = new List<string>()
	{
		"therapists",
		"s words",
		"slang",
		"mustache",
		"sean connery"
	};

	var s_words = words.Where(w => w.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase));

	foreach(var word in s_words)
	{
		Console.WriteLine(word);
	}
}

It works, but it’s a rather long lambda, which is why I broke it out of the for loop. Let’s put that logic into a function, getting this:

void Main()
{
	var words = new List<string>()
	{
		"therapists",
		"s words",
		"slang",
		"mustache",
		"sean connery"
	};

	foreach(var word in words.Where(w => SWords(w)))
	{
		Console.WriteLine(word);
	}
}

public bool SWords(string word)
{
	return word.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase);
}

That’s better. And you might find yourself using your test in other places in the code, so it’s useful to have the function. What I found out recently, is that you can go one step further:

void Main()
{
	var words = new List<string>()
	{
		"therapists",
		"s words",
		"slang",
		"mustache",
		"sean connery"
	};

	foreach(var word in words.Where(SWords))
	{
		Console.WriteLine(word);
	}
}

public bool SWords(string word)
{
	return word.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase);
}

In this example, the savings may not look drastic. But for several chained methods you can gain a lot of brevity and clarity.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter
4
Feb/10
0

MSpec “Hello World” Sample

I’ve been working with MSpec lately. It’s a BDD framework for .Net. Here’s a hello world type example that uses Trace Writing to show a little bit about what it does.

using System;
using Machine.Specifications;
using System.Diagnostics;

namespace UnitedIndustrial.DataImportConcerns
{
    [Subject("Sample")]
    public class SampleConcerns
    {
        static string _myString;
        Establish _context = () =>
        {
            _myString = "value from context";
            LocationValueDump("context");
        };

        Because _of = () =>
         {
             _myString = "value from because";
             LocationValueDump("because");
         };

        It _shouldKnow1And1Equals2 = () =>
         {
             (1 + 1).ShouldEqual(2);
             LocationValueDump("_shouldKnow1And1Equals2");
         };

        It _shouldKnowANewStringIsNotNull = () =>
        {
            "hello".ShouldNotBeNull();
            LocationValueDump("_shouldKnowANewStringIsNotNull");
        };

        private static void LocationValueDump(string location)
        {
            Trace.WriteLine(
                String.Format("in {0} _myString is {1}",
                location, _myString));
        }
    }
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter