Friday, March 17, 2023

A short list of C# coding issues.

Injecting services into entities

It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts with a little entity class to do X. Then, oh, I'd like to be able to do some logging, so take an ILogger<X> as constructor problem..

Woops; now I need a wrapper or some outer factory style XFactory to provide the logger service... It's not too bad I suppose, just a bit cumbersome. 

Entities with async construction

Ok, yes, I know; a constructor should be a fairly dumb operation. The constructor's goal is (mor or less) to validate and preserve input parameters. 

But some times.. particularly if your trying to break out of a Service + DTO view of the world, an entity may need to call an async service method during creation.

Years ago this problem presented with C++ on windows, generally solved with a 2-phase construction.

2-phase is a valid pattern for richer entities, but id does introduce:
  • Created entity is NOT immediately usable.
  • Entity code now generally needs safety code to throw if not fully initialised 

Typed strings with serialization

Not quite sure what to call this. 

Often data is expressed as a string, but with some constraints. For instance a PathString will always start with a '/'. This can be a very useful constraint, particularly for string concatenation etc.

 I also find myself writing constrained string classes for jobs like ensuring a valid Kubernetes entity name.

But as I've done a few times now, I then need patterns to serialize / deserialize these typed-strings, and to cleanly use them with other code.


I'm hoping to soon publish a package for these issues; currently trialling a pattern, we'll see.

Wednesday, March 15, 2023

Introducing kwd.CoreUtil

 I built this a while ago; others may find it handy.


It's a small library focussing primarily on syntax sugar  for C#

kwd.CoreUtil v1.1.0:  Git / Nuget

The main code is a set of extensions to make working with FileInfo and DirectoryInfo more natural.

In addition there are some other utilities for strings and file streams.


Originally the design was to restrict this to ONLY depend on standard .NET Core packages. 

But more recently I stumbled onto System.IO.Abstractions; since the package is lite, and provides significant benefit; I've take it as a dependency


 So what's it good for?

Well, my favourite is the Ensure* extensions. 
Super handy to ensure a directory exists before used.

Have a look and provide some feedback :)

Tuesday, April 26, 2016

LIMO - LeastInMostOut methods

I've been experimenting with different guidelines to help me construct better code. In particular I've been pondering 'how to decide the best arguments for a method'. I started to consider this question a little more, while reviewing another colleagues code. I was struggling to understand what I didn't like about their code, and why. Finally I think I have a 'reason' why their code has a bad flavor to me.

The code was simple enough, but it took large, full agg-roots as parameters. What smelt funny was, only one little VO was needed, yet the class was now coupled to the full AR, without much reason.

As a result the class method was now coupled to the full AR, though it could have been much more reusable, simply by taking just the bit(s) needed. After some googling, and asking other seniors, I couldn't find anything to 'point at' and say, see this guy recons it's better not to couple the classes like that.

So now, here a post to 'point at'.

Guideline:

Methods should take least in arguments to do their job. They should return most out to callers (LIMO).

Why?
Taking the Least-in reduces coupling by only requiring the information needed by the method. It also improves readability by making it clear what the method needs. 

Return the Most-out data you can, this improves re-use of the method while reducing the need for change in the future (Open-closed principal).

Notes:

This does not mean every argument should be a string or some other native type. An arguments type help describes the constraints. For example a method "GetDataFromAServer()" should take a URI rather than just a String.

Another Trick I find useful is to look at how a method argument is used directly inside the method. If the argument is immediately converted to something else, then sometimes this is a clue that some refactoring may be needed.

I tend to return the 'most-data' so the caller can decided what is relevant to them. Some might think this leads to exposing internal class-structure, and I would agree. In my code 'returning the most' helps with unit tests, it also reduces re-coding. If / when I want to return less information, I generally have an interface to express this.

One last trick; at the moment I'm returning this on methods which would normally be void-return. The idea is that by returning this, I'm providing some info to the caller and making caller code flow more. I'm not wed to the idea, this does have a down-side. I now have some difficulty knowing if a method returns a new instance, or the same instance.


Thursday, April 14, 2016

Lifetime trick when migrating to mvc.net core 1

Recently while migrating projects from MVC.Net 5 to core 1 rc1 (mvc6 / vNext) I ran into an IoC problem. I was using Autofac as my container, and had just migrated some MVC filters. The filters were registered in the container using Autofac, and bound to MVC as global filters using ServiceFilterAttribute; following the post http://www.strathweb.com/2015/06/action-filters-service-filters-type-filters-asp-net-5-mvc-6/>here
Unfortunately at run time Autofac threw an error “No Scope with a Tag Matching ‘AutofacWebRequest’ “ . There is a reference to the problem on the Autofac site here
The error indicates either
  1. Trying to bind a long-life (singleton) object with a short-life (per request) object.
  2. Trying to resolve a per-request object before there is a request scope.
With these clues I finally worked out the problem, I have a combination of ‘binding’ approaches in my project.
Some services are bound using Autofac modules, here I was using InstancePerRequest() lifetimes. Other services were bound using the MVC container interface, in particular using IServiceCollection.AddScoped().
Using the Autofac MVC extensions, I add the MVC container bindings to the Autofac continer via ContainerBuilder.Populate(). This method maps the service registrations into Autofac. The mapping converts IServiceCollection Scoped bindings to InstancePerLifetimeScope().
Bingo
So some services were bound with InstancePerReqest(), while others with InstancePerLifetimeScope(). After consolidating my bindings to all use InstancePerLifetimeScope(), problem solved.

Tuesday, June 25, 2013

A stupid Team City build error

I've finally got Team City to run on Azure with the built-in database. But I was having terrible trouble getting my unit tests (MSTest) to run.

The error: 'Could not load file or assembly Autofac ...'

Every thing looked fine. Local build / test worked like a dream. NuGet packages loaded. CI build log showed Autofac was nu-get downloaded, and build success... I even fell back to RDP to build-box and run tests; again, success.

So what was the problem?

I used a simple short-hand to tell team city where the test assembly was: src/core.tests/**/*.tests.dll. This was (unexpected, by me at least) picking up both

  1. src/core.tests/bin/debug/core.tests.dll AND
  2. src/core.tests/obj/Debug/core.tests.dll

Fixing it

The fix is simple, just use a more exact setting in Team City src/core.tests/bin/Debug/*.tests.dll

Thursday, January 3, 2013

Resolving a content item url in Orchard

Recently I needed to create a link to edit a content item in Orchard. Orchard uses a url like http://mysite/Home/Admin/Contents/Edit/123, where the id corresponds to the content item id.

My first thought was to hand-craft the url, replacing the content id as needed. But I found a better way: use the item's meta-data. Firstly inject the orchard IContentManager as usual, then call IContentManager.GetItemMetadata() The returned ContentItemMetadata contains MVC route's, for my particular case, EditorRouteValues had all the data I needed.

In my exploration of Orchard, I am continually finding myself having to dive into the code to work out how to do things. So here is 'how' I finally stumbled on the meta data solution.

Firstly I knew the Content Control Wrapper performed some 'magic' which added a link to a content item's edit.
Alas so-far I have no special trick for getting from a feature to the code that implements it. But eventually I found Orchard.Core/Contents/ControlWrapper.cs which implements the feature as a IShapeTableProvider. In here we see Content is wrapped with a Content_ControlWrapper shape.

Since nothing particularly enlightening is happening, I went to the view for the shape: Orchard.Core/Views/Content.ControlWrapper.cshtml. In the view the Html.ItemEditLinkWithReturnUrl() caught my eye.

This ItemEditLinkWithReturnUrl() is an extension, tracked down to Orchard.Framework/Mvc/Html/ContentItemExtensions.cs

Navigating to find the core ItemEditLink helper, bingo, I found how the content item meta-data is used for route values.

Wednesday, December 19, 2012

Using async/await (TPL) with Orchard

While working on a module for Orchard CMS I ran into some problems trying to glue async (Task) based code with (classic) synchronous code.

Here's the set-up:
  • Service TheMovieDb to call themovedb.org api.
  • Service MovieInfo service to integrate TheMovieDb with Orchard.
  • AdminController for front-end to call MovieInfo and coordinate views.

TheMoveDb uses Tasks, so I don't have to wait around for across-the-wire calls. MovieInfo uses Tasks, and integrates with orchard services. AdminController uses normal Action methods.

Being a TDD developer, all the pieces looked fine. But as soon as I put it together... splat.

It all starts with a deadlock (doesn't it always!). A quick google gets to Stephen Cleary (via SO) Don't Block on Async Code and Async and Await Armed with this I now at-least understand the problem.

Alas, at least in Orchard 1.6, async controllers are a no-go. It took a fair bit of searching, I finally found an SO article describing the problem. So (for now) I've settled on a sync / async solution.

Putting it all together:
  • TheMoveDb service stays as a normal async service.
  • MovieInfo service calls TheMoveDb with ConfigureAwait(false).
  • AdminController stay synchronous; blocks on calls to MovieInfo, waiting for Result.

There was one last gotcha; anything after the await in MovieInfo service executes on its own thread. So no access to orchard services (such as WorkContext etc). To get around this I just had to take care to no need the 'orchard friendly' thread context after the await.

Tuesday, November 27, 2012

Azure web-role with warmup

To avoid the spin-up time on an Azure role, I use the IIS Application Initialization (formally warm-up) module. The module is available by default for IIS8, so it's easier if you can run your azure role on Server 2012 (osFamily=3).

The step-by-step instructions describe how to configure the module for use. Using this along side an article on programmatic configuring azure app pool settings, I've got enough pieces to create a RoleEntryPoint for the task.

You will also need to (find) and include a reference to the Microsoft.Web.Administration assembly. Oh, and in addition to configuring the module, be sure to set the IIS IdleTimeout to 0 (zero).

Putting it all together:
Loading ....

Monday, November 12, 2012

Display summary for content item in Orchard.

Lately I've been building skills using Orchard CMS.
I ran into a problem trying to display a list of content items; in particular the in-built summary approach for Orchard didn't suite. The in-built approach takes the first 200 characters and displays them via the shape: Parts_Common_Body_Summary. This shape is created down inside the ~/Core/Common/Drivers/BodyPartDriver.cs, to be served up via the Parts.Common.Body.Summary.cshtml view template. Then; within the template; the body's html is used to create a excerpt of the first 200 chars, displayed as a p.

For me, I wanted to be able to specify the summary shape using html described in the content item itself. Initially I looked at just customizing the template view, I think this approach may have solved my immediate problem, but I would have had (yucky) logic inside my view template. Sounds like a great excuse for creating a Module :D

Since this was my first Orchard module, there was quite a learning curve to piece together how-to go about this problem. I can recommend the Pluralsight training video's to help you get started. Otherwise the Orchard Doco can help. Of course, nothing beats learning by tracing code and figuring it out yourself :D.

Normal content part driver's in Orchard create a shape, which is then served up via Orchard (don't forget placement) and displayed using a view template. Initially I was inclined to follow this pattern, and create my own "Parts_MySummary" shape for use. For better-or-worse, I opted to alter the existing Summary shape, I'm not 100% this is a good idea, but hey, if the fine folk over on the Orchard Project are going to make such a highly flexible and extensible CMS, then this is the kind of thing that'll happen :O.

To over-ride the in-built shape, I use my own IShapeTableProvider to hook into the display of the Parts_Common_Body_Summary, and with the magic that is IoC tada!

Since I was there, the module is built using 3 strategies for the summary:
  1. Default (fallback) to in-built
  2. First paragraph - extract the first p element from the body
  3. Explicit text - editor defines the summary text to use.
Ideally I would have made this more extensible; allowing for other strategies to also be used. But I couldn't work-out how to add shapes at run-time to represent different strategies. For now, if you want a different strategy: Add an ISummaryStrategy service and provide a better Part editor. I will have to re-visit when I learn more.

The final module is hosted on codeplex: http://kwdsummary.codeplex.com/

Thursday, October 25, 2012

Some tricks for MsBuild + VStudio

Many developers that I work with avoid working with msbuild. This is a shame, since a little msbuild knowledge can go a long way. Here are some tips to help others leverage msbuild along with VStudio

Use .targets and .proj

Both extensions are common for MSBuild files. So which to use? I use the following to help clarify a MSBuild files purpose:

  • *.targets used for projects that are to be imported, these are generally MSBuild files that have little use unless imported into another MSBuild project.
  • *.proj used for projects that have their own useful targets. These are generally MSBuild files that contain targets to be called from command line.

Edit you .csproj to include a .targets project

A great way to leverage msbuild with your normal visual studio (.csproj) project, is to edit the .csproj and import a corresponding .targets file. As a convention, I name the import after the .csproj file, as an example; for a project MyApp.csproj I use a MyApp.targets import. Simply add the following in your .csproj file:

<Import Project="$(MSBuildThisFileName).targets" Condition="Exists('$(MSBuildThisFileName).targets')" />

After importing, you can now make interesting extensions to the build process using the BeforeTargets and AfterTargets attributes

As of VStudio 2012, I can edit my custom MyApp.targets and, without re-loading the MyApp.csproj the changes take effect.

A target naming approach

As your MSBuild project get more complex, you may find (like me) that it can help to use a kind of 2-Target approach. In such cases I try and use a Short name for outer; descriptive name for inner style.

My reasoning is that I use an 'outer' Task from the command line, wehere I want a short easier-to-type name. Whilst, when building the task(s) I want more descriptive names, for future-maintainability. For example, I might have a task makeHelp that calls an internall task AddItemsFromAdditionalPaths.

Use the MSBuild task

To help modularize, use the MSBuild task to 'call' an external project. In the child task, define an Output attribute, and assign a resulting item list to it. Now in the caller (parent) task simply assign the items using TargetOutputs.

Extend when need

MSBuid is surprisingly easy to extend. There are 2 well known extension libraries: MSBuild Extension Pack and MSBuild Community Tasks. If neither suite, its really easy to just create your own.

As another option, you can also inline a task (MSBuild in-line task). But I would recommend NOT doing this. A task is easier to understand when written as a C# class, rahter than in-line.

Leverage your .csproj project

Just as I like to extend my .csproj using a .targets file. It can also be useful to go the other way and build a .proj that imports your .csproj

The Visual Studio IDE is great for maintaining source files, and content files and other files in your project. You can use the UI to visually add and organize project files.

On occasion I take advantage of this using a MyApp.proj MSBuild project that imports MyApp.csproj. This way I can build targets that have access to ItemGroup's such as @(Compile) and @(Content)

Property Functions come in handy

Property Functions can be used to manipulate a property, the string manipulation is one of the more useful capabilities. Unfortunately the syntax is verbose, and can be challenging to read, so I tend to limit to simpler uses.

One of the more useful tricks, is to use property functions with item meta-data. To do this 'convert' meta-data to a string, and use it e.g

    $([System.String]::new('%(RelativeDir)')).Replace('Stub', '$(OutPath)')

Item Metadata for 'special' task processing

Metadata can be a clean way to extend an existing ItemGroup, allowing Tasks to alter how they behave. I prefer to use metadata over creating 'working' ItemGroups. If I find myself creating an ItemGroup just for a Task, e.g

<ItemGroup>
  <LogFilesToArchive />
<ItemGroup>

I prefer

<ItemGroup>
  <LogFiles Include="">
    <archive>$(oldFiles)</archive>
  </LogFiles>
</ItemGroup>

Using meta-data does have a down-side; you need to ensure all Items have the meta-data otherwise msbuild complains. To solve this use a ItemDefinistionGroup, or update the items with:

<ItemGroup>
  <LogFiles Include="@(LogFiles)">
    <archive></archive>
  <LogFiles>
</ItemGroup>

Using DependsOn in .csproj

VStudio uses DependsOn metadata to nest one item under another (like web.config and web.debug.config). You can do this for your own files. For example if you use partials, edit the .csproj to group all the files under one.

Add to ItemGroup with Recursive.

VStudio has a number of well-known item groups, such as @(Compile) and @(Content).

If you edit the .csproj, you can manually add items to these ItemGroups. It can be a faster / easier way to add items, rather then using the UI. I've even use recursive includes to add tree's of files to particular itemgroup's.

Monday, October 22, 2012

Accessing the Orchard current user content item

While working on a custom theme for my Orchard based site, I ran into a problem trying to leverage the current user content item. For my theme, I wanted to be able to present some additional information about the current user, from the header in my theme.

Orchard uses Theme modules to separate presentation from content, this separation is one of the (many) reasons I'm starting to really love Orchard. Using a combination of the Designer tools module, and VStudio, you can peruse the shapes displayed on your page. From this I easily replaced the User.cshtml view with my own, but I couldn't work out how to actually reach the current user content item; the default User.html (from ThemeMachine) uses WorkContent.CurrentUser, but this is the IUser not the content item itself!!??

Eventually I stumbled onto: http://orchard.codeplex.com/discussions/255594, and found the user content item is simply WorkerContent.CurrentUser.ContentItem. To keep my site clean, I opted to leverage the Profile module, and add my custom user data to the Profile content part. Then a little prep code in the view, and now I can leverage a custom DisplayName field in my view. I did have to rummage through the source code to find the best way to reach the data using the dynamic type, finally I settled on:

//http://orchard.codeplex.com/discussions/255594
//User controllable display name.
var displayName = String.Empty;
if(WorkContext.CurrentUser != null)
{
  dynamic user = WorkContext.CurrentUser.ContentItem;
  if(user.ProfilePart != null && 
    user.ProfilePart.Has(typeof(object), "DisplayName") &&
    user.ProfilePart.DisplayName.Value is string)
  {
    displayName = user.ProfilePart.DisplayName.Value.Trim();
  }
  
  if(String.IsNullOrWhiteSpace(displayName))
    { displayName = WorkContext.CurrentUser.UserName; }
}

Thursday, October 11, 2012

Using mq to manage local OSS code.

Recently I've started working with the Orchard CMS open source project. As part of this I needed to alter the code base to suite my environment. So how do I

  1. Manage local / my own changes to the source.
  2. Refresh my tree when the source updates.
  3. Take changes from other forks.
This particular project is using Mecurial (hg), so I can leverage the MQ extension to manage my local code.
I use TortiseHg to work with HG repositories, I'm not really a command-line kinda developer.

Enable MQ extension

Firstly, enable the MQ extension. Be sure to enable the extension in your global settings. More on patching from TortoiseHg Doc.

Clone the repo

The folks on the Orchard project use forks for managing contributions, since this is a local copy, I don't want a fork, just a local clone will do. Otherwise I'll be adding to the noise on the project by holding a fork for an extended time period.

Create your patches repo.

With MQ enabled, you now have a little diamond in the tool-bar. Click to view MQ stuff. Now create a MQ repo. This creates a new hg repository inside the .hg folder, called patches. Since this is itself a repository, working with it is just like working with another repository.
Note: it is NOT a sub-repo, I got confused thinking I could work with the MQ repository like a sub-repository... that ended in tears.

Make a change as a patch.

My first change was to update the azure project. Make the change, but do-NOT commit. Rather use the diamond  click 'new patch' and then commit using QNew. 
I find it useful to view the patch queue, use View--> show patch queue. Another check is to actually open the patches repository, find it inside the .hg folder and open in Tortoise, you should see your patch has been committed.

Update from main repo.

I can now, just like normal, pull from the main repository to get any changes.
before pulling, I like to undo my patches, then re-apply the patches after any updates. Then I can check if each patch is still relevant, and I can update each patch (if needed) to reflect the refreshed code.

Taking changes from another fork.

Orchard uses forks for contributions. Since a fork is just a clone on CodePlex, I can clone a local copy. From Tortoise I can create a patch for a particular change set using r-click export. Then in my local repository, I can import this as a patch using Repository --> Import.
WARNING: be sure to import to patches, not the repository itself.

Extracting a patch.

Any change I make on my local clone, maybe useful as a contribution back to the Orchard project. This can be a bit of a problem, since I may have a few local patches that I don't want to contribute back (because they have no use) to the project. The easiest way I've found is to:
  1. Fork Orchard and get a local clone (normal for Orchard). Open my fork clone.
  2. Use repository --> import and locate the patch in my local/.hg/patches folder.
  3. Import the patch to the Working Directory. Do-not import directly to repository.
  4. Fix the patch if needed, and commit the change set.
  5. All the other bits like running unit tests; push to my fork; submit pull request.
Well that's the plan, will have to see how it goes over time.


Monday, October 8, 2012

URL Rewrite for hosted mvc.net site.

Recently I've been working on deployment of an MVC.NET based site to Azure. As a part of this I needed to re-map request url's from the Azure dns host name to my dns host. After a few fumbling starts I opted to use the IIS URL Rewriter module. The module is installed (by default) on Azure so it was good to go. I spent a good while looking into some of the other available options, in particular the SEO templates for lower-case and trailing-slash. I've had prior experience with url re-writing modules... not much of it good. I did manage to get a re-write rule set to trim and lower case my urls, but I felt it was too fragile to keep.
In the end I settled on just a host-name redirect.
<system.webServer>
<.other.>
<rewrite>
  <rules>
    <rule name="HostName" enabled="true" stopProcessing="false">
    <match url="(.*)" />
    <conditions>
      <add input="{HTTP_HOST}" pattern="YOUR\.SERVICENAME\.cloudapp\.net" />
    </conditions>
    <action type="Redirect" url="{MapSSL:{HTTPS}}/YOURHOSTNAME/{R:1}"/>
    </rule>
  </rules>
  <rewriteMaps>
  <rewriteMap name="MapSSL" defaultValue="OFF">
    <add key="ON" value="https://" />
    <add key="OFF" value="http://" />
  </rewriteMap>
  </rewriteMaps>
  </rewrite>
</system.webServer>

Many thanks to RuslanY for his tips: http://ruslany.net/2009/04/10-url-rewriting-tips-and-tricks/.
This rule was inspired from the stackoverflow: http://stackoverflow.com/questions/2608994/iis7-url-rewriting-how-not-to-drop-https-protocol-from-rewritten-url

Of additional interest: http://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
http://www.iis.net/learn/extensions/url-rewrite-module/using-the-url-rewrite-module

Tuesday, October 2, 2012

Least-Concept-Method

Often when writing code a developer will use member overloading to provide an alternate convenient call interface on a class. Assuming the developer has at-least a passing interest in quality, they will try and stay DRY. To this end, one of the method overloads will contain the core 'work' for the member, whilst overloads will perform only simple tasks, and then hand-off to the core method to do the real work. But which overload is the best for the core?

I like to use a least-concept method for the core. By this I select a set of parameter(s) that are

  1. Not native types, or simple constants.
  2. Don't require the method to navigate deeply into the parameter(s) (one-level in is ideal).
Why not native types? 
Often I've seen code that uses a core method that extracts the most-basic, or native data from more complex objects, and implements the core with this. For example, say I have a CountLines() method that needs a file, the developer may go for the most basic CountLines(string fileName) style. This approach has the benefit of being flexible for the caller, but it sacrifices clarity. The next developer has to know that what I really mean is the full path to the file, not just its file name. You could argue the parameter is badly named (and I'd agree), but I still would prefer a stronger type. C# is a typed language, a better idea would be to leverage it. In this case I would go for a CountLines(FileInfo file) method.

Why not the most complex object as a parameter?
Sometimes you need to implement a method that takes a complex object, particularly when implementing an interface (plug-in), but the method only uses a small part of the complex object. Lets say you're implementing a RejectIfTooBusy(HttpApplication context) method. You want to reject if the current request is from a set of black-listed hosts. The context has the data you need via context.Request.Url.Host, but to reach this you need to check for nulls along the way. Rather than having this parameter conversion code in your main implementation, I prefer to pull out a core RejectIfTooBusy(Uri whoReqested) method, and have this overload called by the first. By separating out the core member, it becomes clearer that all I'm checking is the request url. It can also be useful to split a complex object, to highlight the bits that the method really uses.

Wednesday, September 12, 2012

Generic Split() extension

Recently I needed to break a set into multiple sub-sets, just like the String.Split() operation.
I couldn't find a simple answer; so a quick bit of code and now I have a simple generic Split<T>() extension you can use to split a collection similar to String.Split().

Code and ms tests found in the gist here: https://gist.github.com/3703440

Friday, August 10, 2012

My default browser is now IE9 :(

A monumental change for me.
I have just changed from chrome to IE9 as my default browser. I feel... kinda yucky.

Why? One simple but painful function: support for the file protocol e.g. file://server/share
In IE (and ffox I hear) it opens my local explorer, a very useful behaviour.
In Chrome.. it does nothing.
I spent a fair amount of time trying to find a work around, in the end... see title.

Friday, May 25, 2012

Quint with mstest

Recently I've been doing more complex JavaScript coding. As part of the process, I wanted a better approach for JavaScript unit tests. After a Google I've settled on using QUnit, from the jquery guys.

QUnit runs in browser, which I wanted, since I like to test on an actual browser JavaScript engine; its closer to what the user experiences. I also wanted to be able to run the tests the same way I run .net tests; in my IDE (vstudio), but out of the box quint can't do that.

There are approaches to use QUnit with a server, but these focus on CI; a good thing; but not what I was after.

So, with a little code, and some convention, I use a simple mstest base class to start a web server, open a page, run quint, return the result. I also use a small bit of JavaScript to get QUnit to call back to my test, reporting results.

See the gist: qunit + mstest; using simple in-proc webserver (https://gist.github.com/2784505)

With this, I now run the unit test in v studio, same as normal tests. Too easy.

Friday, November 25, 2011

IOC for objects loaded from orm

I like the idea of coding a Rich domain model, and then applying services to the model. Recently I was trying to get just a little closer to a rich domain, by resolving domain object dependencies during their creation via the ORM. I did find nhibernate supports this style, but alas I am currently constrained to use EF4.1 - code first.

The EF4.1 doco is.... Well there isn't any as best I can tell. For EF4 code first I've relied on blog entries, and perusing the API in object browser. In my quest for rich domain, I found no extension point in EF where I could manage entity proxy creation (pre or post load). I tried finding an override in the db context, no luck. I had some hopes there would be extensibility in te object tracker.. Nup :(.

So in the end I opted to wrap the EF model inside an IOC context aware class (spring.net), that way I coud at least get a post orm load IOC approach.
I've used a simple convention; when the ORM loads an entity, the entity full class name is used as a key in the IOC container. If it's found, the IOC is called, to resolve dependancies on the orm created object.

This approach is all I currently have, with ef4.1.
It works fine, for very simple situations, but since I've intercepted out side of the orm, I only get a shot at resolving dependencies on a top-level entity, not on any child objects that the ORMloads, which kind of makes the whole approach invalid, since I want my ORM to load a more complex entity model than just a set of top-level entities .

Wednesday, November 16, 2011

Add implied interface to a class.

Often... Well often enough, I need to use a .net framework class to implement a method. I almost always find that I want to use an interface on my class, so I can unit test it, and that the framework class provides no interface. This leads to me needing to define a interface, and implement it with a quick decorator around the framework class. Recently I was doing this with the Ping class when I decided to invest a little time looking for a better answer.

My first attempt was to use spring.net mix-ins, or introductions in AOP terms. That kinda worked, but since mixing require a class with the interface implementation, I still needed to write the decorator... not a whole lot better.

After more googling, turns out what I wanted is called duck-typing (who knew). And as with other problems, once you get the term, the googling is easy. I found a few different libraries that could help, I settled on impromptu.

It did take me a while to work out a good way of integrating with spring.net, i've used spring.net a fair bit, but haven't done a lot of extension work to date. Finally I settled on a custom factory object, it requires the target objec rand target interface, using that, it produces a ready to go decorator.
/emote "<-- nods and files away a new tool for the toolbox"

A quick sample class:

Thursday, November 10, 2011

Multiple submit buttons with MVC 3.

I recently needed to create a MVC (MVC3) view with multiple submit buttons.
A quick look around with Google and I found a couple of approaches, but I thought to myself, there must be a cleaner way.

Up till now I've been using the simple approach of creating a controller action where the method takes an extra parameter to describe which action to take like:

Controller:
public class MyController
{
public ViewResult Index() { return View();}

public ViewResult DoSomething(string action, string someData)
{
if(action == "Action1") {}
else if(action == "Action2") {}
else {/*unknown action.*/ }
}
}

xhtml:
<form action="My/DoSomething>
<input name="someData"/>

<input type='submit' name='action' value='Action1' />
<input type='submit' name='action' value='Action2' />
</form>

What I wanted was to be able to define my Controller to have multiple Actions, one for each submit action on a Form, like this:

public class MyController
{
public ViewResult Index() {return View();}

public ViewResult Action1(string someData) {return View();}
public ViewResult Action2(string someData) {return View();}
}

But alas, with MVC I couldn't construct a Route that would do this; MVC routing always uses the Forms action attribute to decide which Controller method to call.

In the end the answer wasn't that hard. I just created a smarter IRouteHander, and applied it to the MVC default route.
The HTML for the form looks almost the same, though I remove the Action from the Form's action attribute, since the route handler will look after that.
xhtml:
<form action="My>
<input name="someData"/>

<input type='submit' name='action' value='Action1' />
<input type='submit' name='action' value='Action2' />
</form>


Now the methods on my controller don't need 'special' arguments, and the world is a better place :D
Here is the custom RouteHandler:

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...