Struggle isn't exactly the right term. More like prolonged torture describes the frustration and experience I have had with some CSS concepts. Let's face it CSS is more of an art than some place where engineers can thrive. But time, practice and just being in the right place at the right time will eventually pay off and you learn how to accomplish something. Dumping table based layouts around 4 years ago for the higher performance and quality offered by pure CSS layouts has been an adventure. I certainly can say it was very worthwhile and has paid great dividends. Yet until recently understanding and applying the principles of absolutely position layouts was just something I could not solve, till a few months ago (I think).
Doing mobile web development for the better part of two years now I have been struggling to find the optimal recipe to make my mobile and tablet layouts work nicely. Of course there is Media Queries, but that only takes you so far and you certainly do not want to over pollute your CSS with copious amounts of extra CSS rules.

This past MVP Summit I found myself in the room with at least a hundred or more passionate web developers for a presentation by Steve Sanderson on single Page Applications, which by the way was an awesome session. I came to the session to see where the team had taken the SPA concepts in the ASP.NET stack, but I found myself doing cartwheels when he spent a few minutes showing an absolutely positioned layout. It was one of those DOOH!!!!!!!!! moments we all have. I should have seen this, why did I not see this? OMG, OMG I have to start writing some code immediately to see my fingers produce this magic.
A few months have passed and I have applied the absolutely positioned layout principle to all my new web projects. I have found I can achieve some pretty great stuff for both phone, tablet and desktop without much thought. Today I want to review some of the core principles so that you might apply them to make your web applications better.
How Does Absolute Positioning Work?
When an element uses absolute positioning it uses a set of foxed coordinates relative to the window. To actually place and define the dimensions of an element using absolute positioning at least one of the position properties (top, bottom, left and right) must be set. Now this is where I think I missed the boat on absolute positioning for so long, how the values work. The values for each position property start at 0 and increase. Note you can also specify a negative value. But what tripped me up was thinking if I set the right value to 0 it would make the element have no width because the left and right properties would both be 0 and to me that meant they were at the same location. This is not true. A 0 for the right property means it is aligned 0 pixels from the right-hand side of the window. When setting bottom to 0 it means the bottom of the element is flush with the bottom of the window.

Once I grasped this concept it clicked. I could now see how to layout my web applications and make this naturally scale with the change in the browser's dimensions.
A Simple Phone Layout
Mobile first is where any web project should start, so let's create a standard phone focused layout. It will contain a header, main content area and a footer. It must naturally fill in the height and width afforded to it by the device. Wrapping the entire view is a DIV element.
<div id="content">
<header class="header">
<h1>My App Title</h1>
</header>
<section id="main" role="main">
<!-- Content Goes Here -->
</section >
<footer class="toolbar">
</footer>
</div>
To make the CSS apply its rendering magic each of the inner elements needs to have its absolute positioning rules applied. The wrapper element does not really need help here, in fact I rarely even apply style to it, but keep it around because it helps organize the DOM.
The Header element uses a 0px position for every side except the bottom, this is left out. Instead the element's height is explicitly set, 60px in this example.
header.header
{
background-color:#FFF;
position: absolute;
top: 0px;
height: 60px;
left: 0px;
right: 0px;
}
The main element, the actual app's content area, defines the top as 61px. This will position the element just below the header and will stick there no matter what happens to the shape of the browser. The remaining position values are all set to 0px, again making them stick to the edge's of the window. If you will notice I make an adjustment by adding the padding-bottom: 48px setting. This is because I am including a toolbar or appbar at the bottom of the view. This padding means any content contained within the main element will not be hidden behind that toolbar.
#main
{
background-color:White;
overflow:hidden;
border-top-color:#000000;
border-top-style:solid;
border-top-width:1px;
position: absolute;
top: 61px;
right: 0px;
left: 0px;
bottom: 0px;
padding-bottom:48px;
}
The afore mentioned toolbar looks like the header, except it is missing the top value. I also added a z-index to make it sit above the main element. I will talk more about this updated toolbar in an upcoming post, so let's shelve that for today.
.toolbar
{
position: absolute;
bottom: 0px;
left: 0px;
right: 0px;
height: 48px;
z-index: 100;
background-color: rgb(0, 0, 0);
color: #fff;
}
Conclusion
Instead of fighting with CSS, let it help you. There is actually very little need for JavaScript resizing mechanisms, etc as long as you grasp the basics of absolute positioning.
I don't know the details, but I know its frustrating when you can't see why something does not work. Since I have been spending time (and honestly more than I feel like I should because of things like this) creating native Android Apps using Cordova (formerly known as PhoneGap) navigating the quirks of Android have been consuming large amounts of my time. One that was particularly frustrating, but very easy to solve once I found the problem was accessing Internet API for AJAX calls.
By default all AJAX calls or any calls out to retrieve web resources are blocked by Android. You have to whitelist the domains you wish to communicate to and from. I know this is the common practice for server system admins and is certainly a more secure way to manage applications, but really? Anyway to create a whitelist for your Cordova Android application you need to modify the cordova.xml file. This is in the xml folder you copied from the Cordova Android example to the res folder in your Android Eclipse project. The image to the right shows what the folder tree should look like, with the cordova.xml file selected.
The default settings only allow local pages. There are some examples of how you can add domains to the application's whitelist. You can also specify http or https as well. You can also create an allow all whitelist with the following setting:
<access origin=".*"/>
If you know the exact domain(s) you need to access you can add them explicitly. If you are like me and have the potential to communicate with a variety of domains that can possibly change frequently (my real-world developer and testing environment for example) you can opt for the allow all, like I have. I would caution you to think about tightening this setting for production, when you have a firm grasp of potential resource domains.
The updated cordova.xml file to allow can look like the following:
<cordova>
<!--
access elements control the Android whitelist .
Domains are assumed blocked unless set otherwise
-->
<access origin=".*"/>
<!-- <access origin="http://127.0.0.1*"/> --> <!-- allow local pages -->
<!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
<!-- <access origin="https://example.com" subdomains ="true" /> such as above, but including subdomains , such as www -->
<!-- <access origin=".*"/> Allow all domains, suggested development use only -->
<log level="DEBUG"/>
<preference name="classicRender" value="true" />
</cordova>
So if are finding yourself stuck trying to troubleshoot connectivity issues making AJAX calls with jQuery using Cordovoa/PhoneGap check your whitelist in the cordova.xml file. If this does not solve your problem you are going to need to do some more digging, sorry.
This is going to be my third installment in this series about making an HTML5 version of the game Pente. The main goal for this phase was to properly place the stones on the nearest grid intersection from where the user touched the board. That part turned out to be rather simple in the end, but my OCD kicked in along the way and I did some more refactoring and wanted to review some of the choices we made.
First we made some global variables to persist information about the game that needed to be referenced in several places through out game play. If you have been following along you might recognize some of the variables as well as some new names. The context is the DOM reference to the game board's (CANVAS) context member. Next is the block size or how large each square is on the board. The color stores the color used for the last stone. This is ultimately going to be used to determine winning, capturing and simulate proper turned based game play. The lines are the number of lines drawn on the board.
var context,
boardOffset,
blockSize = 0,
color = "#000",
lines = 12,
boardHeight = 0,
boardWidth = 0,
boardSize = 0,
stones = []; // stone = {x: 1, y: 2, color: "#000"}
The boardHeight and boardWidth store the dimensions of the game board. I will discuss how boardSize is calculated shortly, but it holds the square dimensions of the game board. An array of stones is the last global variable. It holds a list of stone objects that correspond to the stones placed on the board. A stone is an object with x, y properties for its placement coordinates and a color property to represent what color stone it is.
We made a few changes to the drawCircle method. The name has been changed to drawStone because that was more descriptive than drawCircle. The default fillStyle is not simply filled with a fixed value. Rather is uses a ternary operation to determine the color value. If the previous color was black it will change it to white and vice versa.
fillStyle: (color === "#000") ? "#fff" : "#000",
After the stone has been drawn on the board the color is set and the new stone object is pushed to the stones array. These are some of the global variables mentioned earlier and will be used as game play progresses.
color = options.fillStyle;
stones.push({
x: options.x,
y: options.y,
color: options.fillStyle
});
We decided to refactor the board drawing method into a method of its own. This makes it easier to redraw the board as the browser is resized or the screen orientation changes. The method sets several of the global variables discussed earlier. Ternary operators are used several places to set the value of some of these variables such as the context, boardOffset, etc. The boardOffset variable accounts for the vertical offset of the CANVAS from the top of the window. Right now the board is placed below a header with a height of 60 pixels. These 60 pixels need to be accounted for when determining the size of the board as where stones should be placed.
function drawBoard(){
var $penteBoard = $("#PenteBoard"),
$window = $(window);
context = context ? context : $penteBoard[0].getContext("2d");
boardOffset = boardOffset ? boardOffset : $penteBoard.offset().top;
boardHeight = $window.height()-boardOffset;
boardWidth = $window.width();
boardSize = (boardHeight > boardWidth) ? boardWidth : boardHeight;
blockSize = boardSize/lines;
i = lines;
$penteBoard.attr("height", boardSize).attr("width", boardSize);
intersections = [];
context.strokeStyle = "#000";
context.lineWidth = 0.99;
for(i = lines; i > 0; i--){
context.beginPath();
var x = blockSize + (lines - i) * blockSize;
context.moveTo(x + 0.5, 0);
context.lineTo(x + 0.5, boardSize);
context.stroke()
}
for(i = lines; i > 0; i--){
context.beginPath();
var y = blockSize + (lines - i) * blockSize;
context.moveTo(0.5, y + 0.5);
context.lineTo(boardSize, y + 0.5);
context.stroke()
}
//insert intersections
//intersections.push({x: ?, y: ?});
/*
var j = 0;
for(i = lines; i > 0; i--){
var x = blockSize + (lines - i) * blockSize;
for(j = lines; j > 0; j--){
var y = blockSize + (lines - j) * blockSize;
intersections.push({x: x, y: y});
}
}
*/
return $penteBoard;
};
To determine the actual size of the board the height and width of the window are retrieved and we use the smaller of the two to set the square dimensions of the playing surface. Instead of setting the height and width of the Canvas element using CSS you need to set the dimensions using the element attributes. Setting the dimensions using CSS causes the Canvas to be rendered in a zoomed in mode, which is undesirable.
Another change we decided to make was a new method, placeStone, which does some clean up to place the stone on the nearest intersection. When a user touches the playing surface they are most likely not going to select the exact x, y coordinates they want. With a mouse the odds are higher than on a touch surface, but still there will be various degrees of error that need to be cleaned up.
At first I thought this was going be a lot of ugly math, but as it turns out it was really easy. The JavaScript Math library includes a method called round. Simply put this method returns the closest integer to the value passed. This means if you pass in 87.1111 it will return 87 and 87.755 returns 88.
function placeStone(x, y){
x = Math.round(x/blockSize) * blockSize,
y = Math.round((y - boardOffset)/blockSize) * blockSize;
drawStone({
context: context,
x: x,
y: y, // - boardOffset,
radius: blockSize * .5
});
};
Simply passing in the raw x, y values would not result in the desired numbers. To get the right values we need to do some clean up. When the board is drawn a global blockSize variable is set. Since the board is flush with the left-hand side of the window the x coordinate can be divided by the blockSize then multiplied by the blockSize to get a more accurate x position. When the initial x coordinator is divided by the blockSize the remainder is removed.
When the initial x coordinate is 123 and the blockSize is 53.3...6 is divided into the coordinate the result is 2.30625. Using the Math.round method on that value returns 2. Multiplying 2 by blockSize is 106.6...67, which looks like a big discrepancy, but it actually gives us the exact coordinate we need. The same routine is done to the raw y coordinate, but the boardOffset needs to be subtracted from the raw y or pageY value to map to the right y coordinate on the board. The normalized x, y coordinates can then be passed to the drawStone method. One more thing, instead of a fixed number radius, the radius parameter is set to half the block size. This means all the stones will have the same diameter as each block, but be positioned nicely on the grid intersections. The stones will also touch as they are placed on the board. Later we may come back and make that a variable users can set, but for now this works.

The final change made to the code was adding an event handler for the window resize and orientationchange events. When a desktop browser is resized by the user the resize event fires, which will cause for a poor playing experience because the board surface is not taking advantage of the viewable area. On tablets like the iPad when the user rotates the device the same effect comes into play because most tablets and phones are not square, but rather rectangle. So the board needs to be redrawn. This is why the board drawing routine needed to be refactored to its own method.
$(document).ready(function () {
drawBoard().tap(function(e){
placeStone(e.pageX, e.pageY);
});
$(window).on("orientationchange, resize", function(e){
drawBoard();
});
});
Now that we can properly position stones on the board we need to get deeper into the actual game play. I will write about that later this week. Another issue we currently have is redrawing the stones when the playing surface is redrawn. All the stones will be cleared. So my next post will focus on using the stones array to redraw the stones in the new size and appropriate positions.
This morning I gave my how to do Native experiences using HTML5 talk at the Philly Code Camp. I want to share the links to the live demo site as well as the code and a few other resources. I posted the code I used to a site on my server this morning so if you want to try the code out on your devices feel free. If you want to just download the source code I uploaded the site to the web for you to download.
As for some of the other resources I mentioned Matteo Spinelli's site and projects are located on cubiq.org. He has built the iScroll library as well as the add to home screen libraries. Remember he writes is library to be JavaScript library agnostic. Raul Sanchez wrote the iScroll-wrapper to make it more jQuery friendly.
I hate I did not have WiFi available to show how to make a web application on the iOS devices. So I want to point you to my article on how to use the Add to Home Screen library designed by Spinelli and how to add the Apple web application META tags to make a nice native experience.
The Jumplist widget I showed was written by Colin Eberhardt is available on CodePlex.
Thanks for everyone who came.
As web development and architecture matures so does the way we need to structure our projects. For me that means single page applications. And while I have not had time to write on the topic yet I have been developing my approach to focus on performance and extensibility. Because a single page applications require all the views or pages of an application be available at anytime it means the applications needs to receive all the content up front. Whether you want to actually pull all the applications views at once or utilize a deferred strategy the need to include all the views from a single URL is required.
Managing all these views would be extremely confusing and over complicated using a single page or view. Instead all these views should be some form of individual files, either a shared view or specific cshtml file. But the main page or what I call the deferred content page actually returns all the views in a structured manor.
For MVC I like to include the views in a structured way under the Shared folder. This makes it easier to reference, well at least it gives you the freedom to not include the file extension. In MVC razor these views are included using the following syntax:
@Html.Partial("ViewName")
The Html.Partial method uses the Html helper class and renders the content of the view as an HTML encoded string. Additionally you can pass extra data as an object to the Partial method. You can read more about implementing Html.Partial and Html.PartialView on my friend Rachel Appel's blog.
More and more I find myself developing web applications in using WebMatrix, which also uses the Razor view engine. Unlike ASP.NET MVC WebMatrix does not have the Html helper class available, and instead just uses the Razor view engine directly. Instead of the above syntax, WebMatrix razor looks like the following:
@RenderPage("Viewname.cshtml")
Notice you have to include the explicit file extension. Besides the file path parameter you can also pass additional data as extra parameters to the RenderPage method. This can be a series of parameters or an object. These extra parameters can be retrieved in the view itself by accessing the PageData property.
The output rendered using these methods ultimately looks something like the following:
<section id="View1" class="content-pane">
<h1>View1</h1>
<!-- content here -->
</section>
<section id="View2" class="content-pane">
<h1>View2</h1>
<!-- content here -->
</section>
<section id="View3" class="content-pane">
<h1>View3</h1>
<!-- content here -->
</section>
Obviously using this technique does not have to be limited to a single page web application, but can be used in many scenarios. Its a great technique to leverage when you have common content that can be included in multiple pages in your site or just to break down a large page into more manageable chunks.
This year is looking like the year enterprises execute a radical shift when it comes to mobile strategies to keep up with the consumerization their employees are forcing. This means organizations of all sizes, from small shops to multi-national behemoths are adopting mobile in all sorts of new ways they have never conceived. The days of a closed system that made RIM the dominate tool for enterprise mobile solution are numbered. Today employees want the device they want and to feel like they are in control of their very personalized experience. This raises quite a few challenges for today's IT departments surrounding application provisioning, data access and other security and device management.
The consumer application stores popularized by Apple, Google, Microsoft and others have created a model that many enterprises are considering as a way to manage their line of business application provisioning.
Its been several years since Apple introduced the first mobile app store, yet the needs of enterprises have not been met very well. iPhone and iPad application distribution still requires an organization to negotiate through Apple's censorship and other barriers to a smooth experience. Android by and large requires a corporation to setup and manage their own on-premise application store or go through a third party. Windows Phone still does not have a viable enterprise story after 2 years. Even if you can setup these native application store solutions you still need to develop custom native clients for each platform.
So what does a good enterprise mobile application store look like? What features should it offer to make the IT department's mobile application management as easy as possible, yet engaging and easy enough for employees to use it?
Lower IT Costs
As with any project the enterprise App Store should lower overall IT operation costs. Opening the doors of anything new, especially on the scale of a corporate wide mobile application store has costs associated with it. In the short term there is going to be an understandable burn rate. But over time the long tail effect should be an overall reduction in costs. I often get a little put off by statements like that because there is no real way to measure the cost savings or increases. Would not having an app store at all save money? Is that an option at all?
Not adopting a viable mobility solution/policy will ultimately cost your organization by making it company less competitive through the chaos that ensues?
So to that point, any good enterprise mobility plan should foster application adoption. The corporate app store should be a tool that makes employees want to see out applications, functionalities and cool things your organization has created. It should be a fun, enjoyable experience. This should help squelch any poor political arguments like I presented in the previous paragraph.
Must Be Homogeneous
The reality of a consumerized IT department means any enterprise app store solution should provide a nice homogeneous experience for a very heterogeneous environment. In other words the store should be consistent across all platforms as well as being accessible from all platforms. This means that everyone in your organization can have their iPhones, Nokia Lumina's or Galaxy S's and not be left out in the cold.
Decide Application Class
Another question the IT department must settle is what class of applications are they going to offer? Do we limit things to platform specific native applications? HTML5? Both? Does an organization limit the type of business applications allowed to go mobile? Is there a certain quality an application must have to be accepted in the company store? If so what are those qualifications? Does it have to meet certain aesthetics, security guidelines, performance, etc? Does an application's licensing terms make a difference and how are you going to manage and track the required deployment information regarding any terms?
Update Cadence
How are you going to handle application updates? What sort of update cadence are you going to allow? Does an application submitting and update require a full IT department review as if it were a new application? How will you notify users of application updates? Does and HTML5 app and a native app need the same update and deployment rules applies?
Feedback
While not an obvious app store feature the overall mobile application architecture should provide several levels of feedback. The first level is allowing end user feedback such as ratings, reviews and direct feedback to developers and IT administrators. While real user feedback is invaluable to make improvements, actual raw data can’t be beat. Real-time telemetry and usage data available to both administrators and developers can help improve applications at many levels before users report issues.
Administration
Providing an easy way for IT Admins to manage application access and distribution is one of the driving forces behind enterprise app store adoption. IT should have the ability to manage application deployment, access. This can take the form of controlling when an application becomes available as well as its updates. But it also includes control over what types of employees have access to each application.
Foster Innovation
The company's app store should also foster an environment that encourages developers and departments to produce good line of business application experiences to solve problems and add tangible value to employees work life. Mobile is the hot commodity for technology right now. I think I have given over 20 talks about mobile development in the past 15 months and every single one of them had a large percentage of developers wanting to figure out where to start. They all wanted to do something mobile and when I asked a lot of them they were planning on doing it nights & weekends. What that tells me is there is a large number of developers, many just sitting in the walls of enterprises all over the world just itching to start doing something in the mobile space. Why not tap that energy to make something useful for your organization.
Just as there is a lot of potential mobile energy inside the corporate development programs, there is just as much if not more pent up desires in the rest of the work force. Employees are anxious to be able to work on their iPads, smart phones or just anything that makes the boring routine of their day a little more exciting. I talk to friends more and more that are telling me their company is getting them iPads or allowing them to upgrade their phones so they can be more productive. They get a little pep in their step talking about their job no matter that that job is. Its almost like there is this childhood excitement I have not seen in working adults in a long time. Most are not even sure what these new devices will mean just yet, but my point is they want it, they want to try it out.
Conclusion
The enterprise application store and balance of the mobility strategy should capitalize on the entire organization's excitement around mobility to build not only useful tools, but great experience. The central hub of all this new activity will be the enterprise app store. Everyone will need to access it to install or access line of business tools for their devices. Developers can have a context to express themselves in the mobile space, they can explore and do what they do best, create applications to solve problems and make daily life better. The IT department while having to change some of its traditional thinking when it comes to application deployment should have a tool that not only helps reduces costs over the long term, but helps their company stay competitive and grow.
There are not a lot of books on mobile development I have found to be that helpful so far. Recently I purchased the O'Reilly published Mobile Design Pattern Gallery book and want to recommend it. Its not a book deep in technical details, but rather a survey of UI patterns that work and don't work. It is rich on real life examples of UI patterns used in real applications with explanations of how each one exemplifies good and bad mobile design practices.

Personally I enjoy perusing some of the design pattern library resources online like the Yahoo! Design Pattern Library and Infragistics Quince. While searching through these libraries I not only find some good ideas and inspiration, but they amaze me at how something like a design pattern can be organized. There are numerous site galleries available, but they never focus on how the UI is organized. Which is why I like these libraries. The Mobile Design Pattern Gallery book focuses on mobile only, which the typical library does not focus. In today's world of touch first mobile applications this is extremely important as most developers have not truly grasped concept key to great mobile experiences. This is why I want to recommend the Mobile Design Pattern Gallery by Theresa Neil.
Last week I opened a new series documenting how we are going about writing a HTML5 version of Pente for a class project. The first part focused on creating a Pente board, which is a simple series of lines forming a grid. Today I want to do a quick demo on how to draw circles on a Canvas to represent the stones. In the process I will utilize a JavaScript pattern I love to use to accomplish method overloading
Drawing a Solid Circle on an HTML Canvas
Before I get into code refactoring let's look at how to draw a circle on a Canvas element. Recalling what we learned last week to draw on Canvas you need to get a reference to it's context. Which looks like the following:
var canvas = document.getElementById ( "PenteBoard"),
context = canvas.getContext ( "2d");
Also like last week you need to use the beginPath method to initiate the drawing process. Before creating the circle you need to designate what the object's fill color should be using the fillStyle property. In this case we want a solid black circle. I am using the rgb() method here, passing in 0 for red, green and blue. You can also use the common #000 syntax, just remember to wrap the value in "".
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.arc(100, 100, 25 + 0.01,
0, 2 * Math.PI true);
context.fill();
Next to create the circle we need to call the arc method. This method has multiple parameters. The first two are the x & y coordinates for the center of the circle. The third parameter is the circle's radius. The next two parameters are for the start and stop angles. Having control over the start and stop gives you the power to create arcs and semi-circles as well as a full circle like we need for Pente stones. The final parameter designates if the arc will be drawn in a clockwise direction or reverse. It is optional and assumes clockwise by default.
To complete the circle call the context's fill method. This fills in the desired color, making the circle a solid element. Otherwise we would just have the circle's circumference drawn. Note if you do not designate a fillStyle it will default to black.
Refactoring To A Reusable Method
Now if you know me you know I am satisfied with this. I see a common pattern I plan on using over and over again. So let's refactor all this into a method we can reuse with some default values. Because the steps to draw a circle require multiple values I chose to use an anonymous object to manage these values. I love using this pattern because it makes a method extremely flexible, while providing much needed defaults. It utilizes the jQuery $.extend method. This is one of the jQuery utility methods I use all the time. There are other variations available in other libraries, like underscore.js that you may prefer.
The advantage this technique gives you is the ability to define the default settings and merge them with any corresponding values passed to the method. You can have as many objects as you want passed into the $.extend method. I will apply the values from left to right. In the example below the first object is empty, to guarantee an empty slate to start with. The next parameter is an object defining all the defaults needed to make the drawCircle method work. The final object is the options parameter, which is the method's only parameter. Any member values included in the options object will be merged with the defaults and override them. If there is not a value for one of the properties the default is retained. The $.extend method returns the fully merged object, which in this example is set to the options variable.
function drawCircle( options){
options = $.extend ({}, {
context : undefined ,
fillStyle : "rgb(0,0,0)",
x : 100 ,
y : 100 ,
radius : 25 ,
startAngle : 0 ,
endAngle : 2 * Math.PI ,
clockwise : true
}, options );
if( !options.context ){
return ;
}
var context = options.context ;
context.beginPath ();
context.fillStyle = options.fillStyle ;
context.arc (options.x ,
options.y ,
options.radius + 0. 01 ,
options.startAngle ,
options.endAngle ,
options.clockwise );
context.fill ();
};
After the options have been set the method checks to make sure we have a context to work against. If not it simply returns and no circle will be drawn. Notice the default context value is undefined. This means the calling method must at least pass in a context for a circle to be drawn. The remaining values can use the default values if nothing was defined. The rest of the drawCircle code is the code to draw the stone. Notice we do not use any hard coded values, but rather the members of the options object.
Now that we have a nice reusable method we can start drawing circles. The following examples draw a semi-circle and a full circle.
drawCircle ({
context : context ,
x : 100 ,
y : 100 ,
radius : 35 ,
startAngle : 0 ,
endAngle : 1 * Math.PI ,
clockwise : false
});
drawCircle ({
context : context ,
x : 200 ,
y : 100 ,
radius : 15
});
In the next step we will examine how to place the circles on the board in response to a user selecting a position on the Pente board. This will involve working with both mouse and touch events and some math.

Lately the interest in cloud storage has captivated me. Google offering G Drive, Microsoft pushing SkyDrive more, DropBox offering more space when you get a friend to sign up (hurry you can still sign up can get an extra 500MB at DropBox), etc. Like most people I have not really leveraged all my Gigabytes in the sky till the past week. I raced to claim my 25GB SkyDrive space before it was permanently reduced to 7GB. And I decided it was time to start storing things in the cloud.

When you install the SkyDrive application is creates a SkyDrive folder under your personal folder, C:\Users\{username}\SkyDrive. When you add a file to this folder it will automatically sync it with your SkyDrive storage. Pretty nice, that is until you get a message saying "We're unable to find the SkyDrive folder". I get this message every time I reboot now and of course my files are not syncing up with the cloud.
Searching for the cause I came across this Microsoft Answers page about the SkyDrive issue. After about a week and uploading some logs to Microsoft they responded saying the problem was too many files. Say What???? Evidently you can only have up to 150,000 files in SkyDrive. After that SkyDrive will simply not work.
While 150,000 files may sound like a lot it isn't. Especially if you have opted for a paid plan with even more storage. With additional options above and beyond the free storage that can take you up to 125GB of storage ($50/year for the extra 100GB) this file limit can easily be reached. Doing some quick math in my head that gives me roughly 149,999 files that average 667 Kb. Since I imagine most files will be Office documents and photos it could become fairly easy to max out. In my case I actually moved a folder to SkyDrive that contained a public database containing over 140,000 tiny text files. After deleting that folder from SkyDrive my problem went away.
Error messages like this are problematic. Clear communication with the end user is crucial, especially for a commercial application like SkyDrive. Customers want to know what is going on and not have to search for solutions to an issue. In this case, instead of displaying a message indicating it could not locate the folder, give the user a message about having too many files and the 150k limit. This helps the user understand the issue and make the needed adjustments.
So if you are getting the "We're unable to find the SkyDrive folder" error message check the number of files you currently have mapped to your SkyDrive folder and eliminate files you no longer need or no longer find necessary to store in the cloud
The news about Yahoo's CEO Scott Thompson's resume 'fraud' has the tech and business
world abuzz. Evidently Thompson's resume claims he earned a Computer Science degree that his college did not offer during his attendance. To his credit, he did take some computer science classes while an undergrad toward a concentration in computer science. I understand what this means; my undergrad degree is in Textile Chemistry with a concentration in Polymers. I am not sure how Stonehill college referred to its computer science concentration. Today, I want to discuss truth in business and how it ripples and follows you around.
Company Trust
It's bad enough Yahoo's leadership was already struggling with employee and shareholder moral. This issue does not help. Even when you are not the CEO of the company, you need to earn the trust and respect of your fellow employees. Being the figurehead in the company or even your department only amplifies the effect.
There’s a huge credibility issue now for Thompson. How is he ever going to be trusted in the eyes of his employees now — let alone his investors?
- Forbes
Even if you are not aware of it, everything you do is being watched and logged by co-workers and customers alike. We all do it because we are always trying to gauge what is expected of us as employees. Customers are doing the same to manage their expectations. When I played college football, our coaches always stressed to us how much our off field activities affected the team. They emphasized just how much we were under the public microscope. Any little mistake or mishap could and often would have a ripple effect to everyone in the program. You can see how this works with college athletes today; just look at our rival UNC's football program and the University of Miami. Recently the University of Arkansas had to fire their head football coach, Bobby Petrino, for his actions in a hit and run accident and affair.

Similar headlines hit the business world all the time. Recently you may have heard how Best Buy had issues with their CEO, Brian Dunn. In government, secret services agents got caught exhibiting less than respectable behavior in a foreign country. Again the actions by a leader, such as Brian Dunn, is having immediate ripple effects as another executive left a company that has been struggling lately. I have no research into how this is affecting the average manager and floor employee, but I cannot imagine it is good.
As for the secret service agents it cast a large shadow of doubt on an agency that many actually respected. Its hard enough for a government agency to garner respect, stories of employees acting inappropriately or outright stealing money brings down everyone.
Customer Trust
Something I learned running my own consultancy company was that a typical customer does not trust you, especially when you are doing something they don't understand. As a web developer my customers relied on me to solve technical problems that scared them to death. Stuff that was simple to me often scared them. But I never felt many customers truly trusted me. I always felt like I had to do something more to get their trust. I would try to explain how things worked and why I needed to do certain things, especially when they were complicated. Looking back I think that approach was more of a mistake. I went out of my way to explain many technical details and this only cast greater doubt on that trust. I think they felt like I was trying to deliberately confuse them, sort of the way some car owners don't trust repair shops.
Recently at a car dealership to get a car repaired, I naturally assumed I was going to be shafted. But I actually had a great experience. The folks at the dealership were extremely kind. They made a tremendous effort to explain the problem and my options. But they did a much better job than I felt I could have done explaining the problems. As a result I feel much better about going back to that dealership and recommending it to others.
Other times in my career I found myself in situations when I knew I was getting screwed by those I worked with and my leadership. The classic example is the marketing/sales guy over-promised a customer without consulting the engineers. My standard story is our sales guy left a meeting with a potential customer and called me on the way to the airport. He just told a potential major customer our product did something it did not do, nor had we even considered that functionality at that point. In fact to implement the features would take at least a week or two. To make matters worse, I'm told to make the product appear that it had the functionality by the next morning because he had scheduled a remote demo for me to lead in the morning with the potential client. Needless to say, this meeting did not go well, and the customer never bought a license. I think, if the sale guy had been honest with the customer and said he would check with the developers and ask to add the features, but it would take a month or so to work it into our schedule, we would have gotten the sale. The customer was genuinely interested in the product, but after that meeting lost trust in our product team and the company as a whole.
Employee Trust
One of the main reasons I decided to go out on my own back in 2000 was to eliminate things like the previous story, but more importantly to not have dishonest leadership over me. I won't get into details, but I will discuss common scenarios with various clients over a decade.

One common issue was customers dangling fictitious carrots in front of me. Often a customer would come to me and want me to work for a discount in exchange for a share of their company, etc. They would make wild promises of getting rich if their idea blew up and got big. This scenario was repeated dozens and dozens of times, and I know many others hear this same pot of lies. Other times the carrot would be offered after I was working for a customer in the form of faster payments or increased work if task X lead to Y revenues for them, etc.
As a consultant, and even an employee, this has happened to me and many others. Eventually you become so jaded to employers you simply don't care anymore. The numbness you develop negatively impacts passion and effort. It also leads to job hopping as well. As someone running a small web development business this was extremely stressful and lead to accumulating more clients than I should have, which caused me to stretch myself thinner and thinner. Often full time employees will start doing side work, etc, also reducing the quality of their work.
Money and cash flow are important to businesses, and just as important to individual employees too. Often customers would not pay their bills on time, or even within the same quarter as when invoices were issued. This affected me as I often found myself needing to abandon projects or assignments in favor of others that would pay consistently. It also caused me to try and eliminate the bad customers. During the tornado that was my Extreme Web Works days, I could never see this was a common problem. In fact all the issues are extremely common. I know that now, it's much easier to see that after the fact than it was when I was living it everyday.

As an employee I have been put in no win situations more often than I care to recount. I have been assigned tasks for which I was ill equipped to produce quality work, either because of lack of existing skills set or rushed timing. One of the worst experiences was when I was assigned a project as an expert in a topic I only had a few week's experience. It also required a vast amount of pre-work be accomplished in less than 4 days. Normally that work would require 4-6 weeks of effort. This did not turn out well, and I got about 6 hours of sleep over the course of 10 days. That rippled into physical issues, and it destroyed the relationship I had with that employer as well as the client.
Conclusion
Honesty and trust are two of the most important principles of a business, whether it is the leadership with employees or interactions with customers. Ultimately dishonestly comes around to hurt you by breaking vital trust relationships. This leads to the loss of vital employees and customers that ultimately destroys a company. I have seen it happen over and over, and been affected by it as an employer, employee and customer. So whether it is integrity with your credentials, honesty about your products and skills, how you carry yourself in public or how you treat employees it all matters. Small things add up to big things, so think about the next time you make a claim you know is not true. Eventually it will lead to self destruction.
A truthful witness gives honest testimony, but a false witness tells lies. Reckless words pierce like a sword, but the tongue of the wise brings healing.
- Proverbs 12:17-18
So far this year I have not had the time to get around to events for many presentations. I really enjoy doing sessions because they give me an opportunity to dig into a topic more than I normally would, share things I learn that I simply do not have time to write about here on my blog and finally interact with you. Interaction with fellow developers I don't work with on a daily basis is a lot of fun and helps keep me energized. Since I work from home it also gives me an excuse to go outside LOL. This coming week looks to be pretty busy for me.
Thursday I will do a live webinar titled 'Developing Mobile Applications in the Enterprise: Best Practices, Technologies and Techniques to Build Great Apps Efficiently' at 2PM EST. Now that is a very long title for sure. If you have been reading my blog the past few months you know I have been spending a lot of time researching enterprise mobility issues and answers. While I can't answer everything in a 60 minute session I do plan to address topics around security, mobile device management, leveraging cloud technologies and client development strategies. I have have already written about my MDM position as well as some around enterprise mobility and the cloud. But I have not written much about enterprise mobile client development strategies. I plan on reviewing all these areas next Thursday. Please feel free to register.
This coming Saturday I return to the Philly area Code Camp with about 600 other dedicated .NET developers from the region. I have an early 8:30 AM session presenting how to do some native mobile application features using HTML5. I have given this talk a few times last year, but I am working on updated and some new examples for this session.
Right now my summer is very empty. I hope this changes soon. I have several events and conferences I am working out scheduling. If you would like me to possibly schedule something with your user group event or conference please feel free to contact me, clove@extremewebworks.com. I can't promise I can work it out, but I would really like to give it a shot. I am particularly interested in mobile focused events and conferences outside the .NET world. I want to try and branch out a little this year and learn more about other ecosystems.
I also want to remind everyone that I have a Slide Share page with all my slide decks, http://www.slideshare.net/docluv. Please be sure to check it out and follow me for my latest updates.
Before I wrap up remember I will be speaking along with a dozen or so other MVPs this October at the Windows Phone DevCon in San Francisco. If you register by June 22 you can still save $450 on the conference. It looks to be a great event and I can't wait.
If you know me you know over the past few years I have been a big fan of Metro UI and the tiles. I have been hacking at doing the Metro UI in web applications for a while now, so there are a lot of things I have learned, and some I have not quite mastered yet. Doing tiles is a big part of Metro and this is a relatively easy trick to pull off using common CSS techniques. I created what I refer to as the FourSquare prototype last summer for my team to build the Moesion home screen.

When I refer to FourSquare in this instance I am referring to the FourSquare Windows Phone 7 application which is one of the best Metro UI applications I have used. I really like the way the home screen works because it gives you 8 big easy to read tiles of the 8 most likely places you want to check in when you open the application. In fact it takes 3 touches, including the tap to open the application to check in, just a great UX in my opinion.
But today I want to talk about how to recreate the tiles on the home panel as well as tiles in general that you can reuse in your web applications. I have found it fairly easy to use various DOM elements to make tiles. Today's examples will utilize LI elements, but I have also used DIV, SPAN and SECTION tags as well. They all work out the same. Each item in the list uses the block-item-large class.
<ul class="block-item-list">
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
<li class="block-item-large">Title</li>
</ul>
In this example the blocks are what I consider to be large. I also use classes, -medium and -small, to size smaller blocks when needed as well as a -wide we will see shortly for rectangles. In this example I set the border to none and add a shadow behind the tile. The shadow is so I could see what it looks like, typically you would not add this sort of accoutrement in Metro. To make a square set the height and width to the same value, 96 pixels in this case. 96 is a good number to use because it ensures the user has a solid touch point to hit. It is also a multiple of 6, which is a common scale used in Metro layouts.

li.block-item-large
{
border: none;
cursor: move;
display: inline-block;
height: 96px;
width: 96px;
padding: 4px;
margin: 12px 21px 12px 0px;
color: #FFFFFF;
background-color: #318AC6;
-webkit-box-shadow: 5px 5px 20px 0px #1a1b1f;
-moz-box-shadow: 5px 5px 20px 0px #1a1b1f;
box-shadow: 5px 5px 20px 0px #1a1b1f;
}
To add to the touch target features the margin that provides adequate spacing between elements. In this example I set the left margin to 0 and the other margins to various multiples of 6 & 3. When you are designing touch targets it is very important to use space between elements to help the user touch the right spot, or provide extremely large targets to touch. I will talk about this at some point in the future.

The final CSS rule that makes the tiles work is using dsplay: inline-block. This lets the tiles line up side by side while retaining their block attributes. I find myself using inline-block quite a bit when doing modern layouts because it gives me the best of both worlds. One advantage it gives me is the ability to do a more fluid layout. In the case of the sample layout I have 10 tiles in a bounding container sporting 500 pixels wide. With the size of each tile and its margin spacing this means that only 3 tiles can line up horizontally. But the inline-block setting allows the tiles to naturally create a new line. In this example that makes 3 lines, 2 with 3 tiles and one with 2 tiles.
The next group of tiles I call medium and they are almost identical to the large tiles except there is no shadow and they are smaller. I also added a white border around them to help them standout. These tiles are 48 x 48 squares. I don't have a -small tile to share today. But I do not recommend smaller than 30 x 30, it makes for a tough target to accurately hit with your finger.
li.block-item-medium
{
border: thin solid #FFFFFF;
cursor: move;
display: inline-block;
height: 48px;
width: 48px;
padding: 4px;
margin: 10px 20px 13px 0px;
color: #FFFFFF;
background-color: #318AC6;
}
Finally a wide tile. Again the difference is the tile's dimensions, which in this case are a 2:1 ratio. In my example I choose 84 pixels hight and 168 wide.

li.block-item-wide
{
border: thin solid #FFFFFF;
cursor: move;
display: inline-block;
height: 84px;
width: 168px;
padding: 4px;
margin: 10px 20px 13px 0px;
position: relative;
color: #FFFFFF;
background-color: #318AC6;
}
Creating Metro style tiles using basic HTML and CSS is very easy. Using display inline-block helps you create tiles that not only hold their shape they also naturally cascade across their container to form natural rows and columns. Proper size and spacing helps user have quality touch points so they can successfully use the application. I will make another post soon on how to format inner elements to add icons and titles to the tiles to add more value to the user.
Download the Code!
I do a lot of presentations and online demonstrations of mobile clients these days. That means I need to share screens from all sorts of devices. The problem is none of the major mobile platforms make this easy, but there are some hacks to get you there. Today I wanted to share a simple utility called Android Screencast I have been using to share the screen from my Android devices. There is a good post about Android Screencast with a download link. I have not reviewed the Android Screencast application's source code, but you can get it from Google Code using Git.

The application requires you have the Davlik Debugger up and running and of course your Android device running. Since I have not reviewed the source code, my suspicions are it utilized the debugger's screenshot capability to snap a new screen shot every second or so. I say this because there is a slight delay to what is shown on the screen to what you actually do on the device. So if you are only going to be satisfied with a real-time screen sharing utility keep looking, and of course let me know about it!
Recently I decided to help a very special 11 year old with a class project to write a video game. It takes me back to when I was 11 and wrote my first games. Of course back then I wrote in BASIC on my Timex Sinclaire 1000 and did my best to save the code to a cassette recorder. Today we are going to write the game using HTML5 with WebMatrix and source control systems. Instead of targeting a 13" black and white TV there are a variety of consumption devices we need to target as well as modern touch interfaces. This means we need to have a solution that will work well on a phone, tablet, desktop and beyond. Fortunately HTML5 offers us the ability to start mobile/touch first and scale upward.
We decided we would write an online version of Pente that would work across multiple platforms and devices. I was first introduced to Pente in college when one of my good friends wrote a version of it to help him learn Turbo Pascal one weekend. Since he did it in one weekend back in the early 90s I figured I could do it over several weeks investing 2-3 hours each week.
Pente is a relatively simple game. The goal is to either get five of your stones in a row or 'capture' 5 pair of your opponents stones. The game board is made of a 12x12 square grid. Users take turns placing stones on line intersections. Each player tries to get 5 stones in a row either horizontally, vertically or along a diagonal while blocking their competitor from doing the same. If a player surrounds a pair of opponents stones, those stones are captured and removed from the board. Capturing 5 pairs of stones will also win the game.
In this blog post we are going to create the basic playing surface, a 12x12 grid. Since this game requires some basic drawing techniques I chose to use the Canvas element. Canvas is a new HTML5 element that provides a rich surface to dynamically draw, add images and perform animations common to just about any game. In this initial step I am going to set the canvas dimensions to a fixed 800x800 pixel size. I will make this more dynamic in the next step, but I wanted to simplify things to get it started.
< canvas id= "PenteBoard"></canvas >
You can set the height and width by specifying the values in attributes, but because I know this will need to be more dynamic based on the device and browser size I chose to set this in the JavaScript. In the following code below I set the height and width in the jQuery.ready method. I chose to go a little old school by using the getElementById method instead of a jQuery selector. So you can see once I get a reference to the canvas element I get its 2d context by calling the getContext method passing the "2d" parameter.
$ (document ).ready (function () {
var canvas = document.getElementById ( "PenteBoard"),
context = canvas.getContext ( "2d"),
blockSize = 800 /12 ;
canvas.height = 800 ;
canvas.width = 800 ;
//more stuff goes here
});
Next I define a blockSize variable I will use in the next step. I am getting what each block's dimension should be by dividing the 800 pixels used for the canvas by 12, the number of blocks across and down the playing surface. Next I set the canvas' actual height and width to 800 pixels.
After setting the canvas size its time to add the grid lines. Since the playing surface is a 12x12 cell grid we need to draw 11 vertical and horizontal lines. This means we need to employ 2 for loops that will count from 12 to 0. Why backwards you may ask? Well evidently counting backwards is faster in for loops than forwards, and I am always searching for performance tweaks. This trick was pointed out to me during a talk at the Dallas Day of .NET, and I have seen a few other references to this since then, so let's go with it ;).
Before executing the for loops, you should set the context's strokeStyle and lineWidth because these values will be use by each of the lines. To draw a line on a Canvas you call the context's begingPath method. Then you call the moveTo method supplying the x & y coordinates. This designates the point to start the line. For a vertical line this should be some variable x value and 0 y value. The moveTo call is followed by a lineTo, also passing x & y coordinates. This time the y coordinate should be 800 or the canvas' vertical height. Finally call the stroke method to complete the line drawing.
var i = 12;
context.strokeStyle = "#000" ;
context.lineWidth = 0. 99;
for( i = 12 ; i > 0 ; i --){
context.beginPath ();
var x = blockSize + ( 12 - i ) * blockSize ;
context.moveTo (x + 0. 5 , 0);
context.lineTo (x + 0. 5 , 800);
context.stroke ()
}
for( i = 12 ; i > 0 ; i --){
context.beginPath ();
var y = blockSize + ( 12 - i ) * blockSize ;
context.moveTo ( 0. 5, y + 0 .5 );
context.lineTo ( 800, y + 0 .5 );
context.stroke ()
}
To create the horizontal lines repeat the for loop, but this time the x coordinates will be fixed and the y coordinates vary.

I chose to style the background color using a CSS rule and chose a green. This can be replaced with any color or image. I will explore more options here in a later post as well.
In the next post I will review how to draw a circle to represent a players stone’s. Hopefully by the end of the May we will have a fully functional game to share with everyone as well as learning some basics of using the HTML5 canvas control and basic of AJAX gaming techniques.
Yesterday I posted about including a favicon for every website or web application to increase performance. Another common oversight is not setting a far-future expires header expiration date. I think the Yahoo performance page says it really well why this is important:
'Browsers (and proxies) use a cache to reduce the number and size of HTTP requests, making web pages load faster. A web server uses the Expires header in the HTTP response to tell the client how long a component can be cached.'
The Yahoo article describes how to set the expires header in Apache, but I wanted to review how you would do the same in IIS7 for a designated folder or web site. Simple select the desired folder and the HTTP Response Headers action. After selecting the view you can add new headers, but for expires headers it is pretty easy. You can select the "Set Common Headers' option in the top-right corner.

This will display a dialog with two options, Enable HTTP keep-alive and Expire Web Content. Most likely the Expire Web Content checkbox is not selected. To enable the expires header check this box then set the expires time frame. For truly static content you should set this as far in the future as possible. You also have the option to enter a specific date. But most situations you will want to specify dozens or even hundreds of days.

Setting the expires header for static content can reduce the number of requests for each page by as much as 85% according to Yahoo's research. It is a very common oversight by most web masters to not configure this header for content. But setting this header adds a very tangible increase in performances as well as reducing the server load.