Posts Tagged “c#”

My experience is that Spring.NET configuration files tend to grow very large. As far as I can figure, there are two principal problems that arise from this:

  1. The configuration files get difficult to read and maintain
  2. It gets easier to introduce errors in the configuration because of its size

In general, I am in favour of keeping configuration files as small as possible. I often work with web applications that can (quite) easily be redeployed to the production environment, hence I always ask the question “will this value ever change between environments or deployments” when considering introducing a new configuration part.

Now, the Spring XML configuration usually serves two main purposes; to wire together the application, and to provide values that should be possible to change between deployments of the application or for different environments. The first purpose, I would argue does not necessarily need to be in the XML configuration. Rather, if this is done in code, we get the benefit that the compiler will tell us right away if there are typos or missing references. If this wiring is in the XML configuration file, such errors will not surface until the application starts.

So, the question that I had, was how Spring context wiring could be combined in code and in XML. I found one way of doing it, but it is only applicable to singleton objects.

Say, for instance that we have an object “something” that we wish to have configured in XML:

  <object id="something" type="SpringTest.Something, SpringTest" singleton="false"/>

Then, we have a class that we want to initialize in code:

class Foo
{
    public Foo() { }
    private Something _s;
    Something S
    {
        set { _s = value; }
        get { return _s; }
    }
}

Now, we see that Foo has a dependency on Something; it needs an instance of Something to be injected. We can use the Spring context to do this after we have created the instance of Foo:

IApplicationContext context = ContextRegistry.GetContext();
Foo f = new Foo();
context.ConfigureObject(f, "fooPrototype");

But Spring does not yet know that the Foo instance needs to be injected Something. Hence, we need to tell Spring that by creating what I would call a “prototype” or “template” object configuration:

<object id="fooPrototype" type="ContextTestProject.Foo, ContextTestProject">
   <property name="S" ref="something"></property>
</object>

The final step is then to register our newly created object in the Spring context:

XmlApplicationContext xmlContext = context as XmlApplicationContext;
xmlContext.ObjectFactory.RegisterSingleton("foo", f);

After this, the Foo instance is available for the application in the Spring context.

Comments No Comments »

One question have troubled me for some time when automating Internet Explorer (actually, I am doing web testing with Watin): how to test for HTTP status codes. Finally, I figured out how to do this. The lies in an event that the InternetExplorer object raises when navigation is unsuccessful.

I ended up with writing a C# helper class:

using System.Net;
using WatiN.Core;
using SHDocVw;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Globalization;
namespace Test
{
    public class NavigationObserver
    {
        private HttpStatusCode _statusCode;
        public NavigationObserver(IE ie)
        {
            InternetExplorer internetExplorer = (InternetExplorer)ie.InternetExplorer;
            internetExplorer.NavigateError += new DWebBrowserEvents2_NavigateErrorEventHandler(IeNavigateError);
        }
        public void ShouldHave(HttpStatusCode expectedStatusCode)
        {
            if (!_statusCode.Equals(expectedStatusCode))
            {
                Assert.Fail(string.Format(CultureInfo.InvariantCulture, "Wrong status code. Expected {0}, but was {1}",
                    expectedStatusCode, _statusCode));
            }
        }
        private void IeNavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
        {
            _statusCode = (HttpStatusCode)StatusCode;
        }
    }
}

Note that I use Visual Studio test runner to run my web tests. Then, I can use this in my test:

using (IE ie = new IE())
{
    NavigationObserver observer = new NavigationObserver(ie);
    ie.GoTo("http://some.where.com");
    observer.ShouldHave(HttpStatusCode.NotFound);
}

Comments 1 Comment »

Encapsulation is one of the most important features of object orientation, but often easy to break in practice. One common mistake to make in this respect happens when creating a class that holds some sort of collection or array.

For example, let’s assume that we want to make an immutable object (meaning that its state should never change troughout its lifecycle):


public class Request
{
    private readonly string[] _acceptedTypes;
    public Request(params string [] acceptedTypes) {…}
    public string[] AcceptedTypes { get {…} }
    public bool Accepts(string type) {…}
}

We have a class that take a list of strings as parameter to the constructor. The intent is that the list of strings should never change. Typical use of the class would be something like this:


Request request = new Request("application/json", "application/x-json");
if (request.Accepts(somestring))
{
     ...
}

Here’s a naîve implementation of the class:


public class Request
{
    private readonly string[] _acceptedTypes;

    public Request(params string[] acceptedTypes)
    {
        _acceptedTypes = acceptedTypes;
    }

    public string[] AcceptedTypes { get { return _acceptedTypes; } }

    public bool Accepts(string type)
    {
        foreach (string acceptableType in _acceptedTypes)
        {
            if (acceptableType.Equals(type))
            {
                return true;
            }
        }
        return false;
    }
}

Our intent of creating an immutable object is here manifested in the ‘readonly’ keyword used when defining the member variable _acceptedTypes, and the fact that there is only a set accessor for the AcceptedTypes property. But alas, there are several issues that break our intent.

First, let’s have a look at the AcceptedTypes accessor. It allows us to write code such as this:


request = new Request("application/json", "application/x-json" );

bool accepts1 = request2.Accepts("application/javascript");
request.AcceptedTypes[1] = “application/javascript”;
bool accepts2 = request.Accepts(”application/javascript”);

After running this code, we find that accepts1 != accepts2. We have been able to manipulate the state of the object (in other words, it is mutable). The problem is that the AcceptedTypes exposes a reference to the array of types. Alternatively, it could only expose an IEnumerable that can be used to iterate over the types:


public IEnumerable AcceptedTypes
{
get
{
    foreach (string acceptableType in _acceptedTypes)
{
yield return acceptableType;
}
    }
}

Then, it will not be possible to manipulate the state of the object by calling request.AcceptedTypes[i].
Still, there is one problem with the current implementation. We still can write code such as this:


string[] types = new string[] { “application/json”, “application/x-json” };
Request request = new Request(types);
bool accepts1 = request.Accepts(”application/javascript”);
types[1] = “application/javascript”;
bool accepts2 = request.Accepts(”application/javascript”);

After running this code, accepts1 != accepts2. The problem is that we pass a referene to the constructor, and the object instance stores it in its local variable. We are free to change the object that our reference points to, indirectly changing the state of the object. In order to fix this, we change the constructor code for Request:


public Request(params string[] acceptedTypes)
{
_acceptedTypes = new string[acceptedTypes.Length];
Array.Copy(acceptedTypes, _acceptedTypes, acceptedTypes.Length);
}

Comments 2 Comments »