random thoughts and discussions on the things that interest me

InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain

Aaaah. Right. I didn’t expect that.

To set the scene, I’m writing a .NET 4.0 unit test in Visual Studio 2010 and using Microsoft Moles to test code that’s impossible to test (or something like that). My simplified unit test code can be found below.

using System.IO;
using System.IO.Moles;
using Microsoft.VisualStudio.TestTools.UnitTesting;

public classFileWrapperTest
    [TestMethod, HostType("Moles")]
    publicvoid TestMethod1()
        // arrange
        var fileWrapper = new FileWrapper();
        MFile.ExistsString = path => false;

        // act
        dynamic exists = fileWrapper.DoesExist(@"C:\temp\test.txt");

        // assert

    public classFileWrapper
        public bool DoesExist(string path)
            return File.Exists(path);

I’ve added a Moles assembly for mscorlib to the project and the following to AssemblyInfo.cs:

using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.IO.File))]

I run the test and bang, InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain. Now – because of the lack of complexity in the simplified code – you may have spotted the cause. Why, you will be asking, has the boolean “exists” been declared as dynamic? Well… simply in order to illustrate the point (the test would work otherwise)! The DLR bombs if you attempt a dynamic operatioon, specifically System.Runtime.CompilerServices.CallSiteBinder .BindCore(CallSite site, Object[] args) with (thanks to Reflector) this little gem:

if (!AppDomain.CurrentDomain.IsHomogenous)
    throw Error.HomogenousAppDomainRequired();

Now, I know that the AppDomain should be homogenous when running in Full Trust following the overhall to CAS has had in .NET 4.0 (more here) and as that’s what I’m coding in why isn’t it? Well, it turns out that when you host an MS Test inside a Moles test host that the AppDomain that is created for the test is not homogenous. And that’s it. I’m not sure what to do next? I’ve posted in the forums and sent an email to Microsoft but not had a real reponse yet. I guess I’ll just need to be aware that I can’t use the DLR inside of a Moles test host.

How Lotus Notes is the Worst Piece of Software Ever

I don’t have the time or knowledge to go into details but anyone who has had the misfortune to use Lotus Notes (any version) will no doubt concur that it is the worst piece of software ever. There are some in the industry that have documented it’s many, many pitfalls, details of which can be found here:

“The great thing about Lotus Notes is, that given that it is working in a Windows environment and that the ubiquitous keystroke in that I use to refresh in any other program is F5, whereas Lotus Notes has deemed it necessary to override this functionality to log you out thereby doing pretty much the exact opposite of refreshing (or somewhere in that ballpark).” – Paul Anderson

Tackling Code Reviews using Automation

I’m currently undertaking a QA exercise on outsourced code as it gets delivered. In order to increase the productivity of the review process by reducing the defects raised and number of iterative fix cycles, I have been involved in writing tools that can be used by the external developers for them to check for compliance with specific coding standards and techniques demanded by the business.

The tools I am using for this automation are StyleCop and FxCop, Microsoft’s free code styling and managed code analysis tool. A great number of the standards we have defined are covered by the default rules that ship with these tools but there have been exceptions. For instance, we do not expect any TODO comments in code that has been delivered.

There are several detailed tutorials covering how to write these rules so I’m not going to repeat what’s already out there (links below). (3 parts)

The code for my TODO rule is below. You simply need to call this method from one of the visitor callbacks mentioned in the above posts.

private static void FlagViolationForToDoComment(
    SourceAnalyzer analyzer,
    CsElement element)
    var todoComments = element.ElementTokens
        .Where(e => e.CsTokenType == CsTokenType.SingleLineComment ||
            e.CsTokenType == CsTokenType.MultiLineComment)
        .Where(c => c.Text
            .Substring(0, c.Text.Length >= 10 ? 10 : c.Text.Length)
    if (todoComments.Any())
        foreach (var comment in todoComments)

One of the things to watch for is that if you install StyleCop with the MSBuild plugin that StyleCop may reside in more than one folder with one instance being registered with Visual Studio, and the other with the Explorer shell. In order to update the rules for use with both you will need to copy your rules library into each installation folder; in my case:

C:\Program Files\Microsoft StyleCop
C:\Program Files\MSBuild\Microsoft\StyleCop\v4.4

There’s also a StyleCop contrib project that provides a test-runner allowing unit testing of your StyleCop rules. I can’t recommend this enough – in my mind the only way to write StyleCop rules is to use TDD.

Use the ActionName Attribute, Already

You heard.

I’ve done a bit of MVC in my time but Neville (who knows more than I do about Oracle but less than I do about MVC) just told me about the ActionName attribute. Here’s the lowdown:

That is all.

TF255440: The following account has a SQL Server login, but the login was denied access

I just got this error when trying to add an Administration Console User to TFS 2010 installed on Windows 7 using a SQL Server database on a different server:

TF255440: The following account has a SQL Server login, but the login was denied access: TEST\cameron.fletcher. The server selected to host the databases for Team Foundation Server is: SQL. The SQL Server login associated with the user account must be granted access to the SQL Server instance on that server.

It turns out that although I have a login specifically assigned to me on the SQL box because I am also a member of a SQL administrators group there appears to be some issue with the TFS logic when verifying the connection. The solution? I simply deleted the login and it worked for me.

File Transfer via Clipboard Text

I have recently been involved in some work that requires me to program on a Remote Desktop (via RDP over an SSL connection) so there is no development software installed locally. One of the downsides is that due to the restricted nature of the connection only text based copy and paste works, so it is not possible to transfer files onto the development environment. Not only this, but although the local machine has access to the internet, the development environment has none.

The solution? I wrote a console based application called MemCopy to copy files to and from the clipboard as text. It does this by either encoding the file as Base64 then saving it as text on the clipboard, or decoding it from the clipboard.

I’d only written this in one of the environments, so I had to decode it in the other before I could use it – a bit chicken and egg, if you ask me. Anyway, I have attached a link to the encoded text here (you didn’t think I was going to give you the solution on a plate did you?)

The code below is all that was required to decode it. I placed the encoding into the resources as a file.

byte[] buffer = Convert.FromBase64String(Resources.Encoding);
FileStream stream = new FileStream(
BinaryWriter writer = new BinaryWriter(stream);

The result? Awesomeness.

The [IT] Stig?

Andy Aitken in his normal working attire.


#500 Firewall Error ##

Occasionally I have received the following error when trying to send emails to other organisation from Exchange 2007:

Diagnostic information for administrators:
Generating server: #500 Firewall Error ##

It turns out that this is actually due to the Cisco router inspecting SMTP traffic. Entering the command below into IOS fixed the issue:

no ip inspect name SDM_LOW esmtp

Catastrophic Failure

Andy Aitken, a guy I work with, evidently abused his copy of Visual Studio 2008 to breaking point and got this message in return. Hats off.


UPDATE: It turns out that a week later I too rose to the dizzy heights of Aitken’s abuse:


Converting a CTE T-SQL Statement into Linq2Sql

Below is the SQL statement including the common table expression that I need to re-write using Linq2Sql for an application I’m working on. The query identifies the subset of most up-to-date records using a group by query in a CTE. It then performs a join back to the booking table to return the full list of most up-to-date records.What is noticeable about this particular piece of code is the join between table and CTE making use of the isnull keyword.

with cte (RootBookingID, CreatedTime)
        isnull(ParentBookingID, BookingID),
        max(CreatedTime) -- get the latset version
    from [system].Booking
    where Deleted = 0
    group by isnull(ParentBookingID, BookingID)

select b.*
from [system].Booking b inner join cte
on cte.RootBookingID = isnull(b.ParentBookingID, b.BookingID)
    and cte.CreatedTime = b.CreatedTime;

When rewriting this in C#, we first declare the query for the CTE as its own variable.

//define the cte to use as an anchor
var cte = from b in this.Model.Bookings
    where b.Deleted == false
    group b by b.ParentBookingID ?? b.ID into g
    select new
        BookingID = g.Key,
        CreatedTime = g.Max(b => b.CreatedTime)

We can then reuse this variable within our core query (below). Notice how the join on isnull is created by explicitly defining the name of the anonymous type.

//perform a join on the cte to get the results
var qry = from b in this.Model.Bookings
    join c in cte
        on new
            ID = (b.ParentBookingID ?? b.ID),
        } equals new
            ID = c.BookingID,
    order by b.PickUpTime
    select b;

The post here explains the stumbling blocks I encountered:

To join multi-valued keys you need to construct an anonymous type on both sides of the ‘equals’ that is the same type. The anonymous type initializer expression infers both type and name of members from the expressions that are supplied. Using the name = value syntax in the initializer you can specify the name the compiler uses when creating the type. If all members, types, and names are the same then the anonymous types are the same type.

« Newer PostsOlder Posts »