Why I Hate Unit Testing
So you went to work for the cool company that wooed you with promises of cutting edge technologies and techniques. In the interview, they told you that they are agile and unit test everything. You may or may not have been in an agile environment before, but the important thing you are enthusiastic about joining a team that truly gets software development. You tested on your previous job, even using JustMock to write better tests. You promise you can be agile yourself and quickly adopt their practices. Youâre immediately hired.
Many of you have been there⊠maybe youâre there right now.
It takes a few days to receive your workstation, and you find most of the development software isnât set up. A coworker gives you the instructions, and by the end of the day you find yourself still struggling to connect to the version control server.
The next day, you ask your manager about your problem. It turns out that the person in charge of the version control and build servers left a few months back; youâre the replacement. Further inquiries lead to a startling truth: no one has administrative access.
Remembering that you replaced the version control administrator, you find the user name and password taped under your desk!
You pull down the source code, and it quickly becomes apparent that youâre lost. Itâs a large project, and the unit tests are completely unreadable, seemingly without logic or organization. âSomething is better than nothing,â you think as you run all the tests.
It turns out that the vast majority of the tests are ignored; so much for that approach! You remove the Ignore attributes and try again. It seems to be taking a while, and itâs past time to go out. You decide to check on it in the morning even though itâs a Saturday.
When you arrive at work the next morning you see a fair number of cars. The company stressed having a healthy life/work balance, so you thought mandatory weekend work was rare. You make your way to the office and discover most of your team is here, frantically working.
âHey, itâs good for you to finally join us. There was a catastrophe last night. Our primary data storage was corrupted beyond recovery and the backups arenât restoring successfully. We suspect hackers.â
âHackers?â
âWell, most likely some teenagers who are good at breaking into computers. They manipulated a lot of data, and what we were able to track down is obviously fake. I mean, who names a child Little Teapot.â
That is rather suspicious. At your workstation, you found that the unit tests took an hour to run⊠good thing you left the night before. You search the code base for âLittle Teapotâ and find that itâs used in one of the tests you re-enabled.
You must hate unit testing⊠I know I do.
What to DoIf your employment continues, you may want to apply best practices to the unit test projects. Here are three important aspects you should consider to get started.
IsolationThe reason the finale in my story happened as it did was quite simply due to a test not being isolated. The tests that were ignored were writing test data to a database â the production database! To isolate the test, you need to remove dependencies. If one subsystem calls another, a stand-in object must take the place of the dependent subsystem in the system-under-test. When you run the test, if a substitute was expected to be making calls to a database or other services, it can pretend to do the call then return results that you want the system-under-test to receive.
This is easy to do with Telerik JustMock. I wrote about using JustMock to get you started in From Legacy to Dependency Injection.
Fast TestsSlow unit tests cause lost productivity. While youâre waiting on your tests to run, it may be difficult to get much else done. Worse still, you may find yourself reading blogs until well-after they finish running. Slow tests are typically caused by the lack of isolation, and the best way to handle this issue is to isolate any calls outside of the system.
Hard to Understand Test CodeThere are many patterns in development, and the Arrange-Act-Assert pattern (also referred to the AAA pattern) will help clean up your tests. These steps were described by William C. Wake in 2003.
- Arrange all necessary preconditions and inputs.
- Act on the object or method under test.
- Assert that the expected results have occurred.
When testing certain types of object, you may find that other patterns are more suitable. These are usually slight variations of the AAA pattern accounting for specific behaviors. Some mocking frameworks push you towards different pattern that ends up complicating the code. This is not the case with JustMock, which enables you to stick to the Arrange-Act-Assert pattern to maintain descriptive tests.
Donât Hate the Game, Hate the PlayerIf you have entered a company with poor unit testing practices, you will likely encounter other problems. Many practices and methodologies follow each other, and improper implementation for one item may encourage improper implementation in another. Many companies are successful with different practices in place, and none of this is one-size-fits-all. Steve Forte and Joel Semeniuk have a great presentation on this called The Agile Buffet Table. The most important thing is to regularly analyze your practices and determine if revision is necessary or if everything is okay. And please, realize itâs bad if no one has administrative access to your source control system!
Unit testing is great when done right, and itâs even good when done in a lax manner. However, itâs better to have no unit tests than terrible unit tests.
I hate unit testing done poorly.
About the author
Chris originally wrote this article to be tongue-in-cheek, but then he realized he had created a composite of many wonderful experiences. With well over a decade in software development, you are bound to see some things.
Upcoming Events : Speaking and Attending
Hello Everyone,
From time to time, I sit down and write out all the events that I will be speaking at or attending in hopes of connecting with other developers who may be attending these events. Iâll be at these events representing Telerik, so feel free to stop by the booth and ask say Hi. I have several different talks lined-up from Windows 8, Silverlight, OData and Windows Phone 7! Thatâs a lot of XAML if you ask me!
[Click below for more information including registration links]
All About XAML [May Meetup] â Alabama â May 15th, 2012.

Rocky Mountain Trifecta â Colorado - May 19th, 2012
I have two sessions at this event:
Get Started Buliding Metro Applications for Windows 8 using XAML/C#
10 Things a Silverlight Developer Should Know when Building A Metro Application
Windows Developer Camp â Georgia â May 23rd, 2012 [Sold Out]
The only speakers at this event are Microsoft employees, so I will only be attending. If you want to talk Telerik products then send me a tweet/email and we will link up.
TechEd â Florida â June 11th â 14th, 2012
I will not be speaking at this event, but will be in the Telerik booth showing off all of our XAML products.
CodeStock â Tennessee â June 15/16, 2012

I have two sessions at this event:
Getting your Feet Wet with OData in Silverlight 5 and WP7 Mango
Get Started Buliding Metro Applications for Windows 8 using XAML/C#
That Conference â Wisconsin â August 13th-15th 2012

I have one sessions at this event:
DevLink â Tennessee â August 29th-31st 2012

I have two sessions at this event:
Buliding Metro Applications for Windows 8 using XAML/C#
Wrap-upIf you are attending any of the events then please come up and introduce yourself. I really enjoy meeting new people and hopefully we can sit down and talk tech!
Quick Tips on Troubleshooting Your Web Pages â Element Inspector and Network Resources
When I first started out developing web pages back in the day there barely were any tools for development outside of the IDEs that were offered, which werenât too much to write home about anyways. While some might say that web pages that were manly cluttered with animated GIFs and content related to Warcraft 1 & 2 and Diablo 1 (tells you a lot about my child hood ;)) is not considered much of a web development project, I still say it is (or was) :D. Either way, you wrote your HTML, CSS (fairly new too) and JavaScript and hoped everything would turn out OK when you opened it in the browser. If something was off you went back to tweak it in your IDE (*cough* notepad *cough*) and refreshed while crossing your fingers that everything would be better this time around. Alerts were also frequently used as a way to see if a JavaScript function was accessed, and if a variable existed or what it had for a value.
Itâs not like this today though. Today is much, much different â in a fantastic way. In todayâs world we have more tools than we can shake a stick at for web development. Especially in the way of helping us developers in figuring out what exactly is happening to our web pages when they get rendered in our browser. Questions like âHow come this looks great in Chrome but slightly quirky in IE?â, âWhy is none of my JavaScript executing?â and âWhy is this page loading so slowly?â can now be answered within each of the major browsers thanks to the Developer Tools offered for each one.
Some of you might be saying âwell duh, Iâve been using this foreverâ but there is still a large group of the developer population that does not know about these tools. So for the sake of people either new to web development, or for those of you that just havenât heard of these tools, or only use a small portion of them, I wanted to write this quick blog post series. Iâll be covering some of the main features of these Developer Tools, as well as show how they look in the three major browsers that I like to use; Chrome, Firefox and IE. In the case of Firefox Iâm going to be using Firebug, an add-on that has been available for quite some time and was my introduction to browser dev tools. Firefox does have built-in dev tools now, but I still think Firebug offers more features and is the preferred tools to use right now.
Enough of my rambling on here, letâs get to it! Today Iâll be covering the Element Inspection tools, as well as the Resources tools.
Element InspectionEver seen a button on a page that looked ridiculously awesome and wondered why it looks so good? Maybe youâre just curious why a certain element is now in the upper right-hand corner (has happened way too many times for me), or maybe you just want to see how the page youâre currently on is laid out.
Well thanks to the element inspector all these mysteries are solved! How often do you get to hear that? Well, the element inspector often (as in, most major browsers have this ability) provides you with a couple of useful things.
First of all, when you inspect an element you usually get to see both where it is currently located on the page (each browser does this a little differently) as well as where it is in the DOM. Additionally, and this is an extremely useful feature, you get to see the CSS that affects the particular element. You can see everything from what styles are supposed to get applied, which ones get overridden, and the final styles applied. You can usually also see which CSS file (and what line number!) is responsible for that particular rule as well. Super awesome in scenarios where you would normally just stare at the screen tearing your hair out wondering why everything looks so wrong.
For this particular demo I just have a very quick sample HTML page, as I just want to cover the basics.
<html> <head> <script src="Scripts/jquery-1.7.2.min.js"></script> <link href="Styles/Styles.css" rel="stylesheet" /> <title>Quick Dev Tools Sample</title> <style> p { color: #FFFFFF; } </style> </head> <body> <p id="sampleParagraph"> This is a sample paragraph </p> </body> </html>
As you can see I also have a separate CSS file called Styles.css, which at this moment only looks like this:
body { background-color: #FFFFFF; } p { background-color: #EFB087; font-family: Verdana; width: 100px; }
Very simple, but illustrates the points I want to make. Just from looking at the code above you can see a few things:
- We have a paragraph which should have a black (#000000 in HEX) font
- The font in the paragraph element should be Verdana (no backup)
- The background of the paragraph should be a kind of orange-y color (Iâm awful with color names)
- The background of the body element should be #FFFFFF, or in an English term â white :)
Letâs take a peek at how this looks in our browsers various developer tools available to us.
ChromeThere are a couple of ways you can work with the element inspector tool within Chrome. The easiest way to make sure that you are looking at the specific element you want is to right-click on it in your browser and select âInspect Elementâ from the context menu that appears.
Once you have done this the Chrome Dev Tools will open up, with your particular element highlighted within the DOM.
Speaking of the DOM, you can actually navigate through the DOM and highlight elements that way too. This can be done by just opening the Chrome Dev Tools (CTRL + SHIFT + I, or F12) and going to the Elements tab. Once here youâll see the same view as before, only the body element will be highlighted. If you hover over, or click, on any HTML element in here it will get highlighted as well.
As that screenshot shows you, our element is actually highlighted on our page, and we even get some additional information about it. We know that itâs a âpâ element, with the ID sampleParagraph (â#â refers to the ID) and that itâs 100px by 54px in size.
You also might have noticed the âStylesâ and âComputed Stylesâ in the second image there. Well, this area allows us to easily wee what styles end up getting applied to the element. This means CSS rules that affect the element, even if they have ended up over-writing other styles. Computed Style shows you the end result, and where each style comes from, as can be seen here:
You might notice that each one of those documents (.css and .html) are actually links and will open the CSS file in the Chrome Dev tools to that specific line in the CSS or HTML file so that you can dive in to the file in charge of the style. This gives you a chance to see where the particular style you defined exists, which becomes very handy when you are scratching your head wondering why that element is not getting styled properly.
FirefoxAs I mentioned previously, Firefox has a very similar view brought to you by the add-on Firebug. So letâs go through the same things as I did with Chrome above.
First letâs right-click on my element and go to âInspect Element with Firebugâ. You might notice that there is an âInspect Elementâ option as well. This is for the internal developer tools from Firefox that I mentioned in the beginning. Right now Iâll focus on Firebug, but you never know what kind of blog posts the future holds!
Now we see that the element is highlighted in our DOM explorer.
You get the same view that I mentioned above with Chrome as well, where I can highlight the element in the DOM explorer and have it highlighted in the actual web page as well. So far, nothing really too different.
One thing that you see immediately though is the style tab over on the right-hand side. This is where you notice some differences. For example, the first view we see just shows us the rule applied to this particular element. This was available in Chrome as well, but for the sake of comparison letâs go over to the Computed tab:
Not exactly what we saw in Chrome. The nice thing it does is split up all of the styles according to their relevant groups. So Text, Background, Box Model etc., but there is no way to see where exactly these come from. So we have to look through the styles tab to see where everything is coming from, which isnât a bad thing I just love having those kinds of lines drawn for me.
IE9IE9 has some pretty spiffy tools for web development, which hasnât always been its strong suit in previous iterations. The great thing is that you can also test for the various modes that have existed within IE (quirks mode etc.) and go back to IE7 for testing â all in the same browser.
While there isnât a context menu item to inspect the element we can still very easily get access to an element in order to inspect it. If we open our page in IE9 and press F12 we will see the Developer Tools appear. Once weâve done this we just need to find the arrow icon under the HTML tab, which starts the element inspection:
Once weâve clicked on an element weâre granted a very similar view to what weâve seen before in the other browsers.
We have the same ability to see all of the styles, but one thing that is different is instead of âComputedâ styles we now have âTrace Stylesâ.
This is just the same as in the other browsers, however now we have something that is closer to what we had in Chrome. Unfortunately we cannot get the exact line number, but if we click on a particular file name we can very easily see where in the source file these styles are located. This also allows for very quick tests to see what happens when you remove the styles, which in both other browsers can only be done in the Style tab.
NetworkIâm sure youâve run in to scenarios where you swear that you added an image to a page, or you realize that thereâs no CSS being applied to your page and youâre wondering why. Often times these scenarios are derived from the fact that there was an issue downloading the particular resource. Whether it be an image, a CSS file, or maybe even the next page our clients are navigating to, it can always happen. Spelling mistakes, or moved resources â the list goes on.
Well, what if I told you that you can easily see exactly what kind traffic is occurring on a particular web page, and see exactly what files are attempted to, or successfully, downloaded? Hard to believe it? Let me introduce you to the Network tab of these browser dev tools â itâll rock your world!
For the sake of keeping things simple Iâll be using the same HTML page as with the element inspector.
ChromeIn Chrome it is very easy to find this Network tab. Just open up the Chrome Dev Tools (CTRL+SHIFT+i) and select the âNetwork tab".
Here we can see quite a bit of information, although since my page is fairly simple there might not be a ton of items to inspect. Nevertheless, we can see that I attempted to download index.html, jquery-1.7.2.min.js and Styles.css, all using the GET method. These all succeeded, and I can even see what initiated this action â pretty nifty! Chrome also gives us the ability to see how long it took to download the file, as well as where in the overall page load the download took place.
If we had more happening on this page it would all go through the Network tab like this. Ajax requests would be found here for example. Of course, if we were unable to download a resource it would gladly tell us and say specifically what kind of error (404, 500 etc.) that caused the issue. This is extremely useful when you see odd behavior on a page. You never know what you mightâve missed to download, or if there are any errors in your way.
If youâd like to you can also click on each resource and see the Headers and Response messages for each of these requests. There is also a Preview (for our HTML file this would display the entire HTML in plain text) and a Timing tab which gives us insight as to how long it took for this entire request to get back to us.
FirefoxFirefox has a very similar view as what we found in Chrome. If I open up Firebug and click on the âNetâ tab on my sample page I am greeted by this:
As we can see we get a similar view to what we had in Chrome. While it doesnât tell us what kind of file this is, it still displays all of the files that downloaded. Additionally we get the status, field which would inform us if anything went wrong. You can also expand each item to get a more detailed view of the response, similarly to what we had in Chrome as well
IE isnât far too different either actually and having this as a standard feature is always a good touch. There is an interesting approach that IE9 takes, which is that you can selectively choose when to start and end the capturing of this data. More on this in a second! :)
If we open up the IE9 Dev Tools (F12) and select the âNetworkâ tab this gets displayed:
So, nothing happens by itself here. In Chrome and Firefox we would just refresh the page if we saw nothing under this tab and automatically things would capture. However, this could also leave us with a ton of extra information that weâre not interested in. What if we just want to look at what happens when we click that one button? IE9 lets us define exactly when we start the capture, and when to end it.
If we hit âStart capturingâ and refresh the page I should get something similar to the other two browsers.
Bingo! We get to see the method, satus/result as well as what type of request we are dealing with. Additionally all of the timing information is there as well. One neat thing is that we also get to see what particular element was in charge of initiating the request, even if it was a refresh.
For some more detailed information, which would contain all of the more nitty gritty items that we saw in Chrome and FF all we need to do is press âGo to detailed viewâ and voila â more information than you can shake a stick at!
Oh, We Are Just Getting StartedSo thatâs a quick overview of the Element Inspector and the Network tab of Chrome 18 , Firefox 12 and IE9. This wasnât necessarily a deep dive into any one tool or any one browser, but more of a quick overview of whatâs available. Hopefully I inspired those of you whom havenât used these tools before, or maybe I covered something you havenât been using! Keep in mind that thereâs more to come later as I dive in to the more JavaScript heavy items in the next blog post! :D
About the authorCarl Bergenhem is an Enterprise Solutions Consultant at Telerik specializing in the ASP.NET AJAX and ASP.NET MVC products. He has always been interested in web development and has played around with various web technologies since he was a child. In his free time Carl enjoys soccer, running and playing his guitar.
What makes a marketer of a toolset for building Windows Phone apps happy?
It is news like this one: two of the four apps that won the big prize of the 30 to Launch competition are built with RadControls for Windows Phone - the product our team is building with so much care.
And the apps are:
Play the hunt â built by Eshy Media
Social Mints â built by Techark. Social Mints was also the winner of Core77's FastTrack to the Mobile App International Design Award and was featured at Mobile World Congress 2012.
âWe are extremely excited about this win as there were more than 130 apps submitted for the contest,â said Pratik Kothari from Techark.
And So Am I. Because our customers appsâ success is our teamâs ultimate reward.
Experimental build with integrated style profiler preview
Back in November, we released a standalone build of Opera Dragonfly's style profiler. In today's release on the experimental path, the profiler is now integrated next to the other Opera Dragonfly tabs and tools.
When switching to the Profiler tab, Opera Dragonfly will ask to reload the page. This is necessary in order to get the best possible profiling data, without any overhead from other debugging services that Opera Dragonfly usually runs. [1]
Please note that this is the same version of the profiler that was previously released in the standalone version, so there aren't any new pieces of functionality. However, we're already working on more features, such as the ability to zoom into the timeline.
This release also includes the inspection of return values that was mentioned on the blog recently.
â When Opera Dragonfly is opened, it starts a few services for debugging purposes. One of these is the ECMAScript debugger service, which disables JIT. By disabling this service, the profiler will give much more accurate data, since JIT will remain enabled.
XAMLflix Video Tutorial: RadCalculator for Silverlight and WPF
Hello everyone and welcome back to XAMLflix with RadCalculator for Silverlight and WPF. I hope you have been enjoying the series as last week we took a look at RadPropertyGrid and RadComboBox. This week we will be taking a look at RadCalculator for Silverlight and WPF.
What is XAMLflix you might ask? Well, it is Telerikâs way of teaching you how to use both new and existing controls from Telerikâs XAML suite. Each and every Tuesday and Thursday, we will provide a fresh batch of videos and sample projects highlighting a different control. Since our Silverlight and WPF share a common codebase and API, you only have to learn how to use these controls once! You can simply copy and paste the code between frameworks.
Be sure to check out www.telerik.com/xamlflix for all the videos!
RadCalculator
RadCalculator for Silverlight/WPF has a simple easy-to-use interface enabling the end user to perform all basic calculations such as addition, subtraction, multiplication, division as well as some more complicated ones â reciprocal, square root, negate. The operations can be executed either by clicking the calculator buttons, or by using your keyboard. You can also use the numeric keypad to type numbers and operators by pressing Num Lock. Furthermore, all the Memory and Clear features are exposed as well.
- Getting Started with RadCalculator â In this video, we will see how easy it is to get started with RadCalculator. We will begin by adding RadCalculator to a new Silverlight Application and explore its features. We will wrap up the video by learning how to add the RadCalculatorPicker to you Silverlight project as well. (Download the Project)
- Customize RadCalculator by Creating Custom Operations â In this video, we will learn how RadCalculator can be easily extended by defining custom operations that are needed in specific scenarios. We will add four additional buttons and define the custom operations in code. (Download the Project)
- Use RadCalculatorPicker as an editing element in RadGridView â In this video, we are going to show that RadCalculatorPicker can be embedded as an editing element for a column in RadGridView. Your users will be able to perform calculations inside RadGridView with ease! (Download the Project)
Wrap-Up
Hopefully youâve seen here just how quickly and easily you can add RadCalculator in your next line-of-business application. And as a reminder, this is only one of controls offered in the Silverlight/WPF suite. So, feel free to download your own copy of the Silverlight and WPF control suite right now.
Also, before you go, I need your help. Telerik is driven by customer feedback. This is where I need you to tell me what you want to see in the future. Whether it is new controls, additional features or content based off of existing controls, then just drop me a comment in this post or send me a tweet. I look forward to hearing from you shortly!
@mbcrump
Working with files in JavaScript, Part 2: FileReader
In my previous post, I introduced using files in JavaScript, focusing specifically on how to get access to File objects. These objects contain file metadata obtained only when the user opts to either upload a file or drags and drops a file onto the web page. Once you have files, however, the next step is to read data from them.
The FileReader typeThe FileReader type has a single job: to read data from a file and store it in a JavaScript variable. The API is intentionally designed to be similar to XMLHttpRequest since both are loading data from an external (outside of the browser) resource. The read is done asynchronously so as not to block the browser.
There are several formats that a FileReader can create to represent the file data, and the format must be requested when asking the file to be read. Reading is done through calling one of these methods:
- readAsText() – returns the file contents as plain text
- readAsBinaryString() – returns the file contents as a string of encoded binary data (deprecated – use readAsArrayBuffer() instead)
- readAsArrayBuffer() – returns the file contents as an ArrayBuffer (good for binary data such as images)
- readAsDataURL() – returns the file contents as a data URL
Each of these methods initiates a file read similar to the XHR object’s send() method initiating an HTTP request. As such, you must listen for the load event before starting to read. The result of the read is always represented by event.target.result. For example:
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
This example simply reads the contents of a file and outputs it in plain text to the console. The onload handler is called when the file is successfully read whereas the onerror handler is called if the file wasn’t read for some reason. The FileReader instance is available inside of the event handler via event.target and it’s recommended to use that instead of referencing the reader variable directly. The result property contains the file contents on success and error contains error information about the failed operation.
Reading data URIsYou can use the same basic setup for reading to a data URI. Data URIs (sometimes called data URLs) are an interesting option if you want to, for example, display an image that was just read from disk. You could do so with the following code:
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
document.body.appendChild(img);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(file);
This code simply inserts an image that was read from disk into a page. Since the data URI contains all of the image data, it can be passed directly into the src attribute of an image and displayed on the page. You could, alternately, load the image and draw it onto a <canvas> as well:
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
context = document.getElementById("mycanvas").getContext("2d"),
img = new Image();
// wait until the image has been fully processed
img.onload = function() {
context.drawImage(img, 100, 100);
};
img.src = dataUri;
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(file);
This code loads the image data into a new Image object and then uses that to draw the image onto a canvas (specifying both the width and height as 100).
Data URIs are generally used for this purpose, but can be used on any type of the file. The most common use case for reading a file into a data URI is to display the file contents on a web page immediately.
Reading ArrayBuffersThe ArrayBuffer type[1] was first introduced as part of WebGL. An ArrayBuffer represents a finite number of bytes that may be used to store numbers of any size. The way data is read from an ArrayBuffer is by using a specific view, such as Int8Array, which treats the underlying bytes as a collection of 8-bit signed integers or Float32Array, which treats the underlying bytes as a collection of 32-bit floating point numbers. These are called typed arrays[2], which force you to work with a specific numeric type rather than containing any type of data (as with traditional arrays).
You use an ArrayBuffer primarily when dealing with binary files, to have more fine-grained control over the data. It’s beyond the scope of this post to explain all the ins and outs of ArrayBuffer, just realize that you can read a file into an ArrayBuffer pretty easily if you need it. You can pass an ArrayBuffer directly into an XHR object’s send() method to send the raw data to the server (you’ll have to read this data from the request on the server to reconstruct the file), so long as your browser fully supports XMLHttpRequest Level 2[3] (most recent browsers, including Internet Explorer 10 and Opera 12).
Up nextReading data from a file using a FileReader is pretty simple. If you know how to use XMLHttpRequest, there’s no reason you can’t also be reading data from files. In the next part of this series, you’ll learn more about using the FileReader events and understanding more about possible errors.
ReferencesTelerik OpenAccess ORM - Using SQL Server 2012 LocalDB
Microsoft SQL Server 2012 is certainly an interesting upgrade for the SQL Server, offering lots of improvements and new features. There are many things that might tempt you to migrate to 2012 or at least to start your new projects based on it, but to name a few:
- Enhancements for higher availability
- New and improved version of the SQL Server Management Studio
- Easier migration – the new Side-by-Side Migration option makes the migration from older versions of SQL Server safer and the rollback easier, which can be crucial. In the same time, you can do even an In Place migration (only if you are running 2005 or 2008 edition) or a full-blown data migration by configuring a new machine.
You will most probably want to take advantage of the new file-based version of SQL Express called LocalDB. It will be useful during the development phase of your application as you will not spend any time configuring the server - everything is configured out of the box. In the same time, as it is compatible with the SQL Server 2012 commercial editions, it will be easier to deploy your application to production servers. That means the ORM product you choose has to fully support both versions of the database, and to allow you to easily connect to and use LocalDB.
Let’s get our hands dirty and try all this with OpenAccess ORM - it fully supports LocalDB and SQL Server 2012 commercial editions. We can use the SQL Server Data Tools (SSDT) for creating and defining a LocalDB database, and then generate an OpenAccess Domain Model out of it using the simple Update from Database wizard. This component is available out of the box for Visual Studio 11 Beta, so we will use VS 11 to evaluate what is being offered. Those of you who would like to stick to VS 2010 can download and install .NET Framework 4.0.2 and optionally - SSDT (you can also use the old Server Explorer, it's totally fine).
Note that the Database First approach is the choice in this case since we would like to really familiarize with the database – for the scenarios where you don’t care about it so much, you can just create an empty Domain Model, add your entities and concentrate on the business logic rather than the database specifics.
1. Create a LocalDB databaseFirst, you have to create the .mdf file which will represent your database. In order to add one to your project, choose a Service-based Database in the Add New Item dialog (under Data category):
After you click Add, a wizard will automatically offer you to create some model or a dataset matching the empty database. Cancel the wizard and we will get to creating the model later.
2. Access the database and define the schemaFor database schema manipulations we will use the SQL Server Object Explorer - a shiny new addition to the Visual Studio:
Initially it will not have any servers presented, but if you click on Add New Server a familiar window pops up asking for connection details. Our problem now is how to specify the LocalDB here - we only know the file name and that's it!? Not so obvious, but after a short search it appeared that for getting started you can try writing "(localdb)\v11.0" as a server name and use Windows Authentication. As it turns out, while you can create Named Instances of LocalDB dedicated to one application only, an Automatic (public) one is available and it's named after the LocalDB version, in this case - v11.0.
After we add the Automatic instance, our file is shown as a database under it in the SQL Server Object Explorer. It's full path is used as a database name by default, so we have renamed it to something more readable:
The UI will somehow remind us for the SQL Server Management Studio, but it certainly has some new things to get used to. Adding a table is easy:
Just click Update, and after some additional dialogs showing you a preview of the database changes and asking you to confirm them (nice!), the table is added.
3. Auto-Generate the OpenAccess Domain ModelNow we can start the OpenAccess Add Domain Model wizard:
If you are not familiar how to work with the wizard, you can check out the dedicated Getting Started with Database First video available now in Telerik TV and you should be up to speed! Just select Microsoft SQL Server as a backend type and the connection to the LocalDB file we have added earlier should be available automatically. Just in case you need a connection string anyway, it should be something like:
Data Source=(LocalDB)\v11.0;AttachDbFilename="[path]\LocalDBTest.mdf";Integrated Security=True
Now we are ready - you have your Domain Model in the OpenAccess Visual Designer:
I hope this quick walkthrough has shown how easy is it is to enjoy the latest technologies with OpenAccess ORM. Stay tuned as Q2 2012 is approaching and we are implementing some long awaited features for it!
Basic Mobile Layout
Mobile web development is an expansive field of engineering and design, and can require extensive expertise and involve using many tools. Dojo is designed for mobile development at many levels, including lightweight, granular modules for bandwidth and CPU constrained devices, touch and gesture events, mobile-style widgets in Dojo Mobile, feature branching for mobile customizations, and much more. However, before even getting into these sophisticated aspects of mobile development, it is worth considering some of the basics of mobile layouts. Many web sites and web applications can provide a vastly improved user experience by simply employing viewport definitions and adaptive layout techniques.
Setting the ViewportFirst impressions are critical, and for many outdated web pages, the first thing a user experiences is illegibly small text that they must zoom in to read properly. Probably the first thing any web developer should learn about to prepare for mobile devices is the “viewport” meta tag. This simple tag instructs mobile devices what scale and dimensions to use to display a page, so that users can be instantly greeted with a properly scaled page where they can immediately start reading and consuming your information without zooming.
The “viewport” meta tag allows for a few different parameters that are set through the “content” attribute. Probably the first parameter (and possibly only) to set is the width. If your web page does not have any other mobile-specific customizations, the quickest way to determine a good mobile viewport width is to point your browser at your page and resize the browser horizontally. Make the browser as narrow as possible where you can still comfortably read the main content of the page without having to use horizontal scrollbars (horizontal scrollbars may appear, but shouldn’t clip the main content, only extraneous side bars). The width of the page (document.documentElement.offsetWidth) should be a good mobile width. Ideally this should be a relatively low number, in the range of 300-400 pixels (see the next section if it is not).
Now, only setting the width is not sufficiently adaptive. If you set a width of 400 pixels, this is great for a phone (at least in portrait mode), but is far too zoomed in for tablets that also use the viewport meta tag. Fortunately, this is easily solved. If we combine the width property with an initial-scale property, the browser will use both of these, first ensuring that the page will at least be the specified width, and if a wider display (such as a tablet, or a phone in landscape) is available, then it will match the initial-scale provided. This allows us to have proper scaling on multiple devices. The typical setting for the initial-scape is 1.0, which is the device’s preferred scale level for ease of reading. If you have a minimum page width of 400px, your meta tag could be:
<meta name="viewport" content="width=400, initial-scale=1.0">
Now your users will be greeted with a page that is properly scaled right away!
There are a number of other parameters that can be used with the viewport meta tag, such as minimum-scale, maximum-scale, user-scalable, and constants device-width, and device-height. However, the settings described above provide a simple technique and an excellent user experience for initial scaling and size, without limiting the user’s ability to later scale to their preferred reading size.
Adaptive LayoutIf your web application can really be resized down to a 300-400 pixels width and still be usable, you probably already have a remarkably adaptive layout. However, for most pages, having a layout that can really be usable at these widths will require some layout modifications.
There are a few CSS techniques we can use for more adaptive layouts. First, rather than specifying widths in pixels, we can use percentages. However, this approach is not heavily used in most modern web pages, as it becomes very difficult to maintain pleasant aesthetics across unbounded page widths. Having more definite limits on the layout gives a designer more constraints to work within. Instead, we can still specify widths in pixels, but provide opportunities for adaptation by using the CSS min-width and max-width properties instead of just a single width property.
A popular width for web pages is 960 pixels. To utilize a more adaptive strategy, rather than fixing the width at 960px, we could make this a maximum, and allow for narrow widths (for narrower devices). For example:
.container {
max-width: 960px;
}
Grid systems like 960.gs then often use float: left blocks to align elements within the grid. This can still be used with an adaptive container like the one above. Using floating elements can also contribute to the flexibility of your layout since blocks can wrap down below if they run out of horizontal room. Note, we can also use a min-width if we need to have a lower bound as well.
The inner elements of the layout can also use min-width and max-width when possible. In particular, blocks of context or text can typically be resized quite a bit (while sidebar’s and navigation elements sometimes have less flexibility). Some reasonable width ranges, combined with floating elements can quickly lead to a highly adaptive layout that will scale nicely on smaller mobile devices.
Media QueriesSimply using CSS with flexible widths and floating elements may not be sufficient for a highly polished interface that is fine-tuned for the major devices out there. Media queries give us a powerful way of articulating more complex and precise styling based on device size. With media queries we can specify certain CSS properties and rules that are only to be applied for certain media conditions. For example, perhaps we don’t just want browser-controlled flexible width, but we actually want to alter font size and or background-color on smaller devices. With media queries, we can do just that.
A common media query to use is applying a maximum width for a rule (or set of rules) to be applied. Here is an example of applying a rule to our #nav element when the device width is 500px or less (generally phones, but not tablets), where we reduce the navigation bar’s font-size and change the background-color:
@media screen and (max-device-width: 500px) {
#nav {
font-size: 0.8em;
background-color: green;
}
}
It should be noted that you can specify a minimum device width, but since older versions of IE (IE8 and earlier) don’t understand media queries, usually you will want to target the smaller and newer mobile devices with the media queries.
Because media queries have multiple conditions that can be combined with different logical operators and encompass different CSS rules, the permutations for how we adjust our styles based on the media is virtually endless. This is powerful functionality for making web applications that can run smoothly and beautifully on many devices. Below are a few examples of media query in action:
And Beyond
These tips provide a basic start to making your web applications more mobile-ready, and give a much better user experience with a minimal effort, regardless of what toolkit (if any) you are using. However, a truly mobile-optimized web application can be much more involved. For more advanced capabilities, such as device specific builds, native matching mobile widgets, mobile themes, and touch and gesture event handling, Dojo has a robust set of tools and we can help you create amazing user experiences.
Related posts:
- Mobile Web Apps: Apple iPhone to Wurfl
- Connect to the Mobile Web with SMS
- Mobile Gears could help network latency
SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications. Sign up today!
Deft JS: Loosely Coupled MVC through Dependency Injection
That application you just deployed? As experienced software developers, we all know it wonât be long before youâre going to need make to significant UI changes. Regardless of the amount of painstaking forethought, consensus gathering and planning backing it, no software design ever survives first contact with its users unscathed. To deliver truly effective software, we have to be prepared to adapt to an evolving understating of our usersâ needs.
So⊠how do we architect our software, so we can rapidly implement UI changes without breaking the underlying business logic?
Model View Controller (MVC)It starts by applying structure to our code, separating it into manageable units where each is responsible for a specific application concern. To this end, most software applications employ the Model View Controller architectural pattern. There are a wide variety of implementations of this pattern; software development pundit Martin Fowler has catalogued many of those variations here.
Typically, with an MVC architecture, the:
- Model describes and manages application domain data behaviors and state, and responds to requests to retrieve or persist changes to that state.
- View presents model data to the user, accepts user input, and announces high-level user gestures such as clicks or selection changes.
- Controller mediates between the model and view, listening for user gestures to initiate actions on the Model, and instructing the View to reflect Model changes.
By separating the user interface components and layout (the View) from the logic that observes corresponding user gestures (the Controller) ands triggers business logic or changes to application domain data (the Model), your application is better positioned to adapt to inevitable changes.
Deft JS MVCDeft JS enhances the Model View Controller (MVC) within Sencha Frameworks, where the:
- Model is expressed using âfacelessâ business logic components, such as Ext.data.Store and Ext.data.Model.
- View is realized using any of the rich suite of Ext JS or Sencha Touch containers and components.
- Controller is implemented by creating view-specific controllers that extend the Deft.mvc.ViewController class.
Consider a view to be a composition of multiple components in a container. A View Controller is a lightweight controller responsible for managing the state of a specific view and its child components, listening for events dispatched by the view and its child components in response to user gestures, and delegating work to injected business models and services (such as Ext.data.Stores, Ext.data.Models, etc.).
With Deft JS, a view is typically a subclass of an Ext JS container class, populated with component items. The view is configured to use the Deft.mixin.Controllable mix-in, and annotated with the class name of the associated View Controller. For each view, you would create a corresponding View Controller class that extends Deft.mvc.ViewController. This view-specific view controller would be configured to reference relevant view components and register view controller methods to handle view component events.
The Deft JS View Controller and Controllable mix-in:
- Provide class annotation driven association between a given view and its view controller
- Clarify the role of controller classes â i.e. controlling a specific view
- Support multiple independent instances of a given view, each with its own unique view controller instance
- Reduce memory usage by automatically creating and destroying view controllers in tandem with their associated views
- Offer concise configuration for referencing view components and registering event listeners with view controller methods
- Integrate with the view destruction lifecycle to allow the view controller to potentially cancel removal and destruction
- Simplify cleanup by automatically removing view and view component references and event listeners
Most model, view and controller objects are not self-contained; they reference and delegate some of their work to other objects; these objects are referred to as dependencies. Typically, you might explicitly create instances of these dependencies or manually request them from a service locator.
To encourage loose coupling between application components, Deft JS includes a lightweight Inversion of Control (IoC) container for dependency injection. When applying the principal of Inversion of Control, you annotate your class with a list of its dependencies instead of manually creating or obtaining them. When your class is later instantiated, the IoC container is then responsible for resolving those dependencies with the correct object instances, injecting those values into your class at runtime.
With IoC, your class is no longer responsible for creating its dependencies or knowing where its dependencies are defined. Further, it is no longer bound to a specific implementation of a dependency. Provided it offers the expected API, you can configure the IoC container to inject a totally different implementation.
Consequently, you can easily test your classes in isolation by configuring the IoC container with mock versions of any dependencies. You can also create multiple variants of your application, where the IoC container in each is configured to use different implementations of shared dependencies such as Stores or Proxies; one might be configured to use mock Stores and Proxies driven by static JSON files, and another configured to use Stores and Proxies that access production services via JSONP.
The Deft JS IoC Container and Injectable mix-in:
- Provide class annotation driven dependency injection
- Map dependencies by user-defined identifiers
- Resolve dependencies by class instance, factory function or value
- Support singleton and prototype resolution of class instance and factory function dependencies
- Offer eager and lazy instantiation of dependencies
- Inject dependencies into Ext JS class configurations and properties before the class constructor is executed
Imagine a view within a Contact Manager application containing a grid of contacts:
/** * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann * (http://qbnz.com/highlighter/ and http://geshi.org/) */ .javascript .imp {font-weight: bold; color: red;} .javascript .kw1 {color: #000066; font-weight: bold;} .javascript .kw2 {color: #003366; font-weight: bold;} .javascript .kw3 {color: #000066;} .javascript .co1 {color: #006600; font-style: italic;} .javascript .co2 {color: #009966; font-style: italic;} .javascript .coMULTI {color: #006600; font-style: italic;} .javascript .es0 {color: #000099; font-weight: bold;} .javascript .br0 {color: #009900;} .javascript .sy0 {color: #339933;} .javascript .st0 {color: #3366CC;} .javascript .nu0 {color: #CC0000;} .javascript .me1 {color: #660066;} .javascript span.xtra { display:block; }Ext.define( 'ContactsApp.view.ContactGridView',
extend: 'Ext.container.Container',
mixins: [ 'Deft.mixin.Controllable', 'Deft.mixin.Injectable' ],
inject: [ 'contactStore' ],
controller: 'ContactsApp.controller.ContactGridViewController',
config: {
contactStore: null
},
...
initComponent: function() {
this.items = [{
itemId: 'contactsGrid',
xtype: 'gridpanel',
store: this.getContactStore(),
...,
bbar: Ext.create( 'Ext.PagingToolbar', {
store: this.getContactStore(),
...
})
},
...
{
xtype: 'container',
...
items: [{
itemId: 'editButton',
xtype: 'button',
text: 'Edit'
}],
...
}];
}
);
This view class is configured to be injectable, using the Deft.mixin.Injectable mix-in, and its dependencies are described using the âinjectâ class annotation.
When this view is instantiated via either Ext.create() or Ext.widget(), the IoC container will resolve the âcontactStoreâ dependency and inject the associated value into the âcontactStoreâ configuration. The generated getContactStore() accessor function will return that injected value.
Additionally, this view class is configured to be controllable, using the Deft.mixin.Controllable mix-in, and its controller is specified using the âcontrollerâ class annotation.
When this view is instantiated, an instance of the specified view controller class will also be created and configured with a reference to the view. When the view is destroyed, the view controller will also be destroyed.
/** * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann * (http://qbnz.com/highlighter/ and http://geshi.org/) */ .javascript .imp {font-weight: bold; color: red;} .javascript .kw1 {color: #000066; font-weight: bold;} .javascript .kw2 {color: #003366; font-weight: bold;} .javascript .kw3 {color: #000066;} .javascript .co1 {color: #006600; font-style: italic;} .javascript .co2 {color: #009966; font-style: italic;} .javascript .coMULTI {color: #006600; font-style: italic;} .javascript .es0 {color: #000099; font-weight: bold;} .javascript .br0 {color: #009900;} .javascript .sy0 {color: #339933;} .javascript .st0 {color: #3366CC;} .javascript .nu0 {color: #CC0000;} .javascript .me1 {color: #660066;} .javascript span.xtra { display:block; }Ext.define( 'ContactsApp.controller.ContactGridViewController',
extend: 'Deft.mvc.ViewController',
mixins: [ 'Deft.mixin.Injectable' ],
inject: [ 'contactStore' ],
config: {
contactStore: null
},
control: {
contactsGrid: {
click: 'onContactsGridClick'
}
editButton: {
click: 'onEditButtonClick'
}
},
...
destroy: function() {
if (this.hasUnsavedChanges) {
// cancel destruction
return false;
}
// allow destruction
return this.callParent( arguments );
},
...
onEditButtonClick: function () {
this.getEditButton.setDisabled( false );
},
onContactsGridClick: function () {
// add a ContactEditorView to the TabPanel for the selected item
...
},
);
This view controller extends the Deft.mvc.ViewController abstract base class, which provides a âcontrolâ configuration that simplifies the creation of view component accessors and registering view component event listeners.
In this example, the grid and button are referenced implicitly by their itemId (custom selectors are also supported) and their âclickâ events are configured to be handled by corresponding view controller methods. Two accessor functions will automatically be created: getContactsGrid() and getEditButton(). When the view is destroyed, the view controller's destroy() method will be called, allowing it to cancel view destruction. If this method returns true, the view will be destroyed, and all references and event listeners created in the view controller using the âcontrolâ configuration will automatically be removed.
The IoC container is typically configured in the main application JavaScript file, within Ext.onReady(), using the Deft.Injector.configure() method.
/** * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann * (http://qbnz.com/highlighter/ and http://geshi.org/) */ .javascript .imp {font-weight: bold; color: red;} .javascript .kw1 {color: #000066; font-weight: bold;} .javascript .kw2 {color: #003366; font-weight: bold;} .javascript .kw3 {color: #000066;} .javascript .co1 {color: #006600; font-style: italic;} .javascript .co2 {color: #009966; font-style: italic;} .javascript .coMULTI {color: #006600; font-style: italic;} .javascript .es0 {color: #000099; font-weight: bold;} .javascript .br0 {color: #009900;} .javascript .sy0 {color: #339933;} .javascript .st0 {color: #3366CC;} .javascript .nu0 {color: #CC0000;} .javascript .me1 {color: #660066;} .javascript span.xtra { display:block; }Ext.onReady( function () {
Deft.Injector.configure({
contactStore: 'ContactsApp.store.ContactStore'
// contactStore: 'ContactsApp.store.MockContactStore'
});
});
In this example, the Deft JS IoC container has been configured to fulfill all requests for âcontactStoreâ with a singleton instance of ContactsApp.store.ContactStore. The commented line shows how simple it would be to specify a mock class instead.
About Deft JSDeft JS is an MIT-licensed open source framework that extends the Ext JS and Sencha Touch APIs to provide:
- Loose-coupling and dependency injection via an Inversion of Control (IoC) container
- Flexible component-oriented architecture through an alternative Model View Controller (MVC) implementation
- Elegant asynchronous operation chaining and data processing using Promises and Deferreds
Created by a team of software architects working at the innovative digital solutions agency Universal Mind, Deft JS leverages best practices and proven patterns refined over years of delivering cutting edge solutions across a wide range of platforms and devices.
.right, .alignright { float: right; margin: 0 0 10px 10px; } .left, .alignleft { float: left; margin: 0 10px 10px 0; }As your startup grows, the founders have to grow with it
On Monday, Mark Zuckerberg showed up to pre-IPO roadshow investor meetings wearing his signature hoodie. Wedbush Securities managing director Michael Pachter commented on Bloomberg news yesterday that Zuckerberg should show the investment community some respect by ditching the hoodie in investor meetings and wearing it is a sign of immaturity.
Pachterâs comment:
"Mark and his signature hoodie: Heâs actually showing investors he doesnât care that much; heâs going to be him. I think thatâs a mark of immaturity. I think that he has to realize heâs bringing investors in as a new constituency right now, and I think heâs got to show them the respect that they deserve because heâs asking them for their money."
Predictably the tech elite attacked Pachter; Pacther was even called a âdoofusâ by Kara Swisher of All Things D. To his credit Pacther is taking it well, even suggesting on Twitter that Mark wear an executive pinstripe hoodie.
As a guy who proudly wears jeans and tee shirts to formal events, you would expect me to attack Pachter as well. While I donât completely agree with Pachter, he does have a point.
Founders represent the heart and soul of a company. They set the company culture and lead by example. The problem with founders is that they sometimes forget that their company has grown up and they are still acting like the company is a small upstart. This disconnect between the companyâs size and maturity and the founderâs attitude and behaviors can cause problems, sometimes major ones.
As startups start to mature, their founders have to mature along with it. As the company moves from startup to challenger, to market leader, the founder has to make adjustments along the way. Behaviors and policies that were appropriate for a small startup may not be appropriate for a company that is public.
For example when Bill Gates rallied the troops by saying that they were going to âcut off Netscapeâs air supplyâ, Bill was guilty of acting like Microsoft was the tiny underdog when in reality it was a huge publically traded market leader and Netscape was the tiny upstart. Gatesâ comment became a major piece of evidence in Microsoftâs anti-trust trial.
Iâve made this mistake many times as well. Zagat went through several phases while I was CTO in the dot com boom and my playful behavior that worked so well in the pre-IPO/VC dot com environment of late 1999 did not go over well in the post-crash/layoff environment of 2001. We had brought in a new CEO after the dot com crash and my enthusiasm was misinterpreted by the CEO as not being serious. Unfortunately this reflected poorly on the entire IT staff. I was guilty of forgetting that the company had changed and it was time to keep the same spirit but change some tactics and behaviors. Once I did, things picked up nicely.
Founders also make the mistake of thinking like a startup when larger company decisions are needed. For example, it took Microsoft something like 20 years to buy a corporate jet, Google and Facebook had to get sued to start acquiring patents, and Yahoo! turned down a lucrative offer from Microsoft since they still thought of themselves as a Silicon Valley rebel instead of the blue chip big media company in the trouble it was in.
At Telerik, our founders have had to make adjustments over the years. When I met them Telerik was a scrappy 30 person company. Now we have teams that are larger than that and over 600 people worldwide. The founders have scaled and adjusted their behavior accordingly, all while keeping true to themselves and the company culture. They wear jeans and tee shirts to the office, collared shirts to board meetings, and suits and ties when accepting the Red Herring 100 award.
Iâm not saying the Mark Zuckerberg should ditch the hoodie and wear a suit to work everyday. However, he should realize that going public requires some behavioral changes, not just in financial accounting, but also in his leadership style.
The techie rebel in me applauds Zuckerberg for standing up the the man and wearing his hoodie on Monday. The experienced MBA side of me also cringes knowing that Zuckerberg is bound to make several Bill Gates style mistakes, mistakes that could cost Facebook dearly.
OrcsWeb's Windows Cloud Server Hosting
Doing Your First Mock
Are you looking for a solution to your unit tests modifying data? Perhaps your unit tests are so slow that none of your teammates bother running them? You need mock objects.
The following items will be covered to help you write better tests:
- Why Mocking â how mock objects help you
- Real World Example âan example of code to be tested
- Testing the Example âhow to use mocking to test the example
- AAA Pattern â a pattern emerges when writing clean tests
Mocking is one of the most important factors in writing better unit tests. It drastically minimizes a testâs execution time and gives you an upper hand in validating complex logic without disk, database or service dependencies.
Mocks are more than the default-valued objects known as stubs. Mocks act as collaborators and are subject to behavioral modification. These collaborators will help you achieve your desired unit-testing goal for a given system and a controlled set of inputs. This is achieved by having the mock object stand in for the real object and returning data you have specified.
To get a complete overview of mocks, an informative article named âMocks arenât stubsâ by Martin Fowler is a must read.
http://martinfowler.com/articles/mocksArentStubs.html
After you are finished, itâs time to give you a good grasp of mocking with a real world example.
Real World ExampleI am going to implement part of a banking system. This includes the transfer of funds between two different currency accounts using the currency converter service.
To begin, I have created an ICurrencyService interface:
public interface ICurrencyService { decimal GetConversionRate(string fromCurrency, string toCurrency); }This service interface will be injected to an AccountsService class that is responsible for the transfer funds operation. Once the source and destination account objects are passed to the operation, it will then withdraw from source, convert the currency based on current rate, and finally deposit the converted amount to the target account. There will be a check for available balance, authorization, approval, etc. in more complex scenarios, but they are out of scope for this article.
public class AccountService : IAccountService { private readonly ICurrencyService currencyService; public AccountService(ICurrencyService currencyService) { this.currencyService = currencyService; } public void TransferFunds(Account from, Account to, decimal amount) { from.Withdraw(amount); decimal conversionRate = currencyService.GetConversionRate(from.Currency, to.Currency); decimal convertedAmount = amount * conversionRate; to.Deposit(convertedAmount); } } Testing the ExampleThe goal is to validate or assert the transfer funds operation between two accounts. Therefore, this is the system under test (SUT), and the currency service is the collaborator which will be mocked. I am using JustMock for this purpose, but the core concept is the same with other mocking tools.
ArrangeFirst I will create the mock of the ICurrenyService interface:
ICurrencyService currencyService = Mock.Create<ICurrencyService>();From the account service implementation, I can see that GetCurrencyService is being called to retrieve the conversation rate. The next step is to set an expected return value for it.
Mock.Arrange(() => currencyService.GetConversionRate("GBP", "CAD")).Returns(2.20m).MustBeCalled();Mock.Arrange is the entry-point for setting expected behavior for a given mock. This line is self-explanatory, but I did use one extra option: MustBeCalled. This ensures that if currencyService.GetConversationRate is not called with the above criteria, then it will fail the test.
Since I have finished setting the behavior, I will then create an instance of the AccountService class followed by the source and destination Account classes.
var accountService = new AccountService(currencyService); var canadianAccount = new Account(0, "CAD"); var britishAccount = new Account(0, "GBP"); ActNext, I will add some money into the GBP account:
britishAccount.Deposit(100);Then transfer it to my Canadian account:
accountService.TransferFunds(britishAccount, canadianAccount, 100); AssertOnce the transfer is complete, I need to make sure the operations happened as expected. I will first assert the balance of the two accounts:
Assert.AreEqual(0, britishAccount.Balance); Assert.AreEqual(220, canadianAccount.Balance);Then I will assert the mock to verify whether the required GetConversationRate method is called as expected:
Mock.Assert(currencyService); AAA PatternYou may have noticed that there were three easy steps involved with the unit test. This is part of a well-known pattern called Arrange â Act â Assert or AAA. JustMockâs syntax is implemented to strictly follow the AAA pattern to give you a well-structured flow, even in the most complex scenarios.
In this post, I described how mocking will help you. I then built an example project and test to illustrate how to proceed. Mocking helps you write clean unit tests, and it enables you to focus on the test logic by isolating external factors. With mocking, unit testing is no longer a chore.
About the author
Mehfuz works as the Team Lead at Telerik focusing on JustMock. He is passionate playing around with the latest bits. He has been a Microsoft MVP, author of OS projects like LinqExtender and LINQ to flickr. Prior to working at Telerik , Mehfuz worked as a core member in many high volume web applications including Pageflakes that is acquired by Live Universe in 2008. He is a frequent blogger and was also a contributor and site developer at dotnetslackers.com. He is a firm believer of openness and currently enjoys his free time with objective-c and nodejs bits and never minds writing in textmate.
@mehfuzh
SproutCore 1.8.2 Released
[edit] Due to a mistake in the included files of the published 1.8.2 gem, the gem needed to be re-built. Â Therefore the current working version of the gem for SproutCore 1.8.2 is sproutcore-1.8.2.1. Â Sorry for any confusion.
We are pleased to announce the release of SproutCore 1.8.2. This release contains minor fixes to the 1.8 code-base and will likely be the last patch of 1.8 prior to the 1.9.0 release. To upgrade to the latest version, simply run:
gem update sproutcore
This is a patch release and contains the following bug fixes:
- Fixed syntax error in Datastore unit test.
- SC.SplitView can now mixin SC.SplitChild.
- Thinned picker pane border divs so that they don’t overlap the content view.
- Prevents target property conflict when configuring button targets with SC.AlertPane.
- Changed the aria-orientation of horizontal SC.ScrollView to ‘horizontal’ from ‘vertical’.
- Allows SC.CollectionFastPath to work with sparse content by always returning an item view even when content isn’t yet available.
- Prevents SC.GridView from iterating over its content array in order to work with sparse content.
- The ‘mobile-safari’ body class name is no longer being added in all browsers.
- Enables pasting in SC.TextFieldView to notify that the value changed.
- Prevents default touch behavior being intercepted on <textarea> and <select> elements.
YUI and Travis sitting in a git-tree
Over the last few weeks, I have spent a great deal of time getting YUI’s core tests executing on Travis CI. As of today, every push to our YUI 3 repo on GitHub results in over 6,000 (6,053 to be exact) unit tests being executed and logged. These tests include 1,130 of our core JavaScript-only unit tests executing natively inside of Node.js on versions 0.4.x and 0.6.x (with 0.7.x support to be added soon). We follow that with our full unit test suite (4,923 tests), running with my command-line YUITest/PhantomJS wrapper, Grover.
Today I want to tell you a little more about how and why we are doing this.
Why?For the longest time, our tests and builds were a mystery to our users. They all happened behind closed doors and nobody really knew what we were doing. Over the last few years, we started adding more and more of our tests to our source tree, so that people can see what we are actively testing. This helped a little, but it didn’t show that we run every test on every build and that if a test fails, we don’t push that build to GitHub.
Then along came Travis CI, the open source continuous integration platform that hooks directly into GitHub. I played around with it for a day and immediately began moving our tests around so we could use it. We want to be more transparent in our processes and allow the public to see what we test and how we do it.
One thing we want to add to this process is access to our current code coverage report. Currently, we run a code coverage report daily from tests executed in FF12, Chrome-latest and IE8, but none of our users can see that we are at ~80% covered:

We are working very hard to rectify this issue and hopefully get this data out in the open for everyone to see.
How?I had to make minimal changes to our core test suites in order to get them to run under Node.js in Travis CI. By “core test suites”, I mean any YUI module that can execute without the need for a working DOM. This includes, but is not limited to: YUI Core, Loader, YQL, Y.Array, Y.Object, etc. These modules are all perfectly usable inside of Node.js without modification.
Let’s look at the YQL tests as an example.
All I had to do was create a Node.js wrapper similar to the standard test wrapper we use in a browser and include the exact same test that’s executed in the browser.
Here is the YQL module’s wrapper:
Now, this same test module can be executed in a browser and in Node.js without modification!
Caveats?In order for these tests to run natively in Node.js, they need to not interact with the DOM. For example, Y.Array consists of helper methods for dealing with Arrays in JavaScript. But there are a few tests that include dealing with DOM elements to ensure that the helper methods return the right values. For these tests, I had to move the DOM-related code into a new test and add that test to the list of ignored tests when Y.UA.nodejs is detected. This way, such tests are ignored in Node.js, but still run in the browser.
Here’s an example:
As you can see, it’s relatively easy to make our tests run in both environments to ensure that our code is stable and fully functional when used in Node.js as it is in the browser.
What is Grover?Grover is a command-line tool that allows you to execute YUITest-based tests in PhantomJS. PhantomJS is a headless Webkit instance that allows you to render an HTML page without a GUI present. So Grover closes the gap on this and allows you to run our unit tests from the command-line inside of a CI system like Travis.
Grover is free and available via: npm install -g grover (You must have the PhantomJS binary installed before using Grover.)
How do we see all this?Travis CI provides a full report of previous builds, as well as an up-to-date status information. Below are the links to our current projects hosted on Travis CI:
Here is a small snippet of what our build output looks like (from the build history for the yui3 repo):

We are trying out the new Travis/GitHub Pull Request feature on all of our projects. This means that whenever a developer submits a Pull Request to us, Travis will automatically pull their code, merge it into master (on their server) and run our full unit test suite against it. Their “Travis Bot” will automatically post a comment back to the Pull Request telling the developer whether or not their patch passed its tests.
Here’s an example of a Pull Request passing:

And one where it fails:

We plan on adding support for executing our tests with Yeti as soon as it becomes stable enough to run on each build. We are also looking into deploying our code coverage numbers as well. Other than that, feel free to tell us in what other ways we can be more open than we are now.
I, for one, am very happy with all of these new features and I hope you are too!
The week in qooxdoo (2012-05-11)
Welcome to the weekly status update.
Tool ChainThe commands of ImageMagick which are invoked by the tool chain for image clipping and combining are now exposed in the Json config(a, b) .
BugfixesFor a complete list of tasks accomplished during the last working week, use this bugzilla query.
Be in touch next time.
New stable release with improved color picker
Today's new release on the Opera Dragonfly stable branch includes some major improvements to our color picker. It now opens next to the color being edited, instead of being a floating window. The interface itself has been made lighter, with a smaller size and a gray background. The alpha value is now always available, while previously it only appeared when the original color being edited was specified as rgba or hsla. The palette is available in the bottom left corner and colors can now be added and removed directly from here.
The interaction has also been improved. Scrolling with the mousewheel over the color space will now move the pointer towards or away from the cursor depending on the direction. This makes it easy to blend colors between two points. OK and Cancel buttons have been added, based on user feedback.
But it's not all just about the colors. In this release, we also improved inspection of getters. They will now be presented as getter in italic, and clicking this text will evaluate the getter and show the according value.
In the Network panel, we've updated the UA presets for global header overrides in the options tab to reflect some of the latest browers. And, as a final tweak for this build, Opera Dragonfly will now use the system's application font for its interface elements.
Tool Chain: ImageMagic Commands Exposed
The generator uses the ImageMagick tool suite to clip and combine images. In the framework we only need this functionality when particular images change, new images are added (e.g. for a theme), and combined images have to be regenerated, which occurs rather infrequently. (If you never clipped or combined an image in your qooxdoo projects, don’t worry).
So far the corresponding ImageMagick command invocations were hard-wired in the generator. But as ImageMagick changes the syntax of command-line arguments of their tools, like positions, between releases (and sometimes even their semantics!), it was hard to come up with a generator implementation that would work across some IM versions. To amend this, the IM commands are now part of the configuration of the image jobs, so everybody can tweak them to suit their local IM installation (config keys combine-images/montage-cmd and split-images/convert-cmd).
The configuration values are template strings that have named placeholders (like ‘%(infile)s‘ or ‘%(orientation)s‘). Whenever you shuffle the command line, these should be kept intact so the generator can expand them at runtime with dynamic values. For our IM installations (v6.5 and v6.6), these command lines currently work:
- convert-cmd
- "convert %(infile)s -crop %(xoff)sx%(yoff)s+%(xorig)s+%(yorig)s +repage %(outfile)s"
- montage-cmd
- "montage @%(tempfile)s -geometry +0+0 -gravity NorthWest -tile %(orientation)s -background None %(combinedfile)s"
Designing a Windows 8 Metro style app starting from an existing Windows Phone app â Design Case Study Part 1
A lot of the Windows Phone developers out there are already considering porting their Windows Phone apps to Windows 8. May be you are thinking: from Metro to Metro - it has to be pretty easy and straightforward, doesn’t it? Let’s see if this is true.
This case study gives insights into porting the design of an existing Windows Phone app to a Windows 8 Metro app. It discusses the main similarities and differences between the design guidelines of the two platforms, what can and cannot be reused.
User Experience Design Guidelines for Windows Phone
User Experience Design Guidelines for Windows 8
For the purposes of the case study we are using Tasks - a free Windows Phone todo lists app with more than 100,000 downloads. The app was created by the Telerik Windows Phone team as a showcase of our UI components for Windows Phone. It started originally with an app called ToDoLists, which is meant to serve as a learning material for Windows Phone developers (the source code is freely available and can be downloaded from here.
We will touch upon all the key design patterns and processes that are part of a Metro app and comment on what makes Windows Phone and Windows 8 similar and different:
- Design process
- Layout and navigation
- Commands and actions
- Touch
- Orientation and views
- Notifications and live tiles
- Telerik upcoming Windows 8 suite
This is the first part from series of two blog posts where we will talk about the design process and layout and navigation. You can download the full series as:
high resolution pdf (~7 MB), or
low resolution pdf (~2 MB).
Before we even get to the rough design concept, no matter which platform we are targeting, we start with research, thinking about what users need and analyzing existing applications across all mobile platforms. In our case we had the initial information architecture sorted out in Tasks for Windows Phone. On this solid base we started improving it and make it work for all the screen sizes.
This is how the low fidelity wireframes looked at this phase – sketches of ideas, different pages of the application which formed the application flow and the early paper application prototype. The next step was increasing the wireframes fidelity and transferring them from paper to file.
Paper wireframes
The developers participated in every step of the design process, helping with ideas and technical knowledge. They started working on the prototype of the app simultaneously with me working on the visual design. This does not mean that my job was done once the visual design is delivered – on the contrary. A serious designer input was needed when all the functionality was put together. Only then, especially with touch, we can be sure everything is in the right place, the interaction is consistent and feels natural. Stick to the agile best practices and have as many iterations as needed with the developer team and your testers, if you have such.
My advice is to start working on the device as soon as possible. Once you’ve started working on the device don’t be afraid to make all the necessary changes in order for the app to work at its best. And remember, do not fall in love with the design or the feature which just won’t work.
Application flow diagram – one of the deliverables at the end of the design process
Layout and navigationThe Layout and navigation model of Windows Phone and Windows 8 are very similar and different at the same time. Let’s first look at some of the things the two platforms have in common:
1. Navigate through contentContent not chrome is one of the essential Metro principles and it applies to both the Windows Phone and the Windows 8 Metro app: they have the same hub and spoke navigation models. Here they are:
1.1. Hub page – or the home page of the application from where the user reaches the rest of the application content. The goal of the hub page is to show the variety and richness of the content the application provides. It is like a magazine created for the application. In Tasks we show excerpts from due tasks, projects and categories.
Tasks for Windows 8 hub page
Tasks for Windows Phone hub page
1.2. Section pages – these are pages with identical content type. For example All Tasks page.
Tasks for Windows 8 section page Tasks for Windows Phone section page
1.3. Detail pages – the name speaks for itself – a page that show the details of a single item.
Tasks for Windows 8 details page Tasks for Windows Phone details page
Now let’s examine the differences between the Windows 8 and Windows Phone design patterns.
2. No hardware back button in Windows 8Software back button in Windows 8
Windows 8 has no hardware back button as opposed to Windows Phone, which results in the need for a back button in the page heading or navigation bar. The back button takes the user back where she came from and all pages but the hub page should have it.
In Windows Phone the Backstack is very important – this the list of pages/steps user went through till the current moment. The Backstack should be carefully managed – the user must not get lost in the application, fall into traps, loops, and phantom pages, because only in that way she will thrust the application to get her back where she wants.
I will give you an example for that. In Tasks for Windows Phone it is possible to pin a task (project, category) to Start menu. When the user taps on pinned task a details page is opened. To continue browsing in the application the user should tap on the home button close to the logo. When the user is in the home/hub page the details page is removed from the Backstack. The reason is to fulfill the requirement for publishing apps in the marketplace - when the user is on the home page and hit the back button she should go back to start.
In Windows Phone the user navigates through the app by tapping on the content items and application buttons, and goes back with the back button.
In Windows 8 the user has more opportunities to choose her way.
3. Navigating with the edge swipeSwiping from the edge of the screen is what makes the app bar and navigation bar to appear. The Navigation bar provides global navigation controls - it shows on every page and provides consistent navigation experience. The Navigation bar in Tasks for Windows 8 is one of the main differences from the Tasks for WP. We chose to use it as addition to the already implemented navigation model because of the confidence it gives to the user to go everywhere she wants from any page of the app.
Navigation bar
4. Page filters and sortsThe pivot control is the Windows Phone way to manage views and pages within application. It is used for filtering the content, viewing multiple data sets or switching views. In Windows 8 the pivot control is replaced with page filters and sorts. It is pretty much like traditional tab pattern.
Tab control in Windows 8 Pivot control in Windows Phone
5. List menu navigation. Filter menu.This is the advantage of the bigger screen – to have a menu which is made from items of certain type alongside the detailed page of the selected item. Even better, instead of making this menu list long and unreadable, there is a filter available on top to help for easier access to the desired information. This is almost impossible on the smaller phone screen – to have both the detailed information and the available other choices on same place. It is not applicable in all cases, but in our Tasks app it was more than welcome.
List menu with filter in Windows 8
6. Horizontal/vertical scrollingThe other significant difference between Windows Phone and Windows 8 is the way of handling the scrolling. In the Windows Phone panorama control there could be both horizontal – within the panorama, and vertical – within the listboxes in the panorama. In Windows 8 this situation is not recommended. There could be only horizontal or only vertical scrolling. The reason for that is the cross-slide interaction – sliding the finger a short distance, perpendicular to the panning direction to select an item. There should be consistency of the selection interactivity within single page – that’s why the panning direction should be only horizontal or vertical.
7. Semantic zoomSemantic zoom on the home page
Another element that needs to be designed in Windows 8 is the semantic zoom - a quick way to zoom out to groups of content and jump to the desired one.
8. Settings, sharing, about, feedback, search - with charmsWindows 8 provides for a special place to put all these pages and they are neatly organized. They are called charms and are just an edge swipe away. I must admit that in Windows Phone Tasks these pages are not so well organized but in Windows 8 they will be.
Feedback flyout
Tasks for Windows Phone is available for free on the marketplace. Check it out here
Tasks for Windows 8 is on its way and we will let you know once it’s live.
Tasks for Windows Phone is built with RadControls for Windows Phone – UI components and building blocks for building Windows Phone apps. Read more here and download a free trial.
Stay tuned for part two where we will take a look at commands and actions, touch, orientation and views, notifications and live tiles and Telerik upcoming Windows 8 suite!
SitePen at IBM Impact 2012
Dylan wrapped up his 2012 Dojo tour last week, presenting twice at IBM Impact 2012 in Las Vegas, Nevada. If you attended IBM Impact 2012 and missed Dylanâs talks, or didnât attend IBM Impact and want to see what was presented we’ve posted the slides of the talks:
- Star Search: Dojo 2 and HTML 5
- Beyond Dojo: The Rise of Asynchronous Module Definition (AMD) – with James Thomas
A big thank you to IBM for having us speak at Impact 2012 and to James Thomas for sharing the stage on the Beyond Dojo talk.
Have we piqued your Dojo interest? Learn more about how SitePen can quickly become a valuable extension of your awesome team. From our Dojo workshops to expert JavaScript support and custom web application development we’re ready to help companies of all sizes. Â Check us out!
Related posts:
- Only two stops left! Phoenix Mobile Festival and IBM Impact 2012.
- Road trip anyone? SitePenâs CEO is taking it to the streets.
- Parlez-vous Dojo? Dylan speaks at Web-5.
SitePen offers beginner, intermediate, and advanced Dojo Toolkit workshops to make your development team as skilled and efficient as possible when creating dynamic, responsive web applications. Sign up today!
YUIDoc 0.3.0 is Official!
Today we are pleased to announce the official release of the new YUIDoc, our JavaScript documentation generator. YUIDoc is a Node.js application that generates API documentation from comments in source, using a syntax similar to tools like Javadoc and Doxygen. YUIDoc is currently powering the API documentation for YUI and has been actively updated over the last year.
YUIDoc provides:- Live previews. YUIDoc includes a standalone doc server, making it trivial to preview your docs as you write.
- Modern markup. YUIDoc’s generated documentation is an attractive, functional web application with real URLs and graceful fallbacks for spiders and other agents that can’t run JavaScript.
- Wide language support. YUIDoc was originally designed for the YUI project, but it is not tied to any particular library or programming language. You can use it with any language that supports /* */ comment blocks.
Some of the new features added to this version are:
- Markdown support in code comments
- Support for many more tags out of the box
- Logic separated to allow for easy extensibility
- Better theming support
- Server mode for development time previews
- External data mixing
- Easy cross platform installation
- Cross-linking inside and out of current project
- JSON based configuration
Let’s get into a little more detail on some of these:
Simple InstallationIf you have Node.js and NPM installed, installation is easy:
npm -g install yuidocjsMarkdown support in code comments
YUIDoc will parse your comment with Markdown before it applies the Handlebars template giving you great flexibility when writing your docs.
Logic separated to allow for easy extensibilityYUIDoc uses YUI’s class infrastructure internally and exports all of these modules when you require the yuidocjs module. This allows end users to hook into YUIDoc’s internals and change the way it does things. You can extend classes, augment them or just flat out change methods to suite your needs.
Better theming supportIn this release we use the built-in Y.Handlebars helper to handle all template generation. We have also taken development into consideration when building this feature. YUIDoc will first search it’s built in theme directory for partials, then it will search your local theme directory. This allows you to only have to maintain the files you wish to change in your theme and not have to copy every partial even if you are not modifying it.
Server mode for development time previewsThis is my favorite new feature! You can fire up YUIDoc in server mode and it will give you live previews of your documentation as you edit it. Simply save your file and reload the page from the built in server and see your changes live. Including external data and cross-linking. You no longer have to generate the docs for your entire project just to see a documentation change!
External data mixingYUIDoc now allows you to link your documentation to the rendered output from another YUIDoc instance. For example, if your project is using YUI and extending some of our core classes, you can link to our exported data.json file (from our YUIDoc build) and when YUIDoc parses your documentation it will fetch our data and cross-link all of your extended classes back to ours. This way you don’t have to document another projects code, you simply point over to their docs like it was part of yours.
Project ChangesAll future YUIDoc development will be fully conducted on Github. We will be tracking the project on their wiki and using their issues to manage our tickets. It will be run like a native Node.js project completely in the open. We will also be using a Google Group for support requests, so sign up today!
We are also happy to report that YUIDoc’s unit tests are hosted on Travis-CI and will run per Github push!
What about the old version of YUIDoc?The old Python source for YUIDoc is in a branch on the current Github repo where it will remain indefinately. There are no plans on accepting any pull requests or making any updates to that code base.
