Category: .NET

WCF WTF (part 2)

Here’s few things I learned the hard way, about WCF.

  • Say you’re using sessions and you have custom behavior on your service and your session. Your session doesn’t get committed and first (or any other) message in session gets delivered over and over (or no message get’s delivered at all) – i.e. it becomes a Poison Message. You have tracing turned on, but all it says is enigmatic ‘RequestContext aborted.’

trace

The reason for that may be that your custom behavior throws an exception, that does get caught silently, but strangely, it does not show up in the trace log.

At least one operation on the ‘MyServiceWithConfiguration’ contract is configured with the TransactionFlowAttribute attribute set to Mandatory but the channel’s binding ‘MyBindingName’ is not configured with a TransactionFlowBindingElement. The TransactionFlowAttribute attribute set to Mandatory cannot be used without a TransactionFlowBindingElement.

As described here, by LeszekG netMsmqTransport does not use transaction flow to ensure that operations are performed atomically. You can set TransactionFlowAttribute.NotAllowed and your transaction will work perfectly fine.

 

  • This one is really obscure, and either I’m doing something completely wrong, or it’s a really misleading and plain wrong error message:

wcfwtf2

The actual problem seems to be that TransactionScopeRequired is set to false. Setting it to true, made the exception disappear, and the whole program worked. I’m still not sure however as to true reason for this, not validity of my solution. Can anyone explain this to me?

Technorati Tags:

Is Entity Framework the Pure Evil?

I could risk saying, that Entity Framework made what ALT.NET movement is today. It was strong voice of resistance against it, that gave the impulse to action for people that started evangelizing about alternative approaches, pointing out its flaws and suggesting corrective actions. I guess to some extent this strong voice has been heard at Microsoft, but due to various reasons, not many changes have been made for v1.0 release.

I’m not very surprised to see ADO .NET Entity Framework Vote of No Confidence. (Here you can see who signed it). Sure it’ won’t change anything instantly, but I think that the stronger the voice of people who care about these things, the more likely Microsoft will take them into account. The less products like Visual Studio Team System and Team Foundation Server, overloaded with wizards diagrams and ‘click me baby one more time’ windows.

Read it, and if you agree, sign.

Technorati Tags: ,

WCF and custom behaviors exceptions

I encountered interesting issue with WCF today. When calling a service method on the client side, I sometimes received fault with the following message:

The message with Action ‘SomeUri/Foo/Bar’ cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).

Turns out that this message is misleading. The real issue was, that custom ParameterInspector I had on the service side happened to throw an ArgumentNullException. This was silently caught by the WCF, which interpreted it as contract mismatch and that fault message was sent back.

Adding additional parameter checking in ParameterInspector fixed the issue.

Hope that helps.

 

Technorati Tags:

Posting to Twitter with Launchy

[UPDATE2]

This tool has been deprecated. I leave the download links as they are, but if you want to interact with Twitter from within Launchy you better check out updated version of this tool here.

[UPDATE]

I uploaded a binary version of the tool, for those who don’t want/can’t deal with source code.

Grab it here.

I’ve been using Twitter for few days now, and I’ve tried quite a few options to use it. Currently I’ve settled on three different ways of interaction with the services (excluding browsing its website)

  • When I’m in Firefox I use TwitterBar extension, that allows me to write posts in my address bar.
  • When I read posts (tweets?) of other users in Twihrl and I want to comment on them, I use Twihrl to post.
  • When I’m just doing something on my computer and I want to post without running Firefox or Twihrl I use my beloved app launcher – Launchy to post.

This last option is a little bit tricky and it required a little bit of work to set up. I assume you have Launchy already installed. If not, go get it here.

You’ll also need Twitt.Poster that we’ll be invoking from Launchy to do actual work for us. Just compile the project, set your username and password in app.config, and put the compiled files in some directory.

Next, open Launchy, right-click it, and select “Options”. Then navigate to “Plugins” tab, and select “Runny”. This is the plugin, that will invoke Twitt.Poster.

To make it do so, click the ‘+’ button at the bottom and add new entry to the grid. Name is the name of the command in Launchy – “twitt” in my example but you can call it whatever you like. Then Program is the fully qualified path to the executable of the poster application. Last column is command line arguments and you should set it to “$$”. Notice that you need to put dollar sings in quotation marks, otherwise it won’t work. When you’re done just click OK, and we’re all set.

launchy_twitter

Now you can invoke the command in Launchy, press tab, and enter your message. When you’re done just press enter and your message should get posted to Twitter.

launchy_twitter2

That’s it. So far this is my favorite way of posting to Twitter.

As for Twitter.Poster, use it however you like and don’t sue me if it breaks something. I publish it on terms of BSD licence. However, it uses Twitterizer library, that is licensed under terms of GPL v3, so take that into account when creating derivative work.

This is just a sample application that I created mostly for myself. However you can post bugs and feature requests in comments. I don’t want to promise anything, but I may implement some of them if there’s demand and I find some time.

Technorati Tags: ,

ALT.NET for dummies

ALT.NET is a wonderful movement. It’s a bunch of very smart and open minded people valuing good practices and using common set of tools. It’s discussion group is a great place to share ideas and ask for tips and help.

It’s all great, however there’s one thing that bothers me. The site says:

We are a self-organizing, ad-hoc community of developers bound by a desire to improve ourselves, challenge assumptions, and help each other pursue excellence in the practice of software development.

It’s true. However, as much as I feel strongly about patterns, practices and tools advocated by the movement, I still don’t think that jumping onto that wagon is easy for newcomers. Almost always right, means going against route of least resistance, but still – I don’t think we do enough to introduce the tools and concepts to those who hesitate.

One of the reasons why Ruby on Rails gained so much popularity is the amount of books (some of them are even free in pdf form) for beginners. One of the reasons why non-ALT.NET way of doing things is so popular is the amount of introductory books for each and every technology provided by Microsoft. There are samples, hands-on-labs, tutorials, step by step guides, screencasts, webcasts, podcasts, what have you…

On the other hand, I was trying to recommend to my friend, who wants to learn about IoC, Castle Windsor and loosely coupled design. I looked here and there, and I was disappointed with what I found.

There are blogposts, but they are mostly short, and touch upon single, random, small problem. They aren’t really good for introduction.

There are discussion groups, but they are geared towards people who have specific problems with technology. Someone who comes and asks “how do I use it” would most likely not get much help.

There are articles on codeproject, or some other portals, but they are brief, and try to cover either the very basics, or small subset of technology.

There are even multi-part tutorials, that try to touch upon more or less every aspect of the framework, but they too are brief and don’t provide firm foundation for someone to really grasp the concepts and start using the technology with confidence.

Finally there’s the documentation, but it documents the product, not introduces it to the newcomers.

So, what CAN we do to ease the pain of conversion for unbelievers on the way to become ALT.NETers? Is there hope?

Certainly! I can think of two solutions here:

  • Wikis proved to work as good medium to transfer knowledge. By creating Wikibooks dedicated to specific topics tools (TDD, NHibernate, MonoRail, NAnt, etc) we could collectively contribute and share our knowledge and experience with those who could benefit from it.
  • Or/And develop standard way of tagging posts aka ADN-code (alt.net code smile_wink) on blogs, and create an aggregator that would make all that knowledge easily searchable and accessible from one place. For example if post is tagged with:

altnet://type{tutorial}/level{1}/technology{mbunit}/keywords{row tests,unit tests}

it would mean that this is special post (as opposed to normal post), that is a tutorial, level 1 (meaning geared towards very beginners) regarding tool/technology called “mbunit” and its topic is “row tests” and “unit tests”.

That’s just my suggestions, I’m sure someone will come up with more, better ones.

All in all I’m just hoping, that we, as a community will find a way to make it easier to start with ALT.NET.

Technorati Tags:

I want that in C# 4.0 (or showing spec# love)

I don’t usually do that kind of things, but now I feel obligated. Well, here’s the deal:

Microsoft has put together a promising set of extensions to C# called spec#, that you can read, hear, or watch about, and even download it.

It’s a very nice set of features like non-nullable value-type fields,  preconditions, postconditions and more. Those are very helpful features, and I want to join the movement on the blogosphere, that arose spontaneously to show Microsoft that we do care about those things and we’d love to see those features incorporated into C# 4.0.

Technorati Tags: , ,

Simplifying Rhino.Mocks, Round III: kinds of mocks

My last two posts regarding Rhino.Mocks, attracted quite a lot of attention. Focusing on solution I proposed for limiting complexity around creation different kinds of mocks, one thing was pointed out by few people as not the best solution. Ayende called it “in your face! API design”, that is stating the kind of mock you want to create explicitly, via method parameter.

I don’t think that doing it via method name is any less explicit, but let’s not go there. Instead, let’s think for a while – why do we need 4 kinds of mocks anyway?

All differences boil down to one thing – how the mock handles unrecorded calls:

  • StrictMock (_repo.CreateMock overloads), any unexpected call results in exception being thrown.
  • DynamicMock (_repo.DynamicMock overloads), any unexpected call returns default(T), where T is return type, that is null or 0 for value types.
  • PartialMock (_repo.PartialMock overloads), this works only for classes and any unexpected call is not intercepted but forwarded to the actual method of that class.
  • Stub (_repo.Stub), this is similar to DynamicMock with addition, that if you assign a value to a property, it remembers that value.

Those are all very important differences but I’d say quite subtle. Subtle to a point, that I am willing to agree that specifying them upfront either via explicitly named creation method, or via explicit parameter is throwing “in your face!” decisions that you shouldn’t have to be concerned about at this point.

Morten Lyhr noticed this as well, and he suggested the following solution:

public class LoginPresenterFixture
{
   private MockRepository _mockRepository;
   private LoginPresenter _loginPresenter;
   private LoginView _loginView;
   [SetUp]
   public void Init()
   {
      _mockRepository = new MockRepository();
      _loginView = _mockRepository.DynamicMock<LoginView>();
      CreateLoginPresenter();
   }
   private void CreateLoginPresenter()
   {
      _loginPresenter = new LoginPresenter(_loginView);
   }
   [Test]
   public void Strict_Test_Not_As_Often_Used()
   {
      //Override default mock kind
      _mockRepository.StrictMockBehaviour(_loginView);//this is important
      using (_mockRepository.Record())
      {
         Expect.Call(_loginView.ShowView);
      }
      using (_mockRepository.Playback())
      {
         _loginPresenter.Show();
      }
   }
}

It’s some way of dealing with it but it still requires you to explicitly assign behavior to mock object.

It’s still incorrect level of granularity though: instead of class level (different class per different mock kind) we now deal with it on object level (different kind per object).

I’d however move it yet one step further, to method level (different kind per method).

It might look something like this:

   [Test]
   public void Strict_Test_Not_As_Often_Used()
   {
      using (_mockRepository.Record())
      {
         Expect.Call(_loginView.ShowView);
         //Decide what to do with unexpected calls:
         Expect.For(_loginView).NothingElse();//this is important
      }
      using (_mockRepository.Playback())
      {
         _loginPresenter.Show();
      }
   }

Again, difference is very subtle, but important: instead of explicitly deciding about kind of mock, we decide about what to do about unexpected calls, which is more natural and closer to the actual problem. Different kinds of mocks, are just proposed solutions. The ‘kind’ is no longer a property of the mock object.

It also makes it easier to start with mocking framework: decision about what to do about unexpected calls is not thrown at your face at the very first lines, hidden behind terms like “Partial” or “Dynamic”. Instead you make that decision explicitly (and this time it’s a good thing) in last responsible moment that is in the actual test.

Technorati Tags: , , ,

Static method vs instance method, Reflection.Emit and DynamicMethod

On IL level, when you’re accessing method’s parameters there’s a <sarcasm>small</sarcasm> difference between static and instance methods. Instance methods have implicitly 0th parameter set to this. So if you want to access your 1st parameter in instance method you have to emit ldarg.1, and in static method you have to emit ldarg.0.

It’s basic OO, yet it took me 2h to find out that this was the cause why my DynamicMethod was throwing NullReferenceException. I created a method that looked kind of like what I wanted my dynamic method to look like, and looked at its IL in Reflector. It was exactly what I was emitting to my dynamic method, yet it kept failing.

After way to much time it came to my mind that my DynamicMethod was static, whereas my reference method was instance.

 

Technorati Tags: , ,

Mocking with Moq and Rhino.Mocks

Last week I’ve read quite a few new blogposts about Moq mocking framework. I had looked at it once, when it was first released, but I didn’t find it interesting back then. Now that version 2.0 was released I decided to give it a go once again.

Here’s very simple model I created:

model

It’s a class with one method that uses helper object to obtain a value and possibly raise an event.

Here’s the whole code:

public interface IHelper
    {
        int Param { set; }
        string SomeMethod();
    }
    public class MyClass
    {
        public MyClass(IHelper helper)
        {
            Helper = helper;
        }
 
        public IHelper Helper { set; private get; }
 
        public event EventHandler MyEvent = delegate { };
 
        public void DoSomething(int parameter)
        {
            Helper.Param = parameter;
            string result = Helper.SomeMethod();
            if (result != null)
                MyEvent(null, EventArgs.Empty);
        }
    }

Now, to the fun part:

Let’s see how we can verify that when SomeMethod returns null, MyEvent is indeed not raised. First with Rhino.Mocks

   1:          [Test]
   2:          public void DoDomething_should_NOT_raise_MyEvent_when_helperSomeMethod_returns_null_Rhino()
   3:          {
   4:              var helper = _mocks.CreateMock<IHelper>();
   5:              var subscriber = _mocks.CreateMock<IEventSubscriber<EventArgs>>();
   6:              using (_mocks.Record())
   7:              {
   8:                  Expect.Call(helper.Param = 3);
   9:                  Expect.Call(helper.SomeMethod()).Return(null);
  10:                  DoNotExpect.Call(() => subscriber.Method(null, EventArgs.Empty));
  11:              }
  12:              using (_mocks.Playback())
  13:              {
  14:                  var sut = new MyClass(helper);
  15:                  sut.MyEvent += subscriber.Method;
  16:                  sut.DoSomething(3);
  17:              }
  18:          }

18 lines of code (you could cut that down to 13 simply by using ReplayAll() instead of Record() and VerifyAll in TearDown method instead of Playback, but I prefer it this way. My code is clean and quite well serves as documentation: Especially thanks to explicit usage of DoNotExpect.

The only awkward thing, is that whereas in both Expect call, I insert bare calls, in DoNotExpect.Call I had to use lambda. It’s a small inconsistency.

Now how would the same test look like with Moq?

   1:          [Test]
   2:          public void DoDomething_should_NOT_raise_MyEvent_when_helperSomeMethod_returns_null_Moq()
   3:          {
   4:              var helper = new Mock<IHelper>(MockBehavior.Strict);
   5:              var subscriber = new Mock<IEventSubscriber<EventArgs>>(MockBehavior.Strict);
   6:              helper.Expect(h => h.Param = 3);
   7:              helper.Expect(h => h.SomeMethod()).Returns((string)null);
   8:   
   9:              var sut = new MyClass(helper.Object);
  10:              sut.MyEvent += subscriber.Object.Method;
  11:              sut.DoSomething(3);
  12:          }

12 lines including one empty to visually divide setup part from testing part. Nice. There’s however one BIG problem with this code: it won’t compile. As I said earlier, You can’t have assignment in Expressions, and that’s what Moq is using, so if you want to set some properties on your mock… well – you’re out of luck. I also don’t like the fact that I have to cast null, to string. This seems redundant, but it’s only a small annoyance.

Bigger problem is that I can’t explicitly state that I expect MyEvent not to be raised.

Another thing, I couldn’t find a way to get hold of event raiser. I guess it’s just not there, so if you want to test events… you’re out of luck too.

Moq is interesting project for sure, it’s simple (simplistic) syntax made me think, about how complicated Rhino.Mocks became. Sure it’s orders of magnitude more powerful, but some unification of interfaces, even for a price of breaking some old code would be highly desired. I can imagine that for a newcomer current learning curve may seem steep. Especially the fact of using static classes makes API much less discoverable.

So I will stick to Rhino.Mocks, as it Moq is still to simple for serious use, but I’m glad it’s there. It brings some fresh ideas to the table, and there’s nothing better than a little competition.

Technorati Tags: , , ,

Implicit casting of generic classes

Can anyone tell me what am I missing here? Here’s a simple class

public class Mock<TType>

{

    private readonly TType _actual;

 

    public Mock(TType actual)

    {

        _actual = actual;

    }

    public TType Actual

    {

        get { return _actual; }

    }

    public static implicit operator TType(Mock<TType> item)

    {

        return item.Actual;

    }

}

That’s a generic class that defines implicit casting operator to it’s generic parameter, no magic here. The code compiles without warning. Methods like this one:

 

public TType ThisWorks<TType>()

{

    return new Mock<TType>(default(TType));

}

work as well.

What’s even more stunning, whereas this works:

Mock<string> mock1 = _mocks.Mock<string>();

string actual1 = mock1;

This doesn’t:

Mock<ISomethingUseful> mock2 = _mocks.Mock<ISomethingUseful>();

ISomethingUseful actual2 = mock2;

producing error message:

Error    1    Cannot implicitly convert type ‘Mocks.Mock<Mocks.ISomethingUseful>’ to ‘Mocks.ISomethingUseful’. An explicit conversion exists (are you missing a cast?)

Am I missing something here? Why does it say ‘explicit conversion exists’ when I created implicit conversion? Why it doesn’t work for the interface when it works for string?

[UPDATE:]

According to chapter 6.4.4 of C# 3.0 Language specification you just can’t have implicit conversion to an interface. This in yet another time when I hit an invisible wall trying to do something with generics…

And if you thought that

public class MyClass<TType>:TType

{

}

could be a solution: it isn’t – this won’t compile as well.

Technorati Tags: ,