Skip to main content

Posts

Showing posts from 2010

Serializing Anonymous Methods

I’m taking some time off from not blogging to do a little blogging. I hope this doesn’t inconvenience absolutely nobody. I was doing some [binary] serialization work recently when I came across a problem – I wanted to serialize objects with delegate fields that were populated with anonymous methods at runtime. To wit, I had types like this: public delegate void MakeMove(); public class AdrianPeterson { public int GameOneYards { get; set; } public Football Ball { get; set; } public MakeMove Move { get; set; } } Populated like this: var explicitDirections = new List<string> { "left", "right", "left" }; var ap = new AdrianPeterson(); var apName = ap.GetType().Name; ap.GameOneYards = 87; ap.Move = () => Moves.Weave(apName, explicitDirections); So, I pop a [ Serializable ] on AdrianPeterson (and Football ), and I’m set, right? Wrong. Wrong like getting away from running AP in the second half when the only receiving threat you have is bei...

Micro Fluency

I’ve been having a lot of conversations at work lately about how comments are a code smell , and if you’re not writing self-documenting code , ur doin it rong . Then I found myself in a position I’ve been in quite a few times… The general description is this: I have a method that takes two parameters. The action the method performs is best written in English in the form “{SomethingTheObjectDoesWith} {parameter1} {On/With/For/SomeOtherPreposition} {parameter2}”. The only way to name the method is “ SomethingTheObjectDoesOn/With/For(parameter1, parameter2)” . It seems like I run into this situation too often. The API for all of the concerned code doesn’t necessitate building out a huge fluent interface for readability, but it would be nice to have things read just a little better in this case. An example is certainly in order. I have an ASP.NET server control that activates a certain index on an associated MultiView . In order to let client code know whether or not it activates an in...

When an Object Isn’t an Object

I really wish there were more guidance on how to handle static reflection situations. Some kind of helper library would be nice. I’m actually surprised one doesn’t exist given its usefulness and the quirks involved. Consider this scenario – you’re reflecting over the details of a method call and the parameters passed. You actually care about the values that have been passed. How do you discover them? It goes something like this, I think: var argument = GetExpression(); if (argument.Type.IsValueType) { argument = Expression.Convert(argument, typeof(object)); } var getValueExpression = Expression.Lambda<Func<object>>(argument); var getValue = getValueExpression.Compile(); var value = getValue(); I found that here . If you don’t explicitly convert the value type to an object, you’ll get an exception that will confuse you (something to the effect of “Expression of type 'System.Decimal' cannot be used for return type 'System.Object'”). It’s confusing bec...

Teaser

These tests all pass: [Test] [ExpectedException(typeof(AssertionException))] public void ThrowsAssertionExceptionForWrongArgument() { Expect.Call(() => Console.WriteLine("A specific string.")); StaticClass.CodeUnderTestThatCallsConsoleWriteLine(); Verify.AllExpectations(); } [Test] public void VerifiesCallWithoutActuallyPerformingTheCall() { Expect.Call(() => Console.WriteLine("You shouldn't see me.")); StaticClass.CodeUnderTestThatCallsConsoleWriteLine(); Verify.AllExpectations(); } [Test] public void PerformsAlternativeAction() { Expect.Call(() => Console.WriteLine("YOU SHOULDN'T SEE THIS")).IgnoreArguments() .Do(() => Console.WriteLine("You should see this instead.")); StaticClass.CodeUnderTestThatCallsConsoleWriteLine(); Verify.AllExpectations(); } [Test] public void IgnoresArguments() { Expect.Call(() => Console.WriteLine("")).Ign...

VS Extensibility - It's So Easy!

(Note: This is an old post that was stuck in my backlog. I am publishing it now with the intent of writing more VS extensibility posts.) I have a colleague who laments the desire of developers to have (and tool developers to put) ‘everything in the IDE’. Anyone who has struggled with integrated source control fussing up a solution structure can probably identify with this view to some degree. Still, anyone who has used the NUnit GUI test runner for lack of having ReSharper or TestDriven.NET has had a taste of the case for IDE integration. When building small custom tools to enhance developer productivity and make it easy to perform mechanical tasks, why not stick them in Visual Studio? It turns out, it’s pretty easy to do. Consider a situation in which a developer has user accounts for each tenant of a multitenant application. These accounts get deactivated after a period of non-use, so they need to get reactivated in order for the developer to troubleshoot problems that manifest onl...

Defeating the Purpose of a DSL

First, I neglected to mention in my previous post that I found Paul Cowan's blog to be a tremendous help in figuring out how build a DSL with Boo and Rhino DSL . Second, I wanted to point out that, because this is an internal DSL written in Boo, it's still possible to use familiar programming constructs in the DSL scripts. For example, I could dynamically generate the team definitions from some other datasource, like so: stats = GetData() for row as DataRow in stats.Rows: define row["name"]: defense Determine.DefenseFromRanking(cast(int,row["defenseRanking"])) pass_offense Determine.PassOffenseFromRanking(cast(int,row["passOffenseRanking"])), with_qb_type(Determine.QbTypeFromRatingAndExperience(cast(double,row["qbRating"]), cast(int,row["qbExperience"]))) run_offense Determine.RunOffenseFromRanking(cast(int,row["runOffenseRanking"])) where GetData() returns a DataTable with multiple team statistics, and Det...

Building a Simple Data Definition DSL with Boo

In my daily work, I find myself writing a lot of one-off SQL scripts to handle various data issues. In particular, I've had to tweak existing sets of metadata with scripts that look something like the following: DECLARE @SomeId INT DECLARE @SomeOtherId INT SELECT @SomeId = SomeTableId FROM SomeTable WHERE SomeName = 'Something' SELECT @SomeOtherId = SomeOtherTableid FROM SomeOtherTable WHERE SomeOtherName = 'SomethingElse' IF NOT EXISTS( SELECT 1 FROM SomeMetadataTable WHERE Name = 'MetadataName') BEGIN INSERT INTO SomeMetadataTable (Name, Property1, Property2) VALUES ('MetadataName', @SomeId, @SomeOtherId) END ELSE BEGIN UPDATE SomeMetadataTable SET Property1 = @SomeId , Property2 = @SomeOtherId WHERE Name = 'MetadataName' END Just writing a few of these gets to be tedious, and master script...