Posts Tagged ‘linkedin’

Listener in Oracle 11g

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…

Rake Breathing New Life to Building Old Projects

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.

NHibernate and Auto Properties

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.

Equals, ==, and MSTest

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

External Tools in Visual Studio

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.

Explorer
GitBash

Handling Persistance in Asp.Net with Dynamic Controls

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

Passing in “this” in StructureMap

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

Namespace, Encapsulation in JavaScript

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

Function Name Instead of Lambda in Linq Functions

February 8th, 2010

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.

MSpec “Hello World” Sample

February 4th, 2010

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