As you might already know I am currently authoring a book called “A C# Smorgasbord”. The work on the book is going great and will, if everything goes as planned, be released later this summer (mid/late July).
However, before the book goes off to print, I want to know what trim size you guys prefer, meaning the size of a page(the book when it’s closed). The poll below lists the standard trim sizes available.
So please cast your vote to make this book perfect! Here’s a PDF that compares a lot of different trim sizes.
I am going to step out of my comfort zone a bit and write a post that touches the surface of C++ in Windows 8. Let us start off by looking at an image of what the new WinRT(Windows Runtime) look like:
As you can see, there are a lot of powerful ways to create both metro style and desktop applications. Notice that in Metro style applications, XAML is connected to both C++ and C#/VB.
During my years of .NET development, the reason for using C# or VB has been; RAD(Rapid Application Development). In a world filled with consultants where the customers only see the end result, it can often be hard to convince that putting down 200% more time using C++ is a great idea.
Because let’s face it, it takes a lot more time creating a desktop application in C++ using MFC than what it would to use C# and XAML. Before someone throws a stick at me I have to say that it of course depends on what kind of application you are creating.
The downside from using a managed programming language is that it tends to be a bit slower; in some cases this is critical. Most customers do not care if they have to wait a couple of extra nano-seconds for a control to render.
What does this have to do with Windows 8 and the Windows Runtime?
I really got a nice tingly feeling in my stomach when I first saw that you could use XAML with C++ in Windows 8. But that is not the best part, the best part is that it is fully native!
This means that the designers can make the interface in expression blend and we can dig down into C++ on the backend.
Let us have a look at this! You will need to have Windows 8 Consumer Preview and Visual Studio 11 beta installed (or later) in order follow these examples.
Start off by creating a new blank Windows Metro style application, this is found under “Other languages -> Visual C++”:
When the project is created, you will see some files that have been generated, these are pretty similar to what we are used to see in a normal XAML application in .NET:
Open up the file “BlankPage.xaml”, this will bring you into the designer view of the XAML file. Add a TextBlock to the page:
As you can see in the preview, it shows a tablet with the current view inside it. Remember that we are working with a Metro application, the idea is that you have a metro application in fullscreen or pinned to one of the sides on your screen.
By only adding the TextBlock, this is the XAML that we have now:
If we now navigate to the file “BlankPage.xaml.cpp”, this is where we can actually access the TextBlock. When you compile your solution, the XAML will also be compiled to C++, just like the XAML in a normal .NET application is compiled.
However, to access the TextBlock and set the text of it to the current date, what do we write?
The TextBlock is actually a TextBlock^, the “^” is called a “hat”. Think of this as a pointer, but a pointer that you do not have to worry about disposing.
This means that you do not have to do delete on the object yourself, because it will be automatically removed once the context of it has been exited.
So in order to set the value of the TextBlock we do:
MyTextBlock->Text ="Hello World!";
We can test-run this before we display the current time. First, let’s select to run it in a simulator like this:
This will bring up a tablet emulator that mirrors your system:
Now let’s take a look at how to get the current date there instead of that “Hello World!” text. In WinRT you can access an object called Calendar which you can use to get the date and time.
In order to get a pointer/hat, you need to modify the instantiation a tiny bit. Instead of just writing this:
This lets the compiler know that this will in fact be a hat/”managed pointer”. Something that I have missed a lot when not working in C# is the keyword var and this has finally come to C++ with the more appropriate name auto.
So in order to get a calendar object, calibrate it to the current time and then set the text to the current date we can simple do it like this:
auto calendar =refnew Windows::Globalization::Calendar();
This has been a short post about how to create your first C++ Metro style application in Windows 8 and I hope you enjoyed the read, if you have any questions do not hesitate to leave a comment, tweet or e-mail.
If you head over to the CodePlex page called ASP.NET Web Stack. You’re going to find a lot of useful information here regarding the code base. Since CodePlex now supports git, it’s Very easy for a lot of us to integrate with the development process and contribute patches, yes, you heard me right: contributions by anyone!
I’m using SmartGit in Windows and as you can see by the following screenshot, you’ve got a lot of nice information about the commits, branches, merges and fixes! Most important of all, it’s alive, there are a lot of contributions made the last couple of days and I really think this will increase the quality of what is already high quality.
When you’ve got all the code fetched from the repository, all you need to do is fetching all the NuGet packages. They’ve made this process pretty simple, all you need to do is open up a command prompt, go to the folder where your local repository is and write the following:
build RestorePackages
build
Now you’re ready to contribute to ASP.NET MVC/Web API/Web Pages! There are multiple ways to how you can contribute, head over to CodePlex and read more about it.
Watch the first video trailer for my upcoming book A C# Smorgasbord.
The work on the book is going great, almost 50% of the work is done and the deadline is approaching, stay tuned for more information, trailers and competitions to win a free copy!
Tweet me if you’ve got any questions or if there are any problems with the stream!
Update 2012-03-25
Thanks to everyone who watched my live stream from Webbdagarna in Stockholm. I’m planning to assemble all the videos from the stream and put them on youtube, I can’t promise that it’s going to work due to youtube/justin.tv limitations.
In the new version of ASP.NET you can use something called ASP.NET Web API. This allows you to expose your data in many different formats, such as XML or JSON. The idea is to provide a REST API where you use HTTP for real. Meaning that you use GET/POST/PUT/DELETE. These work pretty straight forward:
GET – Retrieve all or one item
POST – Add an item
PUT – Update an item
DELETE – Remove an item
As mentioned above, you can retrieve data in different formats such as XML or JSON. The type of data that will be in the response is determened by the HTTP header Accept. By default(built-in) you can use the two following accept headers:
application/json
applicaiton/xml
In order to try this out, I will be using curl to make the web requests, because this will allow me to specify the headers manually.
Then you will be presented with what kind of ASP.NET MVC 4 project that you want to create, select to create a new Web API project:
When the project is created, you’ll have some new things that you haven’t seen before in a normal ASP.NET MVC application. It does look a lot like a normal ASP.NET MVC applications, but with some minor add-ons.
The first thing that we are presented with is the ValuesController and this controller inherits from the ApiController. The ApiController is what you will inherit from when you are creating API specific controllers. It will help you map the HTTP requests GET/POST/PUT/DELETE to the methods with the corresponding names.
The second thing that is added is inside the global.asax.cs, a new route to specify where we retrieve the API specific controllers:
routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults:new{ id = RouteParameter.Optional} );
This just help us distinguish between our API calls and non-API calls. If you just start the web application and navigate to /api/values/ you will see a list like this:
If we open this in Internet Explorer 10 instead, it will request a JSON result instead of XML and if we open that up in notepad, it looks like this:
We can verify that this works by testing it out with curl.
Get JSON using curl
curl -H "Accept: application/json" -H "Content-Type: application/json" -X GET "http://localhost:13938/api/values"
JSON Result:
["value1","value2"]
Get XML using curl
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET "http://localhost:13938/api/values"
This is good and all, but we might want to be able to specify what kind of format that we expect with a query string. To do this, we can register a formatter for a certain query string mapping. Go back to global.asax.cs and add the following at the end of Application_Start:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add( new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add( new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
This will allow you to add ?type=json or ?type=xml to request a certain output format:
If you want to retrieve a specific item, you can simply do /api/values/1.
This has been a short introduction to get you started with the ASP.NET Web API. If you found this interesting, stay tuned for the live stream that I will do from Webbdagarna (if the Internet connection allows) and also stay tuned for upcoming posts where we hook up with Entity Framework to make this API more alive.
There’s a Swedish event in Stockholm 22-23 March called Webbdagarna (translation: web days). The focus of the event is to talk about e-commerce, social media, mobile development and much more. It’s not so much programming focus, in fact the only coding part of the event is what me and my colleuge will do.
The idea is that we are going to sit on stage for 2 days right next to the speakers to create a very cool mobile app, live! My main focus on this will be to create the API for the application, I will of course use the latest technology for this:
Our focus is to deliver a proof of concept and not a finished product, but since the audience will be “social media experts”, “seo experts” and whatnot, they won’t be interested in seeing the code. But I know that many of you guys would like to see this so I will be live streaming from the event on JustinTV (if the organizers and bandwidth allows for it).
I will be at the event to reprecent Star Republic which is where I work as a Software Engineer. We put together a pretty fun YouTube video presentation about what I will do there, I talk Swedish in it. So for you guys that don’t talk Swedish it might be like listening to the Swedish Chef(muppets)!
Video translation: I am Filip Ekberg and I work as a Software Engineer at Star Republic, follow us on this rock-n-roll journey, where we build Swedens coolest app, live on stage at Webbdagarna in Stockholm 22-23 March!
Don’t forget to follow me on twitter, this is where I will announce and communicate with everyone at the event (and outside the event).
Yesterday on February 29, Visual Studio 11 Beta was released and with it comes a beta version of .NET 4.5. You can download Visual Studio 11 Ultimate Beta from Microsofts website.
There has been some changes to the UI that has gotten a lot of attention the last couple of weeks, let’s take a closer look at what we can expect from the Visual Studio 11 Beta.
The first thing that we are faced with is the installer, all the installers for Visual Studio has in my opinion looked much better than any other installers and the installer for Visual Studio 11 Beta is the winner among them. It got a very nice look and feel over it and it’s clear they’ve put some effort into the smallest details.
If you are installing Visual Studio 11 Beta with the Web Installer, it will take some time. Once the installation has finished fire up Visual Studio!
When the first screenshots of the Beta was released, many of the Visual Studio users were surprised of the monochrome interface. It’s a quite drastic change compared to what we are used to in Visual Studio. Up until Visual Studio 2010 we’ve been comfortable with a lot of colors and nice icons.
Now, the workspace is in more focus.
The menus, icons, tabs and everything else in the interface just feels right. When you spend 8+ hours per day in Visual Studio, you want something that is easy on the eyes and that is exactly what this is.
Even the icons in the menu have a monochrome approach.
Let us take a look at how it looks and feels to write code, create a new console application.
When the project is created and you’ve got the Program.cs opened add some content to it to get a feeling of the studio.
As you can see the code is in focus, nothing else is stealing your attention. The code coloring is what we are used to and the key mapping as well. Notice the Solution Explorer, there’s an expand button for each file that will let you view classes, methods and properties in the file.
You attention is automatically going towards what is important, the code. Let’s take a look at a last screenshot where it is more clear that the code, comments and breakpoints get your attention.
After you have tried Visual Studio 11, leave a comment and let me know what you think of it!
I put together a short video that shows how you can create your own NuGet Package. This requires that you download the NuGet Package Explorer. Be sure to check out the NuGet documentation, it is very good.
In previous articles we’ve looked at how to increase code quality by either introducing test drive development for new features or using inversion of control. There are of course many other aspects that come into play when you want to reach high-quality code and this article is going to introduce you to mocking that will help you along the way.
You might have come across the word “mock” before, when for instance a UI designer for a Windows Phone application on your team puts together a picture of how the application might look when it is finished: Where do the buttons go? What text might be displayed when the button is pressed?
The word “mock” means to fake something, which is exactly what we want to do here; we want to fake the layout to give the customer an idea of how the application will look or how it will behave. On the rare occasions that I need to do UI mocks I use a tool called Balsamiq and the mockups for a phone application can end up looking as simple as this:
There are techniques for mocking things in the real world as well, an example of this is when you want to build a house, you might first want to see a small scale model before you decide to go with it; this is mocking!
How does this apply to programming?
As we’ve concluded mocking is about faking either a thing or a behavior and in our code it is of course a behavior that we want to fake/impersonate. In the article about IoC and DI I talked about breaking things apart from each other by using interfaces, this is going to help us out a lot with the mocking as well.
Let us assume that we have a system that handles payments and our different payment providers use a shared interface called IPaymentProvider. Then we have something that handles the processing of all the payments through the different payment providers let us assume that this class is called Payment and the constructor of Payment takes an IPaymentProvider.
This class has only one purpose and it is to withdraw money from the customers account. This class resides in a Test project using MS Test. Although that it has one purpose only there are some parameters that will affect the result of the payment execution. In our scenario we the IPaymentProvider will look like this:
The actual execution of a purchase will require us to first Reserve the amount of money we want to withdraw and if that is possible, we can execute the payment and finalize it. This means that our Execute method will end up looking something like this
Even though we have the actual code in front of us, it is not important! What is important is that we just understand that we first need to reserve the amount and then if that succeeds we execute the payment which finalizes the process.
We’ve looked almost all parts of the system, but where is the implementations of the IPaymentProvider?
Let’s assume we don’t have it! Even though we don’t have access to the implementation at this time (maybe we haven’t made it quite yet, we might not even know what payment providers we are implementing the system against) we still want to test the process of the Execute method, we want to assure that no exceptions are thrown and that based on a Reservation that did not go through, we don’t want it to go any further.
In the article on IoC and DI we talked about introducing fakes by creating “dumb” implementations that only did what we asked of them. This is indeed one way to go but let us take a look at another approach of this. Let’s look at a Mocking Framework!
There are a lot of mocking frameworks out there for .NET, here are two that are very good (among many many others):
But I’ve decided to go with Simple.Mocking. We can install this with NuGet, this is how the test-project I’ve created look like before I use NuGet to install Simple.Mocking:
Now fire up the nuget manager and write:
PM> Install-Package Simple.Mocking
And you should see something like this:
Now we’re ready to start mocking!
There are a couple of important parts in Simple.Mocking that we’re going to cover now, the first one is: How do we fake an instance of our IPaymentProvider?
Start off by adding a reference to the framework by adding this to the top of the file:
usingSimple.Mocking;
Now, there’s a class we can access called Mock here we’ve got two different methods that will let us do two things:
Mock.Interface will let us fake an implementation of our interface as if we had a real implementation.
Mock.Delegate will let us fake a delegate, we won’t be looking in to this anything in this article.
Of these two we will only concentrate on Mock.Interface. You easily fake/mock an implementation by doing this:
var provider = Mock.Interface<IPaymentProvider>();
Is this it? No, it’s not! We’ve still got a path to wander before we’ve reached our final destination. If we check what methods we have on the variable provider this is what we got:
So what happens if we run the following code:
var provider = Mock.Interface<IPaymentProvider>();
provider.Execute(100);
It does look valid, doesn’t it? The problem here is that the method Execute has not idea of how it should behave so it will raise an exception. Because it expects us to define a behavior for it before we proceed. This brings us to the next interesting object that we are going to take a look at that comes with Simple.Mocking; Expect!
Almost all the methods on the Expect type takes an expression of type Action or Func<T>, at least the ones we are interested in at the moment. These are the most commonly used methods:
Expect.MethodCall
Expect.PropertyGet
Expect.PropertySet
Expect.AnyInvocationOn
From their names you should be able to figure out what they do, but we’re going to look closer at Expect.MethodCall now. Expect.MethodCall is used to define an expected call to a method on a given type. Take a look at this example:
var provider = Mock.Interface<IPaymentProvider>();
Expect.MethodCall(()=> provider.Reserve(10));
This fakes an implementation of the interface IPaymentProvider and says that it expects us to call provider.Reserve with the amount 10. If we were to invoke it with another value, let’s say 0 like this:
var provider = Mock.Interface<IPaymentProvider>();
Expect.MethodCall(()=> provider.Reserve(10));
provider.Reserve(0);
We would get an exception because it assumes that we are about to call it with the amount 10:
So if we change that to 10, it should be all good, but it’s not always that you want to hard-code a constant value like that, so what you can use is a helper class called Any<T> which will let us define any type as an in-parameter or as a return value. In order to say that we are expecting a parameter type of decimal we do this:
Any<decimal>
But that’s not enough, this only defines the type, we need to use the property Value in order to use the actual value that we will use later when we call this method:
This means that the first time Reserve is called, the value of the decimal sent to the fake method will be 0 and the second time it will be 25. Let’s make it a little interesting, as you might have noticed, you can define a lot of different Expectations for the same method, the parameter values are what defines what mocked invocation to use.
There’s a method called Matching on the Value parameter that you can use to distinguish between different values. For instance, you might want to make a very specific test where it fails when the amount is less than 10 and succeeds when the value is above. That could look something like this:
This mocked method call will be used when we call Reserve with an amount greater than 10. But we’re still not returning either true nor false, that’s the next part! This is probably the easiest part so far, right before the semi-colon, just add .Returns(true); and you’re all set!
So this is what the result of this snippet looks like:
And if we want to add another expectation that returns false if it is less or equal to 10, we can do that as well, the entire code will look something like this:
var provider = Mock.Interface<IPaymentProvider>();
The first reservation will return false, because amount is less than 10 but the second one will use the first faked method call and return true. Now let’s step back a bit and take a look at our original problem, we want to make sure that we can process a payment and it should fail when the reservation fails and succeed when the reservation succeeds. So let’s remove all the fuss around that and we should be left with a pretty simple looking snippet like this:
var provider = Mock.Interface<IPaymentProvider>();
Expect.MethodCall(()=> provider.Reserve(Any<decimal>.Value)).Returns(true);
Now the next steps are pretty straight forward, we need to do the following:
Create an expectation for the method call Execute
Create an instance of the Payment type and pass it the mocked interface
Execute a payment process!
Validate the results by using tests
The next expected method call is the Execute method on the payment provider, this will look almost identical to the Reserve method in this case:
The last two things we need to do now is to create an instance of our payment processor and pass it the interface:
var provider = Mock.Interface<IPaymentProvider>();
Expect.MethodCall(()=> provider.Reserve(Any<decimal>.Value)).Returns(true);
Expect.MethodCall(()=> provider.Execute(Any<decimal>.Value)).Returns(true);
var payment =new Payment(provider);
payment.Execute(200);
This should compile fine and when you run the test it shouldn’t complain anything at all. Now we’ve got everything set up, we need to test the behavior of payment processor and the two scenarios are:
If reservation fails, execute should never be invoked
If reservation succeeds, execute should be invoked and the method should return true
There are a couple of more scenarios such as, in the rare occasion if the reservation succeeds but the execution does not, does it throw a proper exception and roll back? But I’ll leave these special scenarios for you to play with.
Let’s continue looking at the first test, we’ve already (partially) finished it, but I’d like to remove the expectation for a method call, since I do not actually expect a method call at all, if the method is called, we will get an exception and this is correct.
So the first test where we check if the reservation fails looks like this:
[TestMethod] publicvoid CannotExecutePaymentWhenReservationFails() {
var provider = Mock.Interface<IPaymentProvider>();
Expect.MethodCall(()=> provider.Reserve(Any<decimal>.Value)).Returns(false);
var payment =new Payment(provider);
var result = payment.Execute(200);
Assert.IsFalse(result); }
If you run this test (ctrl + r + t) it should process fine and you should see a green icon indicating that the test finished without any errors:
Next up we need to create the test that verifies that everything processes OK, so we need to create a test that checks if Execute returns true if Reserves does too. All we need to do here is add the line of code that we removed before that tells Simple.Mocking that we are expecting a method call. The final test that we are going to make here will look like this if we add that expectation and change the reservation to return true:
var payment =new Payment(provider);
var result = payment.Execute(200);
Assert.IsTrue(result); }
If we run all the tests in the context (ctrl + r + a) it should gives us all green lights:
We could of course test if the Execution fails if both Reserve and Execute returns false, these are just similar test that you can add. As you can see Simple.Mocking is really powerful and of course you will need to test your real implementations, but before you test your real implementations of your payment providers, you will want to know if your internal stuff is working.
There are actually systems that charge you a certain amount of money for each API call, these can get quite expensive if your build server runs through all tests all night. I hope you’ve seen how powerful Simple.Mocking is and how it can help you test faster and test more. I read once that everything should be simplified to an interface, this would mean that anything can be mocked and anything can be tested in one way or another.
So in short what we’ve accomplished is that you now have a fake implementation of your interface that will allow you to test other things in your system that depends on certain values or methods being called on that implementation. Here is the entire code that we’ve been looking over in this article: