Monday, 18 August 2014

Publishing via MSBuild and Web Deploy on a build machine

Whenever something stings me twice, I tend to write a blog post about it. I really should change that to anything that stings me once!

Our build machines (hanging off of TeamCity) were failing to run a little MSBuild command for web deploy publishing using a pubxml file. It would "work on my machine" perfectly fine, but the same command in the same environment on the build machine would simply stop after it was built and proudly pronounce "Done!" without actually publishing the files to our web server.

Irritating.

Not only that, but how do you Google something that hasn't failed? Eventually, you can, apparently. I ended up landing on a link that I recognised from the first time I searched for this particular issue, which references this, which then states:
If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.
It boils down to adding the following switch explicitly stating what VS version you are using, in my case, 2012:
/p:VisualStudioVersion=11.0
Makes sense, whatever. But wait! Why on earth does it work on my local machine at the project level without specifying a Visual Studio version? No idea and I haven't got to the bottom of it.

Suffice to say, the fix is going in and I'm moving on with my life.

I hate unexplained problems like these...

Friday, 21 February 2014

Gratuitous Code: Answer<T>

In a post I am calling Gratuitous Code, taking both definitions:
done without good reason, uncalled for
and...
given or done free of charge

Sales Pitch

Have you ever wanted to return the boolean answer to a question for something and also some extra data to go along with it? Well, now you can with this convenient type that covers the bases for you, it is also implicitly converted to and from boolean!

The Code

I give you, the Answer<T>!
/// <summary>
/// Wraps a common situation where you want to check if something is the case, and then
/// want the ancillary data to go along with it. It has implicit conversion to bool.
/// </summary>
/// <remarks>
/// For example, "has the file name changed?" returns the bool response and also the new file name.
/// </remarks>
public struct Answer<T> : IEquatable<Answer<T>> 
{
    private readonly bool _yesOrNo;
    private readonly T _value;

    public T Value
    {
        get { return _value; }
    }


    public Answer(bool yesOrNo, T value = default(T))
    {
        _yesOrNo = yesOrNo;
        _value = value;
    }


    public static implicit operator bool(Answer<T> answer)
    {
        return answer._yesOrNo;
    }

    public static implicit operator Answer<T>(bool b)
    {
        return new Answer<T>(b);
    }

    #region Equality

    public bool Equals(Answer<T> other)
    {
        return EqualityComparer<T>.Default.Equals(_value, other._value) && _yesOrNo.Equals(other._yesOrNo);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        return obj is Answer<T> && Equals((Answer<T>) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (EqualityComparer<T>.Default.GetHashCode(_value)*397) ^ _yesOrNo.GetHashCode();
        }
    }

    public static bool operator ==(Answer<T> left, Answer<T> right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Answer<T> left, Answer<T> right)
    {
        return !left.Equals(right);
    }

    #endregion
}

Thursday, 20 February 2014

Mercurial diff across renames

Whilst creating a Perforce Time Lapse view for Mercurial, I came across the need to diff a file's revisions that happened to feature a name change. If you just run the following command:
hg diff -r1 -r2 C:\MyRepository\MyFile.cs
What you get, in hindsight not surprisingly, is the diff showing the entire content of the file being "added". To get the sensible diff you can see if you were to use TortoiseHg (only the actual changes showing regardless of file rename), you need to specify the --git flag:
hg diff --git -r1 -r2 C:\MyRepository\MyFile.cs
I only tried this on a file that was successfully tracked by Mercurial as a renamed file, I'm not sure what would happen for file renames that Mercurial doesn't actually know about (perhaps if you renamed and changed the file at the same time). Either way, for me this works as I need it to - my view then goes on to parse the diff output and show change over time. More on that to come soon!

Getting ReSharper to implement Equality for you

Simply because I always forget this:

Place the caret inside the type, Alt+Insert to bring up the context menu and select "Equality members":


Choose the local members you wish to be part of the equality. That's it. It's anybody's guess as to why I keep forgetting this. For a full run-down of the options, see the official help.

Saves you a lot of typing at least :-)

Tuesday, 18 February 2014

Thrift and C#, Part 1: Introduction

This is hopefully the reboot of my blog; for the reasons why my blogging took a nose dive, consult this link.

Contents

This is a multi-part blog post, all parts are (or will be) listed here:

Preamble

I got a chance to use Thrift at work on Valentine's Day this year as part of the annual "Innovation Friday" event our parent company runs. This post is rightfully tagged "late to the game" because I originally thought Thrift was quite a new technology, but it started its open source life all the way back in 2007!

Me and two other guys worked on exposing a small part of our app over Thrift, to be consumed by an Android C# client (using Xamarin), an ASP.NET MVC client via a Web API layer, and a WinForms client.

The reason for the three clients was simply to exercise the portability of view models that were created over the Thrift service. In the end, the Android and WinForms clients ended up using the same view models (with some diligent hard-linking of code because the Thrift C# layers are not portable by default due to System.Web). The web client stuck to the MVC pattern, but included a Web API abstraction over the Thrift contract.

Installing Thrift on Windows

When a technology gives you installation instructions in Linux first and foremost and starts talking about cygwin for the Windows build steps I tend to switch off. However, I persisted and read the page carefully, spotting the pre-built exe link at the top, which I dutifully downloaded.

Downloading the per-language libraries is straightforward and gives you a compressed file. Unzip it, then unzip it again... Inside you will find a "lib" folder, inside that we are interested in "csharp". This is the C# implementation of Thrift and you will need to reference this DLL in any C# servers or C# clients that you want to consume your Thrift service from. I placed all this in C:\Dev\Thrift and added this as to my PATH environment variable. I also renamed "thrift-0.9.1.exe" to "thrift.exe".

The test to see if you are up and running is to try and generate the tutorial Thrift IDL into a set of C# files that you then add to your project (this is the contract that Thrift gives you for a given language based on the IDL). In our case, both the server and the client are C#, so we can simply re-use these files in both locations.

In a command prompt, run:
thrift --gen csharp -o C:\Dev\ThriftGen C:\Dev\Thrift\tutorial\shared.thrift
... for the shared stuff, then:
thrift --gen csharp -o C:\Dev\ThriftGen C:\Dev\Thrift\tutorial\tutorial.thrift
For the tutorial-specific items (notice this also nicely demonstrates the use of imports in IDL).

This instructs the compiler to generate C# classes for the shared and tutorial .thrift files and place them in a pre-existing folder C:\Dev\ThriftGen. If the output folder doesn't exist, it'll whinge. If you don't specify an output folder, it'll create a "gen-csharp" folder in whatever folder your command prompt is viewing.

Beyond the tutorial

Obviously the tutorial is next to useless for anyone who wants more than a Calculator as a Service. As testament to the simplicity of the IDL, my colleague emailed me what he thought would be a good enough contract for our demonstration that day, I simply copied it into a new .thrift file and generated C# classes from it without issue. I cannot use that example here as it wouldn't have any context or make much sense, so I'll create a small project with some sample data in that we can read from the service.

In the coming parts, we are going to fetch customer and orders (shockingly original) and also touch on some of the things that Thrift does not do. The most obvious hurdle you will find is deliberately limited data type support. This is because Thrift has to address the common types across languages. In C# you are missing things like DateTime, Guid, Decimal, though most primitives are there or trivially converted into existing Thrift types for transport.

I advise reading the short whitepaper about Thrift.

Thrift IDL

Base Types

There are a small set of basic types available:
  • bool: A boolean value, true or false.
  • byte: A signed byte.
  • i16: A 16-bit signed integer.
  • i32: A 32-bit signed integer.
  • i64: A 64-bit signed integer.
  • double: A 64-bit floating point number.
  • string: An encoding-agnostic text or binary string.
Unsigned types are not supported and that is a design choice, lots of languages do not have unsigned integers for example.

Structs

It is possible to define struct types, which are complex types containing other Thrift types (as you would expect). In the case of C#, and most object-oriented languages, these actually translate into classes. You can also specify default values for members of the struct.

Containers

There are a small set of collection wrappers available (which translate into common sense collections in C#):
  • list<type>: An ordered list of elements.
  • set<type>: An unordered set of unique elements.
  • map<type1 type2>: A map of strictly unique keys to values.
The nice thing with C# is these translate into generic collections.

Exceptions

Perhaps the best bit is that Thrift also supports Exceptions. These, in the Thrift world, are almost the same as a struct, however once generated they map to the native language's exception mechanisms. So in C#, that means inheriting from Exception.

Services

The whole point of Thrift is the service contracts, obviously there is little point defining all this shared stuff if you don't ever use it! This is basically an interface or pure abstract class in most object-oriented languages, and when passed through the generator, full client and server stubs are generated that implement the contract.

Coming up...

In part 2 we are going to define the IDL for our service and implement the server and server handler.

Tuesday, 8 October 2013

Placing breakpoints in lambda expressions

I used to be one, and now I still stumble across people who don't realise you can place a breakpoint in a lambda expression (that is part of a series of Linq statements, for example).

Simply right click on the content of the expression, "Breakpoint -> Insert Breakpoint". It will highlight in red just the expression, and will break there when the expression is hit (on a per-item basis if this is part of iteration).

Source question for this post: http://stackoverflow.com/questions/19248908/null-reference-exception-occuredlinq

Friday, 27 July 2012

SQL Update Join

I forget this every single time, so I Google "sql update join" and land on Ben Nadel's blog post. But today for some reason it is down, so I'm making this post.

This is the syntax:
UPDATE t
SET    t.Field = 'value'
FROM   MyTable t
JOIN   AnotherTable at
    ON at.Id = t.Id
Seriously, stop forgetting this!