All posts by Vin

Betting on C# and Native for Cross Platform Mobile Development

If there are 2 languages that I consider the most important and versatile are C# and Javascript. We can not deny the omnipresence of Javascript and the web that powers it. It’s an obviously forgone conclusion that Javascript rules the world, mostly client side but also server side with NodeJS.
 
But what about C#? I believe C# is the only other language that can claim to be having an as wide reach as Javascript. Today it can run on desktop, mobile phones (with Xamarin), small devices and so forth. At this year’s Xamarin Evolve conference Scott Hanselman presented a talk titled “How C# Saved my Marriage, Enhanced my Career and Made Me an Inch Taller“.
 
So several months ago, I decided I needed to get in to mobile development, get the basics, fully focused on learning the end-to-end mobile development stack. Purely for the fun and a forward looking possible need at my job.
 
Why Xamarin?
 
I’ve been watching Monotouch and Mono for Android for the past couple of years and it was time to get to it. Xamarin has created something awesome for us, .Net developers, who can take their existing C# and .Net skills and target cross platform mobile development. It’s not a very smooth ride in the beginning, but as with anything, you will get over it and learn to have the challenging fun that follows. I think it’s worth it.
 
So why do I think Xamarin is a better direction for .Net and Web developers than going with a hybrid solution like Phonegap/Apache Cordova, Appcelerator, Icenium and a bunch of others? Well, I believe the ‘design and user focus’ is the answer. Native apps provide the best possible user experiences than any hybrid solution can. It will be years before the Web/HTML5 solution can match the native experience. At least that’s what I think. And I am saying that as a web developer with more than a decade and half of web experience. Now, this may not be the “one way” to do it all, and depending on your specific app requirements/cases, a hybrid solution or a pure native (objective-c or java for android) may be a better, cost-effective solution. There are a number of articles, blog posts on which solution is better suited for a given app-scenario, so I won’t get in to it.
 
For me, end user experience trumps everything in most cases. You’ve gotta be designing in the modern world for the end user. Go watch this fantastic talk by Billy Hollis titled “Design or Die: The Challenge to the Microsoft Developer Ecosystem“.
 
The key thing really is – build real native apps with native SDK for UI and do it using my beloved C# and .Net.
 
So I picked Xamarin. There was no where else for me to go. It was like the good old ASP.Net days, of taking something you already know and venturing in to a new direction and a new universe, with unknown challenges. So far, I am loving it. It’s been very transformative experience. I haven’t yet gone so far as to develop in F# with Xamarin. Someday!
 
One of the major challenges I had early on is to figure out how to lay out the solution, where should the reusable/decoupled pieces go, how does it work with server code etc. Finally I decided to go with Platform specific libraries (with code file reuse, and separate csproj file for each platform) than trying the ad-hoc, error-prone PCL (Portable Class Library). As of this writing, we are still waiting for Xamarin to provide full support for PCL, which I hear is coming very soon.
 
Sometimes you might run in to, “Oh yeah.. but wait, no…” experiences. Well, that’s normal.
Yes_But_no
 
Equipment:
 
First thing I needed was solid equipment, what could be better than a Macbook Air. The Mac mini is just mini, I want the full OS X experience while developing, plus portable. Takes getting used to, but I think, why not? So after the SAF (Spouse Acceptance Factor) was high enough, I bought this Macbook Air.
Paid $1158 with the apple insider promo code.
 
Product Image

 

Development setup:

On the Macbook Air, first you need to download and install XCode and iOS simulators from the Mac app store. Then, I’ve setup VirtualBox to host Windows 8.1 VM (link for a gotcha), where I can do all the server side/web-api/database work. Create 3 desktops (areas, a OSX concept) on the Mac side of the house, move the Windows to one desktop, Xamarin Studio to another, and Chrome browser on the third one. And then I get to use the sweet 3-figure gesture to move between them very smoothly with no friction. Then I setup all the keyboard shortcuts I know and love from Visual Studio, on there with the Xamarin Studio (F9, F10, F12 and the whole nine yards). I prefer to work with ‘Xamarin Studio on Mac‘ than ‘Visual Studio on Windows and use the Mac as build-host. It just feels faster. I use the Inconsolata font which is not as great as Consolas, but I can live with it.

 
Xamarin Links:
 
Here is a link roundup for the cool and productivity enhancing avenues/components for Xamarin. It’s like the .Net world has opened up new possibilities.
 
 

Restsharp – Fantastic library to decouple all your service calls using this component.

Servicestack – I love their serialization/deserialization (ServiceStack.Text), it’s the fastest, I am using it everywhere replacing everything else on server side web apis.

MvvmCross – a leading MVVM xplatform library for Xamarin

MvvmLight – MVVMLight comes to cross platform mobile apps

Monotouch dialog – check out this json based UI creation

Xamarin.Mobile – exposes a single set of APIs for accessing common mobile device functionality across iOS, Android, and Windows platforms.

Xamarin.Social – Share statuses, links, and images on Facebook, Flickr, Twitter and more.

Xamarin.Auth – A cross-platform API for authenticating users and storing their accounts.

Platform specific libraries for code reuse – PSL as opposed PCL (Full support for PCL in Xamarin is coming, still not there yet) – Use the same poco on client and server side for json serialization/deserialization – for clean and maintainable code

NativeCSS / Pixate – yes, write CSS to theme your native UI, win for us the web guys!!!

Google maps component for mapping solutions

ObjectiveSharpie – a very powerful binding definition generator for third party Objective C libraries to help provide APIs matching the .NET idioms and ensure delightful APIs.

Testcloud for testing – it’s an awesome testing solution

Native SignalR – Real time web for the native mobile apps

Signature pad (Imagine building paperless document signing app)

Enterprise grade barcode component

ProtoPad – great prototyping tool for UI, just like linqpad but for UI

http://components.xamarin.com/ has whole bunch of other useful components as well

With this stack, the stuff you can build is pretty much whatever you like. There is a short 1-2 weeks learning curve, but after that it’s a lot of fun.

There is a good chance, you will feel like this, after you finish writing your first app.
excited_dance
 
Hope that helps folks who want to get in the world of Xamarin and Cross platform mobile development.
 
Update: For a detailed post on why native UI and Xamarin is the way to go for XPlatform mobile development, read this fantastic blog post by Wally McClure
 
Happy coding !!!

Simple, easy way to avoid UI from freezing in Windows Forms / WPF apps

It’s always been a pain point to not have the UI freeze, when some long running background task is going on in Windows Forms or WPF applications. We’ve been used to using the infamous BackgroundWorker to achieve this, however with Task Parallel Library it’s so much succinct to manage this.

      Task.Factory.StartNew(() =>
      {
        return DoWork();
      })
      .ContinueWith(antecedent =>
      {
        try
        {
          UpdateViewWithResults(antecedent.Result);
        }
        catch (AggregateException ae)
        {
          ae.Handle((x) =>
          {
            MessageBox.Show(x.ToString());
            statusStrip1.Items[0].Text = "Done.";
            ViewerProgressBar.Visible = false;
            return false; // Let anything else stop the application.
          });
        }
      }, TaskScheduler.FromCurrentSynchronizationContext());

Very cool .Net, Javascript, Json and CSS libraries

Recently I’ve been using and reading about the following interesting libraries for .Net, Javascript, Json and CSS. There are tons of those these days out there. But this will be a list of ones I value most.

  1. OpenWebKitSharphttp://code.google.com/p/open-webkit-sharp/ – check this too – http://stackoverflow.com/questions/790542/replacing-net-webbrowser-control-with-a-better-browser-like-chrome/10097480#10097480
  2. JsonFx.Net – great library to work with Json in .Net – https://github.com/jsonfx/jsonfx
  3. microjs.com – dictionary of js libraries
  4. sugarjs – extends native objects with helpful methods – sugarjs.com
  5. http://emberjs.com/ – another databinding library, looks comprehensive, but I am sold on knockoutjs, I’ve looked at half a dozen binding libs, and to me knockout trumps everything else, just saying…
  6. fully functional, rich datagrids on the client side – http://datatables.net/
  7. do anything with lists – http://listjs.com/
  8. mediatizr – Responsive design support for older browsers – https://github.com/pyrsmk/mediatizr
  9. stroll.js – awesome looking css3 scroll effects – http://lab.hakim.se/scroll-effects/
  10. Superfast client side templating – HandleBarsJS
  11. Rich Data for Javascript apps – perfect for SPA (Single Page App)s that deal with Server side data – BreezeJS
  12. SPA template and client side app library – Single Page Apps done right – DurandalJS

Simple and basic CSS3 properties that change everything

By now the world has pretty much agreed upon the future of HTML5 and CSS3 – This is how new apps will be built, for the web and for multitude of other devices. There is no question native experience on a platform serves the best for the user, slowly but gradually apps are moving to the HTML5 model, primary examples being Facebook app, Netflix, USA Today, Financial times and several business/finance related apps.

CSS3 is awesome, it’s like magic. It suddenly makes your web app look cooler and less stressful. The biggest improvements over previous versions is the support for,

  1. Rounded Corners
  2. Box Shadows
  3. Text Shadows
  4. Gradients

Of course all the above are visible to the user only when they are viewing your app in a browser that supports these CSS3 properties. To lookup which properties are supported in which browser, take a quick CSS3 test.

I’ve been looking to refine the usage of these properties to make them look the best I can and come up with ideal values.

Here’s my current swatch for these properties.

  1. Rounded Corners – this is simple – at 10px border radius it looks like perfection, not more not less.
                -webkit-border-radius: 10px;
                -moz-border-radius: 10px;
                border-radius: 10px;
    
  2. Box Shadows – this is a little hard to get to, but with #999 a nice gray slightly blurred shadow, it seems close to perfect.
                -webkit-box-shadow: 3px 3px 10px 0px #999;
                -moz-box-shadow: 3px 3px 10px 0px #999;
                box-shadow: 3px 3px 10px 0px #999;
    
  3. Text Shadows – this is the trickiest part – because there’s more shadow real estate going on, and it’s harder if you have dark text on light color. This also depends on the background color surrounding the text, so adjust the colors according to your underlying theme.
    // light color text needs,
                -webkit-text-shadow: 0 2px 5px #333;
                -moz-text-shadow: 0 2px 5px #333;
                text-shadow: 0 2px 5px #333;
    // dark color text needs,
                color: #111;
                -webkit-text-shadow: 0 2px 5px #999;
                -moz-text-shadow: 0 2px 5px #999;
                text-shadow: 0 2px 5px #999;
    
  4. Gradients – I avoid them as much as I can, but when I need to I use saturated colors to compliment the darker one. Here’s an example of a glossy CSS3 icon using gradients.
    div.appIconCss
            {
                width: 48px;
                height: 48px;
                margin: 20px auto 0 auto;
                padding:5px;
                font-size: 2.3em;
                color: #ffffff;  
                -webkit-text-shadow: 2px 2px 5px #333;
                -moz-text-shadow: 2px 2px 5px #333;
                text-shadow: 2px 2px 5px #333;                   
                -webkit-border-radius: 10px 10px 10px;
                -moz-border-radius: 10px 10px 10px;
                background: -webkit-gradient(radial, 28.5 -47, 0, 28.5 0, 700,
    		        from(rgba(255,255,255,1)), to(rgba(255,255,255,0)),
    		        color-stop(10%, rgba(255,255,255,0.2)),
    		        color-stop(10.5%, rgba(140,140,140,0.2)),
    		        color-stop(13%, rgba(140,140,140,0)),
    		        color-stop(13.7%, rgba(255,255,255,0)),
    		        color-stop(17%, rgba(255,255,255,1))) #2E79AB;
                background: -moz-radial-gradient(28.5px -47px 45deg, circle farthest-side,
    		        rgba(255,255,255,1) 0%,
    		        rgba(255,255,255,0.2) 72%,
    		        rgba(140,140,140,0.3) 74.5%,
    		        rgba(140,140,140,0) 85%,
    		        rgba(255,255,255,0) 95%,
    		        rgba(255,255,255,1) 160%);
            }
    

 

Designing Error Messages

Error messages are an important part of an application. Generally each application/system has a collection of error messages stored somewhere (I would use a dictionary of some sorts). From a UX stand point it’s important to phrase and design error messages and dialogs, in a way that tells the user what ‘exactly‘ just happened. There’s no point in covering technical issues with a generic error message such as “Service unavailable“, when it doesn’t do anything to help the user take any action based on that information. Provide them with what to do when a service is not available. Is the internet connection not available? Is your web service down for maintenance? Is it a windows service on user’s machine that didn’t start correctly on reboot?

Technially it’s always possible to go that one extra mile to figure out and tell the user exactly what just happened and provide them with links to help documentation or provide useful actionable information immediately available, most times, right on the Error Dialog may be.

I recently got this Error dialog, when I was trying to activate a tool, I entered my credentials and bam, I got this error.

It could have been more specific, as in I entered my credentials wrong or the web service it used to authenticate is not available.

 

UI Design and Approach for Line of Business Apps

For any LOB (Line of Business) Application, User Interface Design can make or break the success of the application. In the recent years, due to the advent of mobile devices, great improvements in the Web technologies, the browsers and client side experience, there has been greater than ever emphasis on UI Design and usability than before. Users having used iPhones, iPads and Kinects come to expect similar intuitive experience when they are using any application, be it an internal enterprise app or public facing web applications.

I’ve been very inspired by Billy Hollis’ approach to Application development, ever since I first listened to his shows on the .Net Rocks podcast shows. He has a keen focus on User Experience and Prototyping.

Here’s a compiled list of links to his talks and presentations

User Engaged Prototyping with Billy Hollis

Billy Hollis on WPF and Silverlight

Bytes by MSDN: June 18 – Billy Hollis

Billy Hollis on Getting Smart with WPF – dnrtv

Billy Hollis: XAML for Developers Part One

Billy Hollis: XAML for Developers Part Two

Check out this nice application called Quince which has a treasure trove of UX Patterns

TDD, Unit Testing and Benefits

What is TDD?

From Wikipedia, quoting,

Test-driven development (TDD) is a software development processthat relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finallyrefactors the new code to acceptable standards. Kent Beck, who is credited with having developed or ‘rediscovered’ the technique, stated in 2003 that TDD encourages simple designs and inspires confidence.[1]

Test-driven development is related to the test-first programming concepts of extreme programming, begun in 1999,[2] but more recently has created more general interest in its own right.[3]

Programmers also apply the concept to improving and debugging legacy code developed with older techniques.

TDD Cycle

TDD Cycle

 

Although TDD doesn’t mean you write your tests first, test-first development relies on the process of writing a requirement to add a feature, functionality in the form of short unit-test, watching it fail first, then implementing the classes, methods and properties defined in the test, bit-by-bit, and then watching it pass, which is why it’s also sometimes termed as red-green (fail-then-pass) refactoring. Test-first or not, Test Driven Development makes Tests first class citizens of development process, rather than an after-thought.

 

Concerns and Benefits

There have been several cases against using TDD or Unit Tests in general, common concerns being,

  1. Oh, this means the developers have to spend extra time writing unit tests, which they could be spending on “actual” development adding “features”.
  2. Well, it’s going to either need more developers to make up for the time lost and increase project costs.
  3. So you are saying we don’t need QA anymore, if Unit Tests are going to take care of all the testing?
  4. and so forth…

Some benefits of Unit Testing in general,

  1. The Project is going to gain a lot more time actually spent on quality, although more time might be required upfront to ensure unit tests are written for as many cases possible. However, the confidence in the quality of the code will be high for each developer. They will be able to know a defect they fixed is not going to break something else, very quickly. Immediate feedback, less QA cycles.
  2. Cost associated with adding more developers is going to pay back once you have lesser QA cycles, immediate feedback on buggy code, lower long term maintenance and QA costs. It’s important not to conclude based just on the initial increase in development time and cost.
  3. Generally it’s not a good idea to add more developers just to write unit tests for code that’s being written by some other developer. Ideally each developer who implements a feature or functionality has to write his/her own unit tests, and then be peer reviewed for accuracy and design
  4. Unit tested and TDD code is likely to create and force automatic optimum design, also it’s going to help discover bugs in existing/legacy code – this is why it’s also sometimes called Design Driven Development. The API is going to evolve and emerge just enough to end up being optimum, on-demand design and avoid any upfront, grand ivory tower design that usually is a pattern in the Waterfall methodology.
  5. Unit tested code is more likely to create a sense of ‘care for the code’ from a developer’s standpoint, and not writing code ‘just to make things work’
  6. There could be more many more that I missed, please feel free to add.

Now, these benefits depend on how TDD is adopted and practiced and the results may vary on case by case basis. Also there are situations when writing unit tests for every part of the application is not feasible or possible. For example, UI testing, which is a whole another topic. For UI testing it is recommended to have Automated Coded UI tests, validating parts of the application that can not possibly be tested using Unit Tests.

Types of Testing

Generally there are 3 types of Testing areas. It’s important to know their differences and purpose.

  1. Unit Tests – focus on testing classes, methods and API in general, interacting with APIs of the various modules of the application. Goal is test functionality at a micro level and make sure each unit of code is accurately functioning as expected.
  2. Integration Tests – focus on testing multiple coherent components/modules of the application. Goal is to validate if they work together as expected. This might include Presentation layer interacting with Business logic / Middleware and databases.
  3. Automated/Coded UI Tests – focus on UI and how the user interacts with the application – test cases generally not covered by the Unit Tests or Integration Tests.

All the above 3 types of tests are known to significantly reduce cost, maintainance and resources for the Project.

Research and Case Study

To that point, a research was conducted by folks at Microsoft which weigh in costs development time vs benefits.

Quoting from that research whitepaper,

Test driven development has recently re-emerged as a critical enabling practice of agile software development methodologies. However, little empirical evidence supports or refutes the utility of this practice in an industrial context. Case studies were conducted with three development teams at Microsoft and one at IBM that have adopted TDD. The results of the case studies indicate that the pre-release defect density of the four products decreased between 40% and 90% relative to similar projects that did not use the TDD practice. Subjectively, the teams experienced a 15–35% increase in initial development time after adopting TDD.

Link to the WhitePaper (thanks to @jslicer for the discovery of this whitepaper)

Great article on several terminologies related to Test practices (Test first, BDD, TDD, Executable Specs etc)

 

Javascript: The Good Parts, Web Programming and Tools

Javascript: The Good PartsJavascript: The Good Parts, is the name of the one of the greatest book written on modern Javascript. Author Douglas Crockford who invented his own JSON spec and also invented JSLint explains why Javascript is not an inadequate language of the web after all. It’s good parts make up for anything that’s wrong or inconsistent. You just have to learn to know it.

If you skip the book, don’t miss this video of a presentation he gave at Google.

My first stint with Javascript was when I started my career in web development back in 1999, writing HTML, CSS and Javascript with Classic ASP on the server side. We worked through hoops to make things work on Netscape and IE (we had to worry about only two browsers back then, but more later on), then there were elaborate, error-prone hacky javascript files (document.getElementById all over the place) we included in pages to take care of client side validation, UI manipulation and XHR. Yes, all the good things of the web today were available to be used back then in the 1990s, especially with the MSIE browser. We just had to know to use it. AJAX was already there.

Since the arrival of modern javascript libraries like jQuery, made the life of a Javascript programmer so much easier. Letting you focus on “What to accomplish” more than “How to accomplish and bring it all together”. Which is great. It also provided a better separation of concerns, getting rid of inline event handling hooks and styling. The MV-VM Javascript library KnockoutJS is yet another tool in the kit, that has brought goodies like observable properties and arrays, viewmodels etc to the web programming arena. With appropriate use of jQuery Templates, you can get Silverlight/WPF like data-template and control-template like capabilities. This morning I discovered d3, this helps dealing with both DOM and SVG way easier.

I am excited how things are getting more and more standardized and easier to use with all the excitement around HTML5, CSS3 etc.

Now on to Tools. One of the areas where ‘Web Development’ lags behind compared to Desktop/Client development is Tools. Tools that are transparent, easy to use, provide context, help and do not stand between the developer and the end result. Historically all these deficiencies have scared away the transition of a VB developer in to the pure web programmer, and thus ASP.Net came in to prominence making the developers not think about javascript, html at all and live in the land of Server Controls, View States and Magical unicorns, in the name of productivity, RAD or whatever you want to call it. While I completely agree ASP.Net filled a void and served well it’s real purpose at the time, it also delayed the emergence of frameworks like ASP.Net MVC. I am speaking in the context of a Enterprise .Net developer here.

ASP.Net MVC brought the shine back to web development on the MS .Net stack. When you have complete control over your markup, scripting, styling, URLs, routing, views, controllers and models, you can have greater transparency and focus on “What you want to create”. Yet built on top of the same ASP.Net’s core foundation, which is solid and evolving with each new version.

Coming back to Tools, I am crazy about ‘Chrome Developer Tools’. It’s brilliant. Simply love the way Chrome is supporting developers by providing context based, transparent and easy to use information about what got rendered on the client and moving away from just relying on “view source”. All though IE-9 is trying to catch up, when you compare, Chrome is years ahead of IE-9.

Chrome Dev Tools Tabs

Learn more about ‘Chrome Developer Tools’ and dont’ miss the video to get a quick look at it.

JSFiddle

You might also want to use pure web-based tools like the awesome JSFiddle. For a full introduction and how-to guide for JSFiddle.Net, read this blog post by Ryan. I am using it on regular basis, when there is a need to create any client side UI development. Prototype it there, once it’s functional, bring the source code back to your application.

To sum it up, you always get good support from Visual Studio debugger and the VS tools to troubleshoot and inspect server side code, and VS does a splendid job of it. In VS2010, the Javascript intellisense and debugging support is great. However without an accompanying browser based Developer toolset your client side development is open to lost productivity, too many trial and error fixing sessions and frustration. This frustration eventually leads to a statement like “Ohh I hate javascript, html and this web development, Windows Forms/WPF/Silverlight development is so much better”. The important thing to note here is that it’s not the web development model that is difficult to deal with, it’s the tools, and the stateless nature of the web. So, you do need things like ‘Chrome Developer Tools’ to fill the gaps and make things happen quickly and efficiently. It’s not perfect, yet, but it will get there, if you use it, you’ll know what I mean.

I wish Visual Studio can provide all three in one place. The Browser Developer Tools, a playground to prototype client side features like JSFiddle and then great, easy to use, built-in Javascript debugging.

Happy web programming folks!

Useful Reference Samples for KnockoutJS

After I recently started using KnockoutJS, the awesome MV-VM Javascript library, I came across several samples which serve as a great reference for real-world scenarios to solve specific UI problems. Because it’s hard to get to when I wanted to take quick look at, thought of making a list. This is an evolving list, so will keep adding samples as I find them.

I am sure you will find them useful.

The reference samples are created by community and are mostly on the JSFiddle.net

  1. ObservableArray Manipulation, providing own mappings for ko.mapping Plugin
  2. Defining a customBinder
  3. Nested Comments Sample
  4. applyBindingsToNode, reapply bindings
  5. Data binding html element’s attributes like Title, Class etc
  6. Subscribe to property inside ObservableArray
  7. ChangedItemes and deltatracking to sent to server
  8. Undo/Redo quick initial sample
  9. Keep a track of selected items (checkbox list) on the client side

Creating handy shortcuts VS2010

There are several in-built keyboard shortcuts available in Visual Studio.

However, there are some actions that developers need shortcuts for, that are not available by default.

One of them is opening up “TFS Source Control Explorer” tool window. I typically attach Ctrl+Alt+S to this action.

Currently we have to open the Team Explorer, drill down to our team project, and then double click on the Source Control Explorer node in the Tree. This is time-consuming.

Here’s how to add Ctrl+Alt+S to “View TFS Source Control Explorer” to Visual Studio.

  1. Go to Tools -> Options -> Environment ->Keyboard
  2. On the right hand pane, filter the “Show commands containing” available commands by typing in “TFSSourceControlExplorer”
  3. Once it’s highlighted in the listbox below, click and focus on “Press Shortcut Keys” textbox
  4. Press Ctrl+Alt+S
  5. Click on the “Assign” button next to the textbox
  6. Hit OK
  7. Done

Another handy shortcut is to assign “Close command on the Currently open File”

Follow the same steps above and assign “Ctrl+W” – the reason I assign Ctrl+W is it’s already in our muscle memory to mean “Close currently open tab document” when we use it in pretty much all browsers. (FireFox, Chrome, IE)

Hope that helps.