Archive for the ‘Programming’ Category
September 7th, 2010
I am working on a project that uses Oracle 11g, and we were standing up a db for proof of concept in one of the dev environments. I configured listener.ora to point to the instance, but still was having connection problems.
Apparently in your init file, you need the line:
local_listener='MySidName'
To make sure it keeps loading, run the following via sqlplus:
C:\> cd some_path_with_my_init_file
C:\> sqlplus /nolog
SQL> connect / as sysdba
SQL> shutdown immediate
SQL> startup pfile='myinit.ora'
SQL> create spfile from pfile
Hope this helps someone…
September 1st, 2010
I’ve seen lots of examples of rake (the ruby make replacement) being used as a build tool in non-ruby projects. Many of these are still modern platforms, like .Net. For example, StructureMap builds with rake. But I’ve found that even on older platforms, the power of having a full programming language in your build tool is useful.
Recently, I was working through examples in Thinking in C++
, and there is the need to build many small one file examples. I started writing a Makefile to simplify this, and decided to try rake instead.
The power of a programming language brings a lot to table when doing repetitive tasks. Check out the following Rakefile which generates a build, run, and clean method for each file listed in an array. And there are aggregate methods which will run or clean all.
exe_name = ["hello","c_in_cpp","file","vector"]
exe_name.each do |f|
desc "clean #{f}"
task "clean_#{f}".to_sym do
sh "rm -rf #{f} #{f}.o"
end
desc "build #{f}"
task "build_#{f}".to_sym => "clean_#{f}" do
sh "g++ #{f}.cpp -o #{f}"
end
desc "run #{f}"
task "run_#{f}".to_sym => "build_#{f}" do
sh "./#{f} 2> error.log"
end
end
desc "run all"
task :default => exe_name.collect{|f| "run_#{f}"}
desc "clean all"
task :clean => exe_name.collect{|f| "clean_#{f}"}
If any of the above is unclear, and you want to see the output, do the following: copy and paste that code into a file named “Rakefile”. Run “rake -T” to lists all available tasks. You won’t be able to actually run the tasks, unless you have the appropriate cpp files in the directory (ie “rake run_hello” requires hello.cpp).
If you want to learn a build tool, and know ruby, or want to learn ruby rather than some specialized build language with no other uses, give rake a shot.
July 8th, 2010
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.

Enable X-Forwaring in Connection.

Setup SSH Tunnels.

Setup a Proxy connection in Firefox

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.
June 9th, 2010
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.
June 9th, 2010
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.
April 26th, 2010
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);
}
April 5th, 2010
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.


March 29th, 2010
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();
}
}
}
February 26th, 2010
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; }
}
}
February 24th, 2010
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());