Tag Archives: code

#REST-ish API with #WCF, part 2 Responses

If you thought the headache was over, I’ve got a treat for you. It’s not. But the “solution” isn’t far away though and quite straight forward. This hack is roughly the same like when working with the requests.

There is a built in constraint in WCF that you can only work with basically Json or XML. Or raw. That’s what all this fuzz is about. Too bad they didn’t make it obvious or easy to implement. The short explanation is however that if you request/return a Stream, it forces the WCF framework to abandon all it’s nifty things and smart moves and leaves it up to you to decide. So, set the return type to Stream, do your thing, serialization and what not. And send it out. The response will not get wrapped within the return type.

public Stream Check(Stream request){
  var json = ReadStreamAndDeserialize(request);
  
  //do stuff
  
  var jsonResponse = Serialize(response);
  
  WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
  return new MemoryStream(Encoding.UTF8.GetBytes(jsonResponse));
}

Why do this?

In our case we needed to serialize different types a bit differently and couldn’t get the internal serializer to work quite as we wanted. But also imagine that you could serve images back. You can even stream images back. And what if it is a file service? You could serve back whatever contenttype you like, and make it different depending on the file served. It does add some nice features you can work with to extend your options.

What you should also consider is what it does. In this case we make heavily use of the http protocol as opposed to others, which means it limits your options of just serving data over any protocol. It also takes you closer to the protocol you are working with, which can be both a blessing and a curse. If you don’t know what you are doing, you could end up in a lot of trouble and just having to write hack upon hack upon hack.

Check out the complete working example on GitHub.

Read more

Tagged , , ,

How to make a #REST-ish API with #WCF

Where I work we integrate a lot with external partners where they sometimes dictate the conditions. At the same time we have our technology, architecture and environment to deal with and solve it as good we can. This put us in a bit of a position recently when we were tasked with “make a REST API that conformes to this document”. We use WCF. And then there was headache.

But, since WCF is carrier agnostic, this shouldn’t be any problem right?! You can deliver via HTTP, TCP, you name it. It’s just the flick of a switch in some config. Turns out it wasn’t quite that easy. The document stated that the request will be sent as content-type “application/json”, it also stated that it will be a POST request and furthermore that the actual JSON request will be a payload in the BODY of the message. WCF don’t give you access to the body. Since it is by design to be protocol agnostic and not all protocols have a body or they differ from eachother.

This is all very well documented if you enter the correct search terms. Read more on both the problem and solution here, here (this is where most paths lead) and here.

This is mostly for me to remember for the future since I know now that I’ve gone through it I did it once before but forgot all about it until it was right there in front of me.

While it all sounds complicated it really isn’t. It’s as easy as 1-2-3, like David points out in his blog post on the subject.

1. Add a new WebContentTypeMapper, like so:

public class RawContentTypeMapper : WebContentTypeMapper
{
  public override WebContentFormat GetMessageFormatForContentType(string contentType)
  {
    //Make if-else statements here if you want to respond differently to different contentTypes. This one will always return Raw regardless of what you attack it with.
    return WebContentFormat.Raw;
  }
}

2. Make your new content type mapper available for use:

<bindings>
  <customBinding>
    <binding name="RawMapper">
      <webMessageEncoding webContentTypeMapperType="Your.Namespace.RawContentTypeMapper, Your.Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </binding>
  </customBinding>
</bindings>

3. Put the new available content type mapper to use:

<endpoint contract="MyContract" behaviorConfiguration="MyEndpointBehavior" binding="customBinding" bindingConfiguration="RawMapper" />

(4.) When working with a Raw content type, your usual way of working with WCF will be put slightly out of order. Instead of using your standard contracts, your method will need to take in a Stream. After that you are free to work as you like. Here is what we did.

public string Check(Stream request)
{
  var json = new StreamReader(request, Encoding.UTF8).ReadToEnd();
  var internalRequest = JsonConvert.DeserializeObject(json);
  var querystring = HttpContext.Current.Request.QueryString; //perhaps some additional data in here?

  //Do stuff

  return string.Empty;
}

The above will give you everything you wanted from the start. Almost.

Now you are thinking “NICE! And then I just use the UrlTemplate(…) to get a descent way of finding the methods!”. Well, not quite. It won’t turn out like http://mydomain.ext/api/check, but rather http://mydomain.ext/path/endpoint.svt/api/check. While I haven’t tried, I’d go with some URL rewriting in IIS or something. Perhaps you have a loadbalancer who can do it for you, or some other mechanism.

Tagged , , , ,

Friday coding contemplation

I haven’t really been to roads end with this one, so bear with me if it doesn’t quite make sense.

When coding, I usually like to keep my objects as immutable. But on the other hand I really like the verbose way of initializing objects with Object Initialization. Of course there are ways around this, like named parameters, or just the good old naming variables correctly.


  var p1 = new Person {
    FirstName = "Monkey",
    LastName = "Business",
    Age = 42
  };

  var p2 = new Person(
    firstName: "Monkey", 
    lastName: "Business", 
    age: 42
  );

  var p3 = new Person()
    .SetFirstName("Monkey")
    .SetLastName("Business")
    .SetAge(42);

Where the Set-methods looks like the following.


  public Person SetFirstName(string firstName)
  {
    FirstName = firstName;

    return this;
  }

  public Person SetLastName(string lastName)
  {
    LastName = lastName;

    return this;
  }

  public Person SetAge(int age)
  {
    Age = age;

    return this;
  }

While this doesn’t make the objects immutable at all, it does open some other benefits. From time to time I tend to really dislike properties because they are easy to misuse. I myself don’t have a right or wrong answer, but to me they should be lightweight accessors and not perform a whole slew of stuff. If you are in that position a method might be good.

I guess the gist of this is that there are ways of doing things which we might forget. And while we love our fluent APIs, we are quite crappy at actually creating and using them for ourselves when not served via a library, framework or something. But all we really have to do is return this;.

What’s your flavour?

Tagged , ,

Friday afternoon #coding #goodie

After our code retreat a couple of months ago I got some inspiration for improving code and specifically number of parameters. So instead of passing parameters all over the place and polluting methods creating long long long long long long long lines of unreadable stuff, there are now just 2 params for this particular method.

Before:

_contentRepository.List(request, marketFilter, showExtended, paging);
...
List(ReadMarketContents request, IEnumerable marketFilter, bool showExtended, IPage paging) {
  //do stuff
}

After:

_contentRepository.List(request, options);
 
List(ReadMarketContents request, dynamic options) {
  //do stuff
}

Since “options” is a dynamic expandoobject I can assign and read data from it as I please with the usual dot-notation without the reflection-crap making things unreadable, since the compiler handles it for me.

dynamic options = new ExpandoObject();
options.MarketFilter = base.Request.GetMarketFilter();
...
var marketFilter = options.MarketFilter as IEnumerable;

And all this goodness without getting a class explosion for each and every request case like in this example. Think it might be a good fit for these kind of optional parameters where scope is limited, since knowledge is required.

Tagged , ,

Good riddance – if-statements

TL;DR; A lot of your if-statements are unnecessary and makes you violate the open/closed principle (open for extension, closed for modification) among other things. Make sure to identify those and get rid of them a soon as possible. They are the ones which checks a type or parameter and then decide what to do in that case.

Open/closed principle

The O in SOLID principles. What it actually means is that a method and in extension, a class, should not be open for modification but only extension. The exception being if the rules actually have changed. Following this principle makes you and your fellow coders avoid changing the behavior by accident.

You could regard this as an extension of SRP (Single Responsibility Principle), where a specific piece of code have one and only one purpose. And the open/closed principle forces you even further in that direction, aswell as making your code DRY and encourages reuse and readability.

An ugly example

While it is easy to think of this for green field projects, it is probably even more useful in brownfield applications in the progressive work of cleaning up and make heads and tails of things. A not uncommon scenario is some kind of Init() method which takes care of some in data validation and checks for a type or enum to then decide what to do.

public class MyInitClass
{
  public void Init (string accomodationType) {
    //do some stuff
  
    switch (accomodationType) {
      case "apartment":
        //do stuff
        CalculateApartmentFare();
        //do stuff
        break;
      case "house":
        //do stuff
        CalculateHouseFare();
        //do stuff
        break;
      case "room":
        //do stuff
        CalculateRoomFare();
        //do stuff
        break;
      default: throw new ArgumentOutOfRangeException("Invalid type provided.");
    }
  
    //do even more stuff
  }
}


It looks innocent and perhaps not that intimidating. But what if the contents weren’t in methods? Even worse, there might be twenty accomodation types. And you can count on that there will be more in the future. You will have to make modifications to this piece of code each time, which might be cumbersome depending on what it looks like aswell as adding a bit of risk of not changing anything else. Who knows what might be hidden underneith or inbetween? There is also the impending doom of this if-statement being copied all over and not knowing all places to change.

The remedy

Don’t fear, there is something fairly easy you could do in several steps. One small baby step at a time. If the contents aren’t in methods. Do that first, make sure to stream line it so they behave as expected for each type and does only one thing.
After that perhaps you could break out the entire switch-statement into a method of it’s own. Is it copied else-where? Put the brand new method in a class and point all of the others to that class as well.
Still not satisfied, but coming closer. Even though it is now isolated in a class of its own, there is this ugly switch-statement. Not a fun thing to update each time and it is bound to the fare calculations of all the accomodation types. Break away the calculations to new classes for each accomodation type. Since all of the methods being called are of the type Calculate(), make them implement and interface with that single method on it.

Now it’s time to get rid of the pesky switch-statement, the foundation is there. Put the type-names in a dictionary with their corresponding calculation class as the value. Since they inherit the same FareCaluculator interface you can call Calculate() on all of them! It is more loosely coupled and you can safely add new ones without fear of disturbing others.

public class MyInitClass
{
  private readonly AccomodationCalculationConditioner _accomodationCalculationConditioner;

  public MyInitClass()
  {
    _accomodationCalculationConditioner = new AccomodationCalculationConditioner();
  }

  public void Init(string accomodationType)
  {
    var calculator = _accomodationCalculationConditioner.GetCalculationConditionForType(accomodationType);
    var fare = calculator.Calculate();
    //do more stuff
  }
}

public class AccomodationCalculationConditioner
{
  private readonly Dictionary _conditions;

  public AccomodationCalculationConditioner()
  {
    _conditions = new Dictionary
    {
      {"apartment", new ApartmentCalculator()},
      {"house", new HouseCalculator()},
      {"room", new RoomCalculator()}
    };
  }

  public IAccomodationsFareConditions GetCalculationConditionForType(string accomodationType)
  {
    if (_conditions.ContainsKey(accomodationType))
    {
      return _conditions[accomodationType];
    }
    throw new ArgumentOutOfRangeException("accomodationType", "Invalid accomodation type provided");
  }
}

public class RoomCalculator : IAccomodationsFareCalculation
{
	public double Calculate()
	{
		throw new System.NotImplementedException();
	}
}

public class HouseCalculator : IAccomodationsFareCalculation
{
	public double Calculate()
	{
		throw new System.NotImplementedException();
	}
}

public class ApartmentCalculator : IAccomodationsFareCalculation
{
	public double Calculate()
	{
		throw new System.NotImplementedException();
	}
}

public interface IAccomodationsFareCalculation
{
  double Calculate();
}

Now that wasn’t so hard was it? And even more, almost all of the SOLID principles are in there or are at least possible to apply if the need arises. But these are just bonuses, what it all boils down to and is the important point here, is if you consider the understandability of the Init() method. Is it hard to read? Is it hard to understand? Can you figure out what it does fairly easily? How about testability? And, would it be hard to change something in there? Would you consider it riskful to change something and not knowing what else might get affected? This is called orthogonality, that is something good.

Wrap up

Now, this is not _the_ way, it is only _a_ way. Which other ways do you know of? How do you approach dragons and other beasts out there luring in the code jungle? Hit me up on twitter to let me know!

Further reading

Tagged ,

Alert general!

At work we recently started decoupling our services a bit more than previously. It is an older system which has been around a few years and haven’t got much love. We quite quickly identified that work being done was done on the same thread as the request, in sync, so the user had to wait for all work to complete until they were released into freedom again.

Grabbing the beast by the horns my colleague started looking into and learning NServiceBus which we already use at the office for other systems. This way we could decouple the workload off of IIS and letting the user continue to work, instead of waiting half an hour for the import to finish, or a spritemap to completely regenerate. But, on the other hand the user didn’t get any response as when the job finished, or if it did finish.

Now what…? Signal it! RRRR!

This signaling/notification system can quite easily and nicely be achieved with todays techniques. Since we are more or less bound to Microsoft platform, we went for SignalR to solve it.

Now, out of the box SignalR don’t scale very well. But they do have a nice scale out technology which scales out via a backplane that might consist of almost any technology you choose. They ship support for SqlServer, Azure Servicebus and Redis. We have SqlServer in place so the choice was already made. This way any message sent via SignalR will be sent to the backplane, via which all other clients on other machines listens to and publishes messages to its users.

So with this in place we could handle our environment of loadbalancing and fail over. The last piece is the worker service described at the top, which will want to send an update when it finished or if it failed. This is achieved by adding it as another client to the equation.

To the code!

This example uses the canonical SignalR chat example. There are two web apps which could run on separate machines, and a console app which acts as the worker service and connects to one of the web apps as a client.

There is actually extremely little code involved to achieve this. What you do is this:

  1. Add both the SignalR and SignalR SqlServer backplane packages to your web apps from NuGet.
  2. Set up the backplane like so in the Startup class for each web app:
            public class Startup
            {
                    public void Configuration(IAppBuilder app)
                    {
                            GlobalHost.DependencyResolver.UseSqlServer(ConnectionStringProvider.SignalRPubSub());
                            app.MapSignalR();
                    }
            }
    

    Notice that the backplane itself will set up all required tables and stuff, so all you need to do is provide a connectionstring and a database.

  3. Make sure to add the SignalR Client package to the worker service, the one that will “call in” with additional messages.
  4. Then, calling in is simply as easy as just connecting to one the web apps, doesn’t matter which one, create a local hub proxy with the same name as the one you want to communicate with, and upon message sending – call the server side method of the hub.
            class Program
            {
                    static void Main(string[] args)
                    {
                            const string name = "Console";
                            var conn = new HubConnection("http://localhost:55566/");
                            var proxy = conn.CreateHubProxy("chatter");
    
                            conn.Start().Wait();
                            proxy.Invoke("Notify", "Console", conn.ConnectionId);
    
                            string message;
                            while ((message = Console.ReadLine()) != null)
                            {
                                    proxy.Invoke("Send", name, message).Wait();
                            }
                    }
            }

  5. Then… done!

The entire working code is available on GitHub for your pleasure. There is however some irrelevant code commited which fetches history. It’s not done in this example but it doesn’t affect the demo, so I just left it there. Might fix it in the future. What is left is to read the data back from a byte array in correct order.

Further reading

Tagged , ,