Musings<Biefeld>
- curiosities of development, life, the universe and everything -
Archive for the ‘C#’ Category
Thursday, 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.


Tuesday, 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);
	}
}
Tuesday, April 14th, 2009


I just finalized my text color theme for visual studio. Just thought I would share it with everyone. It is geared towards those of you who have resharper installed, but it should still work fine without it.


The theme is based off of the textmate twilight theme. I was going for a low contrast theme that is easy on the eyes.  I have tried the Vibrant Ink theme and it is too abrasive for me. My goal was to make warnings and errors blatantly obvious and distinguish classes from interfaces. I also love how the comments are dark and do not draw attention, I am not a big fan of comments.  I think the code along with BDD tests should be self-explanatory of what is going on.


All resharper warnings show up as red text. Build errors have red squiggly lines under them.  Breakpoints have red background.


Here is a c# example:



Here is an example of an aspx page:



Style sheet example:



JavaScript example:



Let me know if you have any suggestions.


Grab the Visual Studio settings file here!


Wednesday, February 18th, 2009


Obviously the answer to the titular question is yes.


I have recently found myself questioning whether the logic I am coding belongs in a domain service or in the presenter. I actually found the same logic in the presenter residing the base repository. Something definitely smells wrong, almost like the putrid smell of death, lol, nah just a DRY smell and a hint of mixed responsibility odor. The presenter was calling the Repository directly which was kinda of an indicator, but it is valid to do so, depending on the scenario.


The application that I am currently working in is a web application. That being said, I feel it is valid to consider the web limitations part of the current domain, not just a concern of the presentation. If we need to move to a windows app or something else, it will take a lot of refactoring, so why not just view the web’s issues as part of what affects the domain. Besides, is the purpose of the domain to be abstract enough to support multiple platforms or to dimish complexity? Anyway, that’s another discussion altogether, and I’m digressing.


Here’s the skinny, that’s a valid colloquialism isn’t it. I found string to integer conversion happening in two different places. Once in the presenter, grabbing a string Id from the view, converting it, calling an overloaded GetById method from the repository or throwing an exception if the Id was invalid. The overloaded GetById method was in the base repository, it either accepted a string Id or integer Id, if the string Id was invalid it was throwing an exception. Yikes, this is scary, and to think I was the one that coded all this, frightening, I know. I am recovering so don’t you worry yourself. Now to the current code:

Code to be Refactored:

Presenter

public virtual void InitializeView()
{
	if(TreatmentIdIsValid())
		LoadTreatment();
	else
		throw new ApplicationException(string.Format("A Record of Waste cannot be completed because of the invalid treatment id: {0}", View.TreatmentId));
}

private bool TreatmentIdIsValid()
{
	int validTreatmentId; 

	bool treatmentIdIsValid = int.TryParse(View.TreatmentId, out validTreatmentId); 

	if(treatmentIdIsValid)
		CurrentTreatmentId = id; 

	return treatmentIdIsValid;
} 

protected virtual void LoadTreatment()
{
	try
	{
		CurrentTreatment = Repository<ITreatmentRepository>.GetById(CurrentTreatmentId);
	}
	catch
	{
		throw new ApplicationException("Could not retrieve the specified treatment");
	}
}

Base Repository

public virtual Entity GetById(string id)
{
	int parsedId;

	if (!int.TryParse(id, out parsedId))
		throw new ApplicationException("Could not convert the given id: " + id + " into an integer");

	return GetById(parsedId);
}

public virtual Entity GetById(int id)
{
	return Session.Get<Entity>(id);
}

I think that there is no place for logic in the repository it should be left to the domain service. You could even argue that this functionality is common and can be moved to a domain utility. For ease I am going to move it to a domain service. Now, lettuce see the refactoring to the code above:

Refactored Code:

Presenter

public virtual void InitializeView()
{
	LoadTreatment();
}

protected virtual void LoadTreatment()
{
	CurrentTreatment = RecordOfWasteService.GetParentTreatmentById(CurrentTreatmentId);
}

Domain Service

public virtual Treatment GetParentTreatmentById(string id)
{
	int validTreatmentId;

	if (!int.TryParse(id, out validTreatmentId))
		throw new ApplicationException("Could not convert the given treatment id: " + id + " into an integer");

	return GetParentTreatmentById(validTreatmentId);
}

protected virtual Treatment GetParentTreatmentById(int treatmentId)
{
	try
	{
		CurrentTreatment = Repository<ITreatmentRepository>.GetById(treatmentId);
	}
	catch
	{
		throw new ApplicationException("Could not retrieve the specified treatment");
	}
}

Base Repository

public virtual Entity GetById(int id)
{
	return Session.Get<Entity>(id);
}

Alrighty then, we got any logic out of the repository, I’m feeling better already, my face has gone from grimace to grin, and no not the McDonlad’s character Grimace. Super serial, a la Al Gore about ManBearPig, what was Grimace, was he what you turn in to if you only eat McDonalds and nothing else?


The responsibility of the repository should be to read and write to persistence/web services/messages etc. The string validation logic is in the domain service, I may pull it out to a base service or utility service. Our presenter is so much simpler now, and not worried about logic that it shouldn’t have to worry about. Hmm, the cleanliness is delightful. There is no more duplication of logic in the presenter and repository, w00t! Now let me know your thoughts, comments, opinions etc. of dissent or agreement, it will help me and hopefully others learn and grow. I’m off to watch the some Teenage Mutant Ninja Turtle original series, wow, I’m a nerd.

Wednesday, February 11th, 2009

Today when preparing for our code review I happened upon a few methods in our base repository. Those methods were using NHibernate to retrieve collections of objects from persistence. I started scanning over the methods and figuring out what they were trying to accomplish. After understanding their function I noticed that they were prime candidates for a refactoring.

The methods were:

public virtual IList<Entity> GetAll()
{
	return Session.CreateCriteria(typeof (Entity)).List<Entity>();
}

public virtual IList<Entity> GetActiveItems()
{
	ICriteria criteria = Session
		.CreateCriteria(typeof(Entity))
		.Add(Restrictions.IsNull("InactiveDate"));

	return criteria.List<Entity>();
}

public virtual IList<Entity> GetItemsLikeName(string name, string columnToCompareBy)
{
	ICriteria criteria = Session.CreateCriteria(typeof(Entity))
		.Add(Restrictions.IsNull("InactiveDate"))
		.Add(Restrictions.Like(columnToCompareBy, name, MatchMode.Start).IgnoreCase());

	return criteria.List<Entity>();
}

Analysis:

Now the first thing that tipped me off to the need for Refactoring was the DRY (Don’t pete and repete yourself) principle, which can be extrapolated into Attwood’s Curly’s Law and even further to the Single Responsibility Principle. At least, I thinks DRY’s a principle, maybe it’s classified as a technique, or to be more in tune with coding hype a code smell. Lol, code smells, it may work if compared to flatulence but if you compare it to cheese, the more pungent the odor, the better the cheese. Actually it has more to do with identifying different smells so that you know what needs to be refactored or reworked entirely. Anyway, they all pretty much are talking about the same thing, minimizing duplicate code/rules/processes.

The Break Down:

The first thing I noticed was the responsibility of all the methods, they are responsible for retrieving a collection of objects. I observed this by the methods’ return types of IList<Entity> and their names, GetAll(), GetActiveItems(),GetItemsLikeName().

Next all of the methods are following the same basic pattern(process) of creating an ICriteria object, setting the specified ICriterion(where my object equals some value) on that ICriteria and finally executing the retrieval of the matching objects. The following is some psuedo code of that pattern(process)

ICriteria criteria = Session.CreateCriteria(typeof(Entity))
		.Add(ICriterion)
return criteria.RetrieveMatchingObjects<Entity>;

The Refactor:

Now we know the reponsibility and the process of all three methods. From this knowledge we can refactor those methods to use one method, but we will want to keep the signatures of each method, because they still have a separate responsibility as well. Let’s see the common concern is collection retrieval through different criteria. To address handling the different criteria we can utilize c#’s keyword params to pass in a variable number of criterion. Now, our combined method signature should look like:

protected virtual IList<Entity> GetAllItems(params ICriterion[] criterion)

Our refactored method is ready to return a collection of objects and to accept n number of ICriterion.

Next we need to create our ICriteria creation:

ICriteria getCriteria = Session.CreateCriteria(typeof(Entity));

After that it’s on to handling our array of ICriterion:

if (criterion != null)
{
	foreach (var criteria in criterion)
	{
		getCriteria.Add(criteria);
	}
}

First we need to check if the array is null, it is always good to check for null before trying to loop through an IEnumrable. Once we are sure that the array is not null we can loop through that bad boy and add the criterion to our ICriteria object. At this point we can execute our query, I prefer burning at the stake, but it’s up to you. Anyway our retrieval and return will (survey says) look like:

IList<Entity> result = getCriteria.List<Entity>();

Next on the proverbial platter, both the GetActiveItems() and GetItemsLikeName() methods are using the same criteria in their queries, the null check of Inactive Date. Ah ha, another point to refactor, stop the repetition. Let’s create a read onlyICriterion property named WhereInactiveDateIsNull, remember fluent interfaces are your friend. If the name is unclear now, it may make more sense in a bit, so chill.

protected virtual ICriterion WhereInactiveDateIsNull
{
	get
	{
		return Restrictions.IsNull("InactiveDate");
	}
}

Alright so we now have our one method to rule them all, or at least the three methods we were looking at before.

The Result:

So now all of our methods are going to call the method we created and tell that method their own specific responsibilites through the criterion they pass in.

protected virtual ICriterion WhereInactiveDateIsNull
{
	get
	{
		return Restrictions.IsNull("InactiveDate");
	}
}

protected virtual IList<Entity> GetAllItems(params ICriterion[] criterion)
{
	ICriteria getCriteria = Session.CreateCriteria(typeof(Entity));

	if (criterion != null)
	{
		foreach (var criteria in criterion)
		{
			getCriteria.Add(criteria);
		}
	}

	return getCriteria.List<Entity>();
}

public virtual IList<Entity> GetAll()
{
	return GetAllItems();
}

public virtual IList<Entity> GetActiveItems()
{
	return GetAllItems(WhereInactiveDateIsNull);
}

public virtual IList<Entity> GetItemsLikeName(string name, string columnToCompareBy)
{
	ICriterion whereColumnValueStartsWithNameIgnoringCase
		= Restrictions.Like(columnToCompareBy, name, MatchMode.Start).IgnoreCase();

       	return GetAllItems
	(
		WhereInactiveDateIsNull,
		whereColumnValueStartsWithNameIgnoringCase
	);
}

The Interlude:

“Oh, this little guy? I wouldn’t worry about this little guy.”


That just popped into my head, I must be astral projecting again. Seriously, if you don’t know what that quote is from, you fail at life, nah, just joking, look it up. Hmm, it must be late, my mind is wandering. Blogging and jamming. Jamming, is that still a socially acceptable term? Jamming to The Tangent, great stuff.

The Conclusion:

Ah, the fruits of our labor are so sweet. Remember, I know it’s hard, but remmember when I was speaking of the fluent interface, ah now you remember. Excellent, so if we take a look at our new GetItemsLikeName() method we can see the fluency at work;

we want to GetAllItems(WhereInactiveDateIsNull,(and) whereColumnValueStartsWithNameIgnoringCase).


If you can’t glean what this is doing from the naming, I am sorry, but there is no hope for you, :) . This fluent interface does several things, it decreases the learning curve for new-comers, increases the readability of our code, and overall increases the maintainability.

I find that the best thing to do is try to contemplate the Single Responsiblity Principle, Dont Repeat Yourself Principle, or other sundry names for it; when you are satisfying your broken tests, assuming you are testing first. I know that sometimes it can be hard but it is a fracking awesome practice to achieve. Even if you can’t see the common responsibilities at first, definitely try to find them after your tests pass. Red, Green, Refactor.


Friday, February 6th, 2009

How often do you use lambda expressions?  I use them a great deal, mostly when I am making method assertions in Rhino Mocks.  If you do the bare minimum, which i see a lot, the expression can be somewhat cryptic.

Less readable:

Users.Find(x => x.Id == selectedUserId)

I am guilty of doing this as well, without even realizing.  Maybe I am just being nit picky.

I think it is much more readable if you use something more descriptive than some arbitrary letter in the alphabet.

More readable:

Users.Find(user => user.Id == selectedUserId)

This becomes much more useful when you are coding more complex lambda expressions.  One example is when making a method assertion using Rhino Mocks.

Less readable:

_userRepository.AssertWasCalled
(
     x => x.Save(newUser),
     o => o.IgnoreArguments()
);

With that assertion we have two arbitrary letters, what the heck does ‘x’ and  ‘o’ represent.  Are we talking about hugs and kisses.  I don’t think so.

So to remedy this, lets change ‘x’ to ‘userRepository’ and ‘o’ to ‘method assertion’.  I believe these terms will make the assertion much more readable and concise.

More readable:

_userRepository.AssertWasCalled
(
     userRepository => userRepository.Save(newUser),
     methodAssertion => methodAssertion.IgnoreArguments()
);

With that little change it is much easier to understand what is being asserted and what parameters are being set on that assertion.

The hardest part is breaking the habit of using arbitrary letters.  In the long run a more descriptive expression improves the readability of the code.  It will also decrease the amount of time it takes a new person to understand the lambda expressions in the code base.

Wednesday, September 17th, 2008

I recently needed a textbox that would fire a server event when the textbox’s onblur JavaScript event was fired.  It took a while of googling and asking coworkers questions to figure out how exactly to do it.  Couldn’t seem to find an example of exactly what I needed.

 

I started off by creating a class that inherited from textbox and implemented ICallBackEventHandler.  I soon realized that this was not going to work for what I needed.  The ICallBackEventHandler is best suited for a simple Ajax control that just needs to update its own content.  Problem is that I need a post back to happen in order to update other controls on the page.

 

So instead of implementing the ICallBackEventHandler interface I implemented the IPostBackEventHanlder interface.  This turned out to be a much simpler, cleaner way to do it.

When implementing the IPostBackEventHandler you must Implement the RaisePostBackEvent method:

public class BlurTextbox : TextBox, IPostBackEventHandler
{
    #region Implementation of IPostBackEventHandler

    /// <summary>
    /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
    /// </summary>
    /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler. </param>
    public void RaisePostBackEvent(string eventArgument)
    {

    }

    #endregion
}

 

This method is what gets called by .net’s JavaScript when your control does a post back.

 

Now what we want to do is create the JavaScript function that will cause the post back will allow the RaisePostBackEvent method to handle the logic for that event.

 

I just created a method on the textbox that returns the script.  You can use the Page.ClientScript.GetPostBackEventReference(Control control, string argument) method but this is not necessary because all the it generates is __doPostBack(’controlName’,'argument’), either way works.

 

If you want to be able to have multiple instances of the control on the same page you need to write it yourself, this is what I did:

private string GetScript()
{
    return "function OnBlurred(control, arg)\n{\n __doPostBack(control, arg);\n}";
}

There are two parameters needed, the control and the argument, the control string that the asp.net JavaScript call is expecting will need the textbox’s UniqueID for it to work properly. 

Next I created a server side event on the control called Blur:

public delegate void OnBlurDelegate(object sender, EventArgs e);

public event OnBlurDelegate Blur;

private void RaiseOnBlurEvent()
{
    if(Blur != null)
    {
        Blur(this, EventArgs.Empty);
    }
}

Now we can call the RaiseOnBlurEvent() method in the implemented RaisePostBackEvent() method like:

public void RaisePostBackEvent(string eventArgument)
{
    RaiseOnBlurEvent();
}

Lastly I overrode the OnInit event, called the base.  I check if that script is already registered, if it’s not I register it, otherwise move one.  Then registered the OnBlurred script we created, and added the JavaScript onblur event attribute to the textbox.  I pass in the UniqueID and empty quotes because I don’t need any arguments.

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if (!Page.ClientScript.IsClientScriptBlockRegistered("OnBlurTextboxEvent"))
        Page.ClientScript.RegisterStartupScript(GetType(), "OnBlurTextboxEvent", GetScript(), true);
    Attributes.Add("onblur", "OnBlurred('" + UniqueID + "','')");
}

Now all that is left to do is use it on some web page and setup the server side handling.

Aspx:

<cc3:BlurTextbox ID="Test" runat="server" OnBlur="Test_OnBlur"></cc3:BlurTextbox>

Server Handling:

protected void Test_OnBlur(object sender, EventArgs e)
{
}

The whole thing is here.

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