Skip to content

Blogs

AutoMapper 3.3 feature: open generics

Jimmy Bogard - Sat, 12/20/2014 - 01:10

One of the interesting features of AutoMapper 3.3 is the ability to map open generic types. Open generics are those that don’t supply type parameters, like:

var openType = typeof(IEnumerable<>);

AutoMapper had some limited support for certain built-in open generics, but only the collection types. This changed in version 3.3, where you can now map any sort of open generic type:

public class Source<T> {
    public T Value { get; set; }
}

public class Destination<T> {
    public T Value { get; set; }
}

// Create the mapping
Mapper.CreateMap(typeof(Source<>), typeof(Destination<>));

Instead of using the normal syntax of the generic CreateMap method, you need to use the overload that takes type objects. This is because C# only accepts closed generic types as type parameters. This also means you can use all the configuration available for you to do member-specific mappings, but can only do them by referencing as a string instead of an expression. Not a limitation per se, but just something to be aware of.

To use the open generic mapping configuration, you can execute the mapping against a closed type:

var source = new Source<int> { Value = 10 };

var dest = Mapper.Map<Source<int>, Destination<int>>(source);

dest.Value.ShouldEqual(10);

Previously, I’d have to create maps for every closed type. With the 3.3 version, I can create map for the open type and AutoMapper can automatically figure out how to build a plan for the closed types from the open type configuration, including any customizations you’ve created.

Something that’s been asked for a while, but only recently have I figured out a clean way of implementing it. Interestingly enough, this feature is going to pave the way for programmatic, extensible conventions I’m targeting for 4.0.

Someday.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

Testing on the Toilet: Truth: a fluent assertion framework

Google Testing Blog - Fri, 12/19/2014 - 20:28
by Dori Reuveni and Kurt Alfred Kluever

This article was adapted from a Google Testing on the Toilet (TotT) episode. You can download a printer-friendly version of this TotT episode and post it in your office.


As engineers, we spend most of our time reading existing code, rather than writing new code. Therefore, we must make sure we always write clean, readable code. The same goes for our tests; we need a way to clearly express our test assertions.

Truth is an open source, fluent testing framework for Java designed to make your test assertions and failure messages more readable. The fluent API makes reading (and writing) test assertions much more natural, prose-like, and discoverable in your IDE via autocomplete. For example, compare how the following assertion reads with JUnit vs. Truth:
assertEquals("March", monthMap.get(3));          // JUnit
assertThat(monthMap).containsEntry(3, "March"); // Truth
Both statements are asserting the same thing, but the assertion written with Truth can be easily read from left to right, while the JUnit example requires "mental backtracking".

Another benefit of Truth over JUnit is the addition of useful default failure messages. For example:
ImmutableSet<String> colors = ImmutableSet.of("red", "green", "blue", "yellow");
assertTrue(colors.contains("orange")); // JUnit
assertThat(colors).contains("orange"); // Truth
In this example, both assertions will fail, but JUnit will not provide a useful failure message. However, Truth will provide a clear and concise failure message:

AssertionError: <[red, green, blue, yellow]> should have contained <orange>

Truth already supports specialized assertions for most of the common JDK types (Objects, primitives, arrays, Strings, Classes, Comparables, Iterables, Collections, Lists, Sets, Maps, etc.), as well as some Guava types (Optionals). Additional support for other popular types is planned as well (Throwables, Iterators, Multimaps, UnsignedIntegers, UnsignedLongs, etc.).

Truth is also user-extensible: you can easily write a Truth subject to make fluent assertions about your own custom types. By creating your own custom subject, both your assertion API and your failure messages can be domain-specific.

Truth's goal is not to replace JUnit assertions, but to improve the readability of complex assertions and their failure messages. JUnit assertions and Truth assertions can (and often do) live side by side in tests.

To get started with Truth, check out http://google.github.io/truth/

Categories: Blogs

Microsoft Virtual Academy Links for 2014

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

So I thought that going through a few Microsoft Virtual Academy links could help some of you.

Here are the links I think deserve at least a click. If you find them interesting, let me know!

Categories: Blogs

Temporarily ignore SSL certificate problem in Git under Windows

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

So I've encountered the following issue:

fatal: unable to access 'https://myurl/myproject.git/': SSL certificate problem: unable to get local issuer certificate

Basically, we're working on a local Git Stash project and the certificates changed. While they were working to fix the issues, we had to keep working.

So I know that the server is not compromised (I talked to IT). How do I say "ignore it please"? Temporary solution

This is because you know they are going to fix it.

PowerShell code:

$env:GIT_SSL_NO_VERIFY = "true"

CMD code:

SET GIT_SSL_NO_VERIFY=true

This will get you up and running as long as you don’t close the command window. This variable will be reset to nothing as soon as you close it. Permanent solution

Fix your certificates. Oh… you mean it’s self signed and you will forever use that one? Install it on all machines.

Seriously. I won’t show you how to permanently ignore certificates. Fix your certificate situation because trusting ALL certificates without caring if they are valid or not is juts plain dangerous.

Fix it.

NOW.

Categories: Blogs

The Yoda Condition

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

So this will be a short post. I would like to introduce a word in my vocabulary and yours too if it didn't already exist.

First I would like to credit Nathan Smith for teaching me that word this morning. First, the tweet:

Chuckling at "disallowYodaConditions" in JSCS… https://t.co/unhgFdMCrh — Awesome way of describing it. pic.twitter.com/KDPxpdB3UE

— Nathan Smith (@nathansmith) November 12, 2014

So... this made me chuckle.

What is the Yoda Condition?

The Yoda Condition can be summarized into "inverting the parameters compared in a conditional".

Let's say I have this code:

string sky = "blue";if(sky == "blue) {    // do something}

It can be read easily as "If the sky is blue". Now let's put some Yoda into it!

Our code becomes :

string sky = "blue";	if("blue" == sky){    // do something}

Now our code read as "If blue is the sky". And that's why we call it Yoda condition.

Why would I do that?

First, if you're missing an "=" in your code, it will fail at compile time since you can't assign a variable to a literal string. It can also avoid certain null reference error.

What's the cost of doing this then?

Beside getting on the nerves of all the programmers in your team? You reduce the readability of your code by a huge factor.

Each developer on your team will hit a snag on every if since they will have to learn how to speak "Yoda" with your code.

So what should I do?

Avoid it. At all cost. Readability is the most important thing in your code. To be honest, you're not going to be the only guy/girl maintaining that app for years to come. Make it easy for the maintainer and remove that Yoda talk.

The problem this kind of code solve isn't worth the readability you are losing.

Categories: Blogs

Do you have your own Batman Utility Belt?

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24
Just like most of us on any project, you (yes you!) as a developer must have done the same thing over and over again. I'm not talking about coding a controller or accessing the database.

Let's check out some concrete examples shall we?

  • Have you ever setup HTTP Caching properly, created a class for your project and call it done?
  • What about creating a proper Web.config to configure static asset caching?
  • And what about creating a MediaTypeFormatter for handling CSV or some other custom type?
  • What about that BaseController that you rebuild from project to project?
  • And those extension methods that you use ALL the time but rebuild for each projects...

If you answered yes to any of those questions... you are in great risk of having to code those again.

Hell... maybe someone already built them out there. But more often than not, they will be packed with other classes that you are not using. However, most of those projects are open source and will allow you to build your own Batman utility belt!

So once you see that you do something often, start building your utility belt! Grab those open source classes left and right (make sure to follow the licenses!) and start building your own class library.

NuGet

Once you have a good collection that is properly separated in a project and that you seem ready to kick some monkey ass, the only way to go is to use NuGet to pack it together!

Checkout the reference to make sure that you do things properly.

NuGet - Publishing

OK you got a steamy new hot NuGet package that you are ready to use? You can either push it to the main repository if your intention is to share it with the world.

If you are not ready quite yet, there are multiple way to use a NuGet package internally in your company. The easiest? Just create a Share on a server and add it to your package source! As simple as that!

Now just make sure to increment your version number on each release by using the SemVer convention.

Reap the profit

OK, no... not really. You probably won't be money anytime soon with this library. At least not in real money. Where you will gain however is when you are asked to do one of those boring task yet over again in another project or at another client.

The only thing you'll do is import your magic package, use it and boom. This task that they planned would take a whole day? Got finished in minutes.

As you build up your toolkit, more and more task will become easier to accomplish.

The only thing left to consider is what NOT to put in your toolkit.

Last minute warning

If you have an employer, make sure that your contract allows you to reuse code. Some contracts allows you to do that but double check with your employer.

If you are a company, make sure not to bill your client for the time spent building your tool or he might have the right to claim them as his own since you billed him for it.

In case of doubt, double check with a lawyer!

Categories: Blogs

Software Developer Computer Minimum Requirements October 2014

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

I know that Scott Hanselman and Jeff Atwood have already done something similar.

Today, I'm bringing you the minimum specs that are required to do software development on a Windows Machine.

P.S.: If you are building your own desktop, I recommend PCPartPicker.

ProcessorRecommendation

Intel: Intel Core i7-4790K

AMD: AMD FX-9590

Unless you use a lot of software that supports multi-threading, a simple 4 core here will work out for most needs.

MemoryRecommendation

Minimum 8GB. 16GB is better.

My minimum requirement here is 8GB. I run a database engine and Visual Studio. SQL Server can easily take 2Gb with some big queries. If you have extensions installed for Visual Studio, it will quickly raise to 1GB of usage per instance and finally... Chrome. With multiple extensions and multiple pages running... you will quickly reach 4GB.

So get 8GB as the bare minimum. If you are running Virtual Machines, get 16GB. It won't be too much. There's no such thing as too much RAM when doing software development.

Hard-driveRecommendation

512 GB SSD drive

I can't recommend enough an SSD. Most tools that you use on a development machine will require a lot of I/O. Especially random read. When a compiler starts and retrieve all your source code to compile, it will need to read from all those file. Same thing if you have tooling like ReSharper or CodeRush. I/O speed is crucial. This requirement is even more important on a laptop. Traditionally, PC maker put a 5200RPM HDD on a laptop to reduce power usage. However, 5200 RPM while doing development will be felt everywhere.

Get an SSD.

If you need bigger storage (terabytes), you can always get a second hard-drive of the HDD type instead. Slower but capacities are also higher. On most laptop, you will need external storage for this hard drive so make sure it is USB3 compatible.

Graphic Card

Unless you do graphic rendering or are working with graphic tools that require a beast of a card... this is where you will put the less amount of money.

Make sure to get enough of them for your amount of monitors and that they can provide the right resolution/refresh rate.

Monitors

My minimum requirement nowadays is 22 inches. 4K is nice but is not part of the "minimum" requirement. I enjoy a 1920x1080 resolution. If you are buying them for someone else, make sure they can be rotated. Some developers like to have a vertical screen when reading code.

To Laptop or not to Laptop

Some company go Laptop for everyone. Personally, if the development machine never need to be taken out of the building, you can go desktop. You will save a bit on all the required accessories (docking port, wireless mouse, extra charger, etc.).

My personal scenario takes me to clients all over the city as well as doing presentations left and right. Laptop it is for me.

Categories: Blogs

SVG are now supported everywhere, or almost

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

I remember that when I wanted to draw some graphs on a web page, I would normally have 2 solutions

Solution 1 was to have an IMG tag that linked to a server component that would render an image based on some data. Solution 2 was to do Adobe Flash or maybe even some Silverlight.

Problem with Solution 1

The main problem is that it is not interactive. You have an image and there is no way to do drilldown or do anything with it. So unless your content was simple and didn't need any kind of interaction or simply was headed for printing... this solution just wouldn't do.

Problem with Solution 2

While you now get all the interactivity and the beauty of a nice Flash animation and plugin... you lost the benefits of the first solution too. Can't print it if you need it and over that... it required a plugin.

For OSX back in 2009, plugins were the leading cause of browser crash and there is nothing that stops us from believing that similar things aren't true for other browsers.

The second problem is security. A plugin is just another attack vector on your browser and requiring a plugin to display nice graphs seem a bit extreme.

The Solution

The solution is relatively simple. We need a system that allows us to draw lines, curves and what not based on coordinate that we provide it.

That system should of course support colors, font and all the basic HTML features that we know now (including events).

Then came SVG

SVG has been the main specification to drawing anything vector related in a browser since 1999. Even though the specification started at the same time than IE5, it wasn't supported in Internet Explorer until IE9 (12 years later).

The support for SVG is now in all major browsers from Internet Explorer to FireFox and even in your phone.

Chances are that every computer you are using today can render SVG inside your browser.

So what?

SVG as a general rule is under used or thought of something only artists do or that it's too complicated to do.

My recommendation is to start cracking today on using libraries that leverage SVG. By leveraging them, you are setting yourself apart from others and can start offering real business value to your clients right now that others won't be able to.

SVG has been available on all browsers for a while now. It's time we start using it.

Browsers that do not support SVG
  • Internet Explorer 8 and lower
  • Old Android device (2.3 and less), partial support for 3-4.3
References, libraries and others
Categories: Blogs

Microsoft, Open Source and The Big Ship

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24


I would like to note that this post takes only public information available and are not based on my status as Microsoft MVP. I did not interview anyone at Microsoft for those answers. I did not receive any privileged information for writing this post. All the information I am using and the insight therefor are based on publicly available information.

When it happened

I'm not sure exactly when this change toward open source happened. Microsoft is a big ship. Once you start steering, it takes a while before you can feel the boat turn. I think it happened around 2008 when they started including jQuery in the default templates. It was the first swing of the wheel. Back then, you could have confused it for just another side project. Today, I think it was a sign of change.

Before this subtle change, we had things like Microsoft Ajax, the Ajax Control Toolkit and so many other reinvention from Microsoft. The same comment came back every time:

Why aren't you using <INSERT FRAMEWORK HERE> instead of reinventing the wheel?

Open source in the Microsoft world

Over 10 years ago, Microsoft wasn't doing open source. In fact, nothing I remember was open sourced. Free? Yes. Open source? No. The mindset of those days has changed.

The Changes

Initiatives like NuGetintegrating jQuery into Visual Studio templates, the multiple GitHub accounts and even going as to replace the default JSON serializer byJSON.NET instead of writing its own are all proofs that Microsoft have changed and is continuing to change.

It's important to take into account that this is not just lip service here. We're talking real time and money investment to publish tools, languages and frameworks into the open. Projects like Katana and Entity Framework are even open to contribution by anyone.

Without letting slip that Roslyn (the new C#/VB.NET compiler) as well as the F#'s compiler are now open sourced.

This is huge and people should know.

Where is it going today

I'm not sure where it's going today. Like I said, it's a big ship. From what I see, Microsoft is going 120% on Azure. Of course, Windows and Office is still there but... we already see that it's not an Open-Source vs Windows war anymore. The focus has changed.

Open source is being used to enrich Microsoft's environment now. Tools likeSideWaffle are being created by Microsoft employees like Sayed Hashimi and Mads Kristensen.

When I see a guy like Satya Nadella (CEO) talk about open source, I think it is inspiring. Microsoft is going open source internally then encouraging all employees to participate in open source projects.

Microsoft has gone through a culture change, and it's still happening today.

Comparing Microsoft circa 2001 to Microsoft 2014.

If you were at least 10 years in the field, you would remember that way back then, Microsoft didn't do open source. At all.

Compare it to what you've read about Microsoft now. It's been years of change since then and it's only the beginning. Back then, I wouldn't have believed anyone telling me that Microsoft would invest in Open Source.

Today? I'm grinning so much that my teeth are dry.

Categories: Blogs

List of d3.js library for charting, graphs and maps

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

So I’ve been trying different kind of library that are based on d3.js. Most of them are awesome and … I know I’m going to forget some of them. So I decided to build a list and try to arrange them by categories.

Charts
  • DimpleJS – Easy API, lots of different type of graphs, easy to use
  • C3.js – Closer to the data than dimple but also a bit more powerful
  • NVD3.js – Similar to Dimple, require a CSS for proper usage
  • Epoch – Seems to be more focused on real-time graphs
  • Dygraphs – Focus on huge dataset
  • Rickshaw – Lots of easy chart to choose from. Used by Shutterstock
Graphs

Since I haven’t had the chance to try them out, I won’t be able to provide more detailed comments about them. If you want me to update my post, hit me up on Twitter @MaximRouiller.

Data Visualization Editor
  • Raw – Focus on bringing data from spreadsheets online by simply copy/pasting it.
  • Tributary – Not simply focused on graphics, allows you to edit numbers, colors and such with a user friendly interface.
Geographical maps
  • DataMaps – Not a library per say but a set of examples that you can copy/paste and edit to match what you want.
Categories: Blogs

How to display a country map with SVG and D3js

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

I’ve been babbling recently with charts and most of them was with DimpleJS.

However, what is beside DimpleJS is d3.js which is an amazing tools for drawing anything in SVG.

So to babble some more, I’ve decide to do something simple. Draw Canada.

The Data

I’ve taken the data from this repository that contains every line that forms our Maple Syrup Country. Ours is called “CAN.geo.json”. This file is called a Geo-Json file and allows you to easily parse geolocation data without a hitch.

The Code
var svg = d3.select("#chartContainer")
    .append("svg")
    .attr("style", "solid 1px black")
    .attr("width", "100%")
    .attr("height", "350px");

var projection = d3.geo.mercator().center([45, 55]);
var path = d3.geo.path().projection(projection);

var g = svg.append("g");
d3.json("/data/CAN.geo.json", function (error, json) {
    g.selectAll("path")
           .data(json.features)
           .enter()
           .append("path")
           .attr("d", path)
           .style("fill", "red");
});
The Result var svg = d3.select("#chartContainer") .append("svg") .attr("style", "solid 1px black") .attr("width", "100%") .attr("height", "350px"); var projection = d3.geo.mercator().center([45, 55]); var path = d3.geo.path().projection(projection); var g = svg.append("g"); d3.json("/data/CAN.geo.json", function (error, json) { g.selectAll("path") .data(json.features) .enter() .append("path") .attr("d", path) .style("fill", "red"); }); Conclusion

Of course this is not something very amazing. It’s only a shape. This could be the building block necessary to create the next eCommerce world-wide sales revenue report.

Who knows… it’s just an idea.

Categories: Blogs

Animating your charts with Storyboard charts from DimpleJS and d3js

Decaying Code - Maxime Rouiller - Fri, 12/19/2014 - 20:24

chart-line-148256_640

Storyboard are charts/graphs that tell a story.

To have a graph, you need a timeline. Whether it’s days, weeks, months or years… you need a timeline of what happens. Then to have a chart, you need two axis. One that tells one version of the story, the other that relates to it. Then you move things forward in time and you move the data point. For each of those point, you also need to be able to label that point.

So let’s make a list of what we need.

  1. Data on a timeline.
  2. One numerical data
  3. Another numerical data that correlate to the other in some way
  4. A label to identify each point on the graph

I’ve taken the time to think about it and there’s one type of data that easy to come up with (I’m just writing a technical blog post after all).

Introducing the DataSet

I’ve taken the GDP, Population per country for the last 30 years from World Economics and merged it into one single file.

Note: World Economics is very keen to share data with you in format that are more readable than what is on their website. Contact them through their twitter account if you need their data!

Sound simple but it took me over 1 hour to actually merge all that data. So contact them to have a proper format that is more developer friendly.

Here’s what is the final result:

graphAnimation

So this is the result I have.

The Code

That’s the most bonkers thing ever. Once you have the data properly setup, this doesn’t require that much code. Here’s what the code to generate the same graph on your end:

$.ajax("/GDP.csv", {
    success: function (data) {
        var csv = d3.csv.parse(data);

        var post3 = function () {
            var svg = dimple.newSvg("#storyboardGraph", 800, 600);
            var chart = new dimple.chart(svg, csv);

            csv = dimple.filterData(csv, "Year", ["2000", "2001", "2002", "2003",
                "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011",
                "2012", "2013", ]);
            
            var frame = 2000;
            chart.addMeasureAxis("x", "GDP");
            chart.addMeasureAxis("y", "Population");
            chart.addSeries(["Country"], dimple.plot.bubble);
            var story = chart.setStoryboard("Year");
            story.frameDuration = frame;
            story.addOrderRule("Date");
            chart.draw();
        };
        post3();
    }
});
Conclusion

Stop using weird graphing library that will cost you an arm and a leg. Your browser (both desktop and mobile) can handle this kind of technology. Start using it now.

See DimpleJS for more examples and fun scenario to work with. Don’t forget to also follow John Kiernander on Twitter.

As usual, the source is available on Github.

Enjoy!

Categories: Blogs

EuroSTAR – Star – Paul Gerrard

The Social Tester - Fri, 12/19/2014 - 13:00

This is a short series leading up to Christmas where I feature a tester that was at EuroSTAR 2014, who I personally believe you, my readers, will benefit from knowing. The last tester in this short series before Christmas is Paul Gerrard. For those that don’t know – Paul Gerrard was conference chair at this … Read More →

The post EuroSTAR – Star – Paul Gerrard appeared first on The Social Tester.

Categories: Blogs

Static code analysis for LoadRunner scripts

My Load Test - Fri, 12/19/2014 - 10:41
The idea of static code analysis has been around since at least the 1970s. These days, some kind of static analysis is usually built into most good quality IDEs (or it is available as a plug-in). Static analysis tools find bugs in software by looking at the program’s source code rather than executing the program. […]
Categories: Blogs

The So in Absolute

Hiccupps - James Thomas - Fri, 12/19/2014 - 08:51
In a job interview once, the candidate said to me
All software requires regression testingand I said
 All software requires regression testing?(I didn't think I could put stress on regression testing as well. It might have sounded like I was shouting.)

The candidate said - after a reasonably lengthy pause - simply
Yes. When reporting something as apparently absolute, I want my testers to caveat, to contextualise, to define the scope of the statement
I'm saying X, so long as ...When presented with an unequivocal, absolute, universal statement, I want my testers to be thinking about the ramifications, to be testing it
You're saying X, so what about ...Well, if I want to stay on the right side of Batman, I want them to do those things so far as it makes sense in their context.

So here's a bit of seasonal fun: what scenarios can you think of where software doesn't require regression testing? Be as creative as you like and stuff them into the comments.
Image: https://flic.kr/p/7N8dfY
Categories: Blogs

EuroSTAR – Star – Declan O’Riordan

The Social Tester - Thu, 12/18/2014 - 13:00

This is a short series leading up to Christmas where I feature a tester that was at EuroSTAR 2014, who I personally believe you, my readers, will benefit from knowing. Next up is Declan O’Riordan. Before EuroSTAR 2014 I’d met Declan a couple of times and seen him present a good talk at SIGIST. I … Read More →

The post EuroSTAR – Star – Declan O’Riordan appeared first on The Social Tester.

Categories: Blogs

MediatR hits 1.0

Jimmy Bogard - Wed, 12/17/2014 - 16:45

I’ve been using a project I wrote/borrowed/stole from a number of internal projects and existing libraries (thanks Matt) for well over a year now, and are releasing to 1.0. MediatR helps turn complex code into simplified request/response interactions, encapsulating queries, commands and notifications into a single, simple interface, collapsing complex controllers into simple pass-throughs to the real work being done:

public class ConferenceController : Controller
{
    private readonly IMediator _mediator;

    public ConferenceController(IMediator mediator)
    {
        _mediator = mediator;
    }

    public ActionResult Index(IndexQuery query)
    {
        var model = _mediator.Send(query);

        return View(model);
    }

    public ViewResult Show(ShowQuery query)
    {
        var model = _mediator.Send(query);

        return View(model);
    }

    public ActionResult Edit(EditQuery query)
    {
        var model = _mediator.Send(query);

        return View(model);
    }

    [HttpPost]
    public ActionResult Edit(ConferenceEditModel form)
    {
        var conf = _mediator.Send(form);

        return this.RedirectToActionJson(c => c.Show(new ShowQuery { EventName = conf.Name }), "Default");
    }
}

MediatR lets you send a request to a single handler:

var request = new ApproveInvoiceRequest {
   InvoiceId = invoiceID
};
ApproveInvoiceResponse response = mediator.Send(request);

Or do it asynchronously:

var request = new ApproveInvoiceRequest {
   InvoiceId = invoiceID
};
ApproveInvoiceResponse response = await mediator.SendAsync(request);

Or send a notification to a number of handlers:

var notification = new InvoiceApprovedEvent {
    InvoiceId = invoiceId
};
mediator.Publish(notification);

I’ve talked about the advantages to this pattern many times, and we use this pattern on nearly every project we encounter these days. The goal of MediatR was to create a small, unambitious implementation of the Mediator pattern, tied only to the Common Service Locator library for instantiating handlers and portable, so it works on just about every platform checkbox I could check, including Xamarin.

The GitHub repo has examples for plugging in all the major containers, and the wiki has documentation. Although the library uses Common Service Locator, it’s completely DI friendly too. Ultimately, the compositional tool is your container, and MediatR merely provides the mediation from message A to handler of A. Enjoy!

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

EuroSTAR – Star – Stephen Janaway

The Social Tester - Wed, 12/17/2014 - 13:00

This is a short series leading up to Christmas where I feature a tester that was at EuroSTAR 2014, who I personally believe you, my readers, will benefit from knowing. Next up is Stephen Janaway. I’ve known Stephen for a few years now and we regular speak at the same conferences. Stephen works for Net-A-Porter … Read More →

The post EuroSTAR – Star – Stephen Janaway appeared first on The Social Tester.

Categories: Blogs

ZFS on Linux ‘insufficient replicas’ panic

Chris Read - Wed, 12/17/2014 - 06:55

I run a lovely little HP N54L MicroServer at home to keep all my important bits. It’s been a faithful companion for many years across two continents. I’m running Ubuntu LTS on it, booting off a small SSD but keeping years worth of backups across two ZFS mirrors.

I discovered this evening that the little PCIe card I was using for my boot drive had failed. There’s a spare SATA port on the motherboard I never bothered using (it’s only SATA II, the SSD is SATA III), so I just pulled out the old card and booted off the onboard controller. Imagine the horror when I got the following response to my zpool status after the first boot:

root@dumpy:~# zpool status
  pool: first
 state: UNAVAIL
status: One or more devices could not be used because the label is missing
	or invalid.  There are insufficient replicas for the pool to continue
	functioning.
action: Destroy and re-create the pool from
	a backup source.
   see: http://zfsonlinux.org/msg/ZFS-8000-5E
  scan: none requested
config:

	NAME        STATE     READ WRITE CKSUM
	first       UNAVAIL      0     0     0  insufficient replicas
	  mirror-0  UNAVAIL      0     0     0  insufficient replicas
	    sda     UNAVAIL      0     0     0
	    sdb     FAULTED      0     0     0  corrupted data

  pool: second
 state: UNAVAIL
status: One or more devices could not be used because the label is missing
	or invalid.  There are insufficient replicas for the pool to continue
	functioning.
action: Destroy and re-create the pool from
	a backup source.
   see: http://zfsonlinux.org/msg/ZFS-8000-5E
  scan: none requested
config:

	NAME        STATE     READ WRITE CKSUM
	second      UNAVAIL      0     0     0  insufficient replicas
	  mirror-0  UNAVAIL      0     0     0  insufficient replicas
	    sdc     FAULTED      0     0     0  corrupted data
	    sdd     FAULTED      0     0     0  corrupted data

The whole point of having two separate mirrors was so that bad things like this would need something more serious than an unconnected controller failure corrupting them!

After taking a deep breath I had a look at the data again, and at the rest of my system. /dev/sda was now my boot SSD, but ZFS thought it was part of an array. Looks like using the on board port had shuffled drive names around. This data is stored in /etc/zfs/zpool.cache to speed up mounting on boot. Moving drives around had invalidated this information.

So, I did the following:

  • rm /etc/zfs/zpool.cache
  • Rebooted the machine (unloading the ZFS modules should also theoretically work)
  • zpool import <my pools>

And all my bits were back in the correct order!

root@dumpy:~# zpool status
  pool: first
 state: ONLINE
  scan: scrub repaired 0 in 3h27m with 0 errors on Sun Dec 14 03:27:14 2014
config:

	NAME                                          STATE     READ WRITE CKSUM
	first                                         ONLINE       0     0     0
	  mirror-0                                    ONLINE       0     0     0
	    ata-WDC_WD20EARX-00PASB0_WD-WMAZA6447754  ONLINE       0     0     0
	    ata-WDC_WD20EARX-00PASB0_WD-WMAZA6448154  ONLINE       0     0     0

errors: No known data errors

  pool: second
 state: ONLINE
  scan: scrub repaired 0 in 9h42m with 0 errors on Sun Dec 14 09:42:32 2014
config:

	NAME                                          STATE     READ WRITE CKSUM
	second                                        ONLINE       0     0     0
	  mirror-0                                    ONLINE       0     0     0
	    ata-WDC_WD20EARS-00J2GB0_WD-WCAYY0231617  ONLINE       0     0     0
	    ata-WDC_WD20EARS-00J2GB0_WD-WCAYY0221030  ONLINE       0     0     0

errors: No known data errors

I initially created the system with an early 0.6.0 release candidate of ZFS on Linux, which is why it was doing something as silly as identifying drives by /dev/sd? in the first place. Now I’m running on the 0.6.3 release I’m happy to see it using drive serial numbers instead.

Hopefully this information will save someone from blowing away a valid mirror and having to restore from backups…


Categories: Blogs

Getting Started Testing in Python

Testing TV - Tue, 12/16/2014 - 20:34
If you’ve never written tests before, you probably know you *should*, but view the whole process as a bureaucratic paperwork nightmare to check off on your ready-to-ship checklist. This is the wrong way to approach testing. Tests are a solution to a problem that is important to you: does my code work? This presentation shows […]
Categories: Blogs