What do you get when combining EF5, Web API, Bootstrap, jQuery, Breeze, Knockout, Sammy, Require and SignalR into a single MVC 4 app ? Behold SuperSPA Template.

Hello Dear Reader,

This is my first post of 2013 so I want it to have a special creativity flavor. :)

SPA´s or Single Page Apps are really the buzz words of the moment, so after being inspired by John Papa´s Pluralsight video, I decided to create my own SPA template for VS 2012.

You are probably wondering…wait isn´t there a SPA Template delivered with the ASP.NET Fall 2012 Update? Yes and it´s awesome! But it doesn´t have all the technologies mentioned in the video as well as others like SignalR, Breeze, Bootstrap, etc that I bring in.

Say hello to SuperSPA Template! A responsive SPA app that works on all modern HTML 5 browsers and devices.

SuperSpa Template

SuperSpa Template

The user story behind the template (the Photo BlurZ! app) is very simple. It´s a blurred images sharing site where users can not only search and download those images (so called blurz) as well as contribute to the gallery by uploading their own.

What it´s interesting about this SPA is that all data changes are processed in real-time, that is to say if you open 2 browser windows and user in window 1 uploads an image or changes the image ratings, user in window 2 will immediately see those changes. How cool is that? ;)

Also because it makes heavy use of local caching, the app is quite fast and server round-trips only happen when absolutely necessary or when the internal entity change detection mechanism tells it to do so.

Enjoy!

First Hello World on a Win8 App? Don´t bump into execUnsafeLocalFunction.

15 days since I installed Win8 Pro RTM on my Asus G74SX and let me tell you, I absolutely LOVE it! Super fast boot times, fluid and responsive design, Hyper-V is just that delicious cherry on top of the cake and if like me you´re a keyboard shortcuts and run command freak, you´ll love the new desktop mode without a start button.

As the installation went out so well, I thought it was now time to “shout” my first Hello World with a Windows 8 App, so I fired up Visual Studio 2012 Ultimate, and after File > New Project > Templates > Other Languages, I selected the JavaScript Blank App template.

With the help of MSDN Roadmap a Hello World was almost as quick as blinking an eye. The only thing that made me a little reluctant was when I decided to pull the the jQuery lib from Nuget, included it in my project and after hitting F5 started having errors like “Unhandled exception at line 2031 JavaScript runtime error: Unable to add dynamic content”.

This means that I’d just “bump” against the new Windows 8 security model that prevents “unsafe” dynamic DOM injections when using either innerHTML and outerHTML properties or the document.write method. jQuery comes with lots of checks for browser compatibility when bootstrapping that make use of these, so the error occurrence had a point there.

How does one solve this?

Fortunately, Microsoft provided the method execUnsafeLocalFunction so that we can wrap our “unsafe” code in order to step over this security validation.

Like this example below:

<div id="dynamicDiv"></div>
MSApp.execUnsafeLocalFunction(function () {
    document.querySelector("#dynamicDiv").innerHTML = "<a>This is a DOM injected link</a>";
});

After some googling around I found this “Win8 ready” jQuery lib, which already has the execUnsafeLocalFunction in place and I´m sharing it here so that unlike me, dear reader, you don´t hurt your head when this bump happens. ;)

The final work was kind of a fancy CSS 3 animated menu. See ya next time!

Hello World Fancy Menu

Hello World Fancy Menu

An overview of my MSc thesis and maestroo – an immersive sensing tool

Well it´s no secret to anyone, especially those following my activity that I am finishing my Master´s degree in Computer Engineering and currently coding and writting my thesis, which is being developed at the research unit SITI in Universidade Lusófona under the coordination and guidance of PhD Paulo Mendes and Professor Bruno Batista.

All my work integrates another project called CitySense and was inspired by the concept of Cooperative Sensing Systems, which are nothing more than large-scale distributed systems, hosted on mobile devices, that work in a collaborative way, sensing the environment and our interactions with it, whether they are between people or between people and their surroundings.

The term cooperative arises from the fact that these mobile sensing systems can share sensing data between them (i.e. combining gps with accelerometer and gyroscope for accurate location and position) and by doing so they are not only allowing a more precise inference over the collected data but also diminishing the burden of power constraintability (aka battery-life) over a single sensing device.

If you google on the issue you´ll find a ton of papers on this matter, so probably you´re asking what was my motivation behind this? It´s simple, allowing this systems to share, besides sensor data, the sensors themselves, in such a way that if I want to incorporate a sensor from another device onto mine, i can literally do it in an easy and straightforward way.

Now besides this, as maestroo (the name of the software) abstracts what a sensor really is, we can build an entire app having sensors of all kinds to share, “real” ones, like accelerometers, gps, light, temperature, etc and what we call “virtual”, that can be really anything ranging from an output of a software that measures a company kpi´s, to a feed reader, to camera images, to an audio stream, you name it, as long as it can come down the wire, the software will know how to handle it.

Maestroo is entirely built on C# and runs on every platform that can support it. Currently is working on Windows Phone, Android with mono for android, windows and linux workstations with the help of mono project and in the future will be developed for iOS using monotouch and micro-framework based boards, like the netduino.

One of the main challenges of building a distributed system like this is trying to avoid code changes, when you move from a platform to another or else it will look like your coding a different application everytime.

So besides the precious help of mono there were other technologies that made this happen, TinyIoC as the name suggests, a small dependency resolver / injection container, protobuf.net, google´s engine for object serialization implemented for .net and working on almost every platform and vici coolstorage for handling sqlite database operations also multi-platform support.

For the video above I´ve built a simple MVC 4 SPA to make use of the sensed data in a more visual way and used some javascript libraries that helped a lot like KnockoutJS for MVVM and declarative bindings support, KinectJS for HTML 5 Canvas API drawings and animations and last but definitely not least, JQuery, which needs no introductions.

You can also find more information about the technologies used in here.

This is still a work in progress, so enjoy…

LiteIoC

As probably everyone else out there I don´t like to be part of the wheel reinventers club, but sometimes, when you can´t beat them…join them.

In the process of coding for my Masters thesis, which involves having fun with mobile devices and embedded programming on microcontrollers like my NetDuino board, I really needed a super micro, tiny, lightweight…you name it…IoC container specifically crafted for the .Net Micro Framework.

I thought, “this will be an easy task as there are many IoC libraries out there”…Yes…but not for Micro Framework.

The only one I found that seemed to fit my needs had a strong dependency on another 3rd party library for AOP , but when you have only 64k to spend for code storage, optimization clearly becomes the word of the day.

So I took some time to code a very small and simple IoC container that had just the features I needed:
- Lightweight
- Simple Setup
- Singleton “lazy” container
- Constructor and parameters injection
- Named based registration

Say hello to LiteIoC.

Structural Patterns #5 Façade

Objective: Provide a higher level interface to a large and complex set of classes, simplifying the way clients make use of use those subsystem objects.

Appropriate: Abstraction / Refactoring scenarios

Participants:

  • Facade- Knows which subsystem classes are responsible for a request and delegates client requests to appropriate subsystem objects.
  • Subsystem classes- Have no knowledge or reference to the facade, implement subsystem functionality and handle work assigned by the Facade object.

Usage: Very High.

Example: The StateService class provides usefull info about an US State, such as average temperature on corresponding State cities.

UML:
Façade UML Diagram

Snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Facade
{
    class Program
    {
        static void Main(string[] args)
        {
            StateService _stateService = new StateService();
            var temperature = _stateService.AverageStateTemperature("CT");

            if(temperature == -100)
                Console.WriteLine("Invalid State code. Please try again.");
            else
                Console.WriteLine(@"The average city temperature for CT state is:
                                  {0} degrees Farenheit.", temperature);

            Console.Read();
        }
    }

    /// <summary>
    /// The Façade Class that 'hides' all the complexity behind getting an average US State cities temperature
    /// </summary>
    class StateService
    {
        CityInfo _weatherService = new CityInfo();
        Calculator _mathService = new Calculator();

        public int AverageStateTemperature(string state)
        {
            int result = -100;

            List<int> temperatureList = new List<int>();

            _weatherService.GetCityTemperatures(state).ForEach(x => temperatureList.Add(Int32.Parse(x.Split(':')[1])));

            if (temperatureList.Count > 0)
                result = _mathService.GetAverge(temperatureList);

            return result;
        }
    }

    /// <summary>
    /// The CityInfo 'Subsystem Class' class
    /// </summary>
    class CityInfo
    {
        public List<string> GetCityTemperatures(string code)
        {
            List<string> cities = new List<string>();

            switch (code)
            {
                case "CT":
                    cities.AddRange(new string[] {"Bridgeport:60", "Bristol:65",
                                                  "Danbury:70", "Derby:64",
                                                  "Groton:63", "Hartford:62",
                                                  "Meriden:61", "Middletown:67",
                                                  "Milford:70", "New Britain:70",
                                                  "New Haven:69", "New London:68",
                                                  "Norwalk:70", "Norwich:64",
                                                  "Shelton:65", "Stamford:70",
                                                  "Torrington:70", "Waterbury:70",
                                                  "West Haven:70", "Winsted:70"});
                    break;
                case "ME":
                    cities.AddRange(new string[] {"Auburn:67", "Augusta:68",
                                                  "Bangor:70", "Bath:71",
                                                  "Belfast:69", "Biddeford:64",
                                                  "Brewer:68", "Calais:65",
                                                  "Caribou:62", "Eastport:68",
                                                  "Ellsworth:68", "Gardiner:68",
                                                  "Hallowell:68", "Lewiston:68",
                                                  "Old Town:68", "Portland:64",
                                                  "Presque Isle:70", "Rockland:65",
                                                  "Saco:66", "South Portland:67",
                                                  "Waterville:68", "Westbrook:69"  });
                    break;
                default:
                    break;
            }

            return cities;
        }
    }

    /// <summary>
    /// The Calculator 'Subsystem Class' class
    /// </summary>
    class Calculator
    {
        public int GetAverge(List<int> numbers)
        {
            return numbers.Sum() / numbers.Count();
        }
    }
}

Structural Patterns #4 Decorator

Objective: Dinamically assign aditional responsabilities to an object.

Appropriate: Whenever you need to extend an object´s behaviour at runtime through another class (mixing  polymorphism and delegation) .

Participants:

  • Component - Interface for objects who´s responsabilities can be extended dynamically.
  • ConcreteComponent - The concrete object to which aditional behaviours (responsabilities) can be attached.
  • Decorator - Has a reference to a Component object and defines an interface that conforms to Component´s interface.
  • ConcreteDecorator - Adds responsabilities to the component.

Usage: Medium.

Example: The ToolBoxShop adds the possibility for someone to buy and use a tool.

UML:

Decorator UML Diagram

Snippet:

 1: using System;
 2: using System.Collections.Generic;
 3: using System.Linq;
 4: using System.Text;
 5:
 6: namespace Decorator
 7: {
 8:     class Program
 9:     {
 10:         static void Main(string[] args)
 11:         {
 12:             //create tool
 13:             var hammer = new Tool();
 14:             //can´t use it it´s not bought
 15:             hammer.Use();
 16:
 17:             // Buy tool (extend it´s behaviour) , then you´ll be able to use it.
 18:             var shop = new ToolBoxShop<Tool>(hammer);
 19:             shop.Buy();
 20:             shop.Use();
 21:
 22:             Console.ReadKey();
 23:
 24:         }
 25:     }
 26:
 27:     /// <summary>
 28:     /// Component abstract class
 29:     /// </summary>
 30:     /// <typeparam name="T"></typeparam>
 31:     abstract class ToolBox<T>
 32:     {
 33:         public static int NumTools { get; set; }
 34:
 35:         public abstract void Use();
 36:     }
 37:
 38:     /// <summary>
 39:     /// ConcreteComponent Class
 40:     /// </summary>
 41:     class Tool : ToolBox<Tool>
 42:     {
 43:         public double Price { get; set; }
 44:
 45:         public Tool()
 46:         {
 47:
 48:         }
 49:         public override void Use()
 50:         {
 51:             if(NumTools > 0)
 52:                 Console.WriteLine("You are using {0} tool(s).", NumTools);
 53:             else
 54:                 Console.WriteLine("You haven´t got any tools yet! ");
 55:         }
 56:     }
 57:
 58:     /// <summary>
 59:     /// Decorator abstract class
 60:     /// </summary>
 61:     /// <typeparam name="T"></typeparam>
 62:     abstract class Decorator<T> : ToolBox<T>
 63:     {
 64:         private ToolBox<T> _tools;
 65:
 66:         public Decorator(ToolBox<T> tools)
 67:         {
 68:             _tools = tools;
 69:         }
 70:
 71:         public override void Use()
 72:         {
 73:             _tools.Use();
 74:         }
 75:     }
 76:
 77:     /// <summary>
 78:     /// ConcreteDecorator Class
 79:     /// </summary>
 80:     /// <typeparam name="T"></typeparam>
 81:     class ToolBoxShop<T> : Decorator<T>
 82:     {
 83:           // Constructor
 84:         public ToolBoxShop(ToolBox<T> tools)
 85:             : base(tools)
 86:         {
 87:         }
 88:
 89:         public void Buy()
 90:         {
 91:             NumTools++;
 92:         }
 93:
 94:
 95:         public override void Use()
 96:         {
 97:             base.Use();
 98:         }
 99:     }
 100:
 101:
 102: }

Structural Patterns #3 Composite

Objective: Tree form object hierarchical composition.

Appropriate: Whenever you need to create a data structure with groups of objects.

Participants:

  • Component - Declares the interface for objects in the composition and implements default behaviour for the interface common to all classes, as appropriate.
  • Leaf - Leaf object (has no children) in the composition and defines the behaviour for primitive objects in the composition.
  • Composite - Defines the behaviour for components with children, stores child components and implements child-related operations in the Component interface.
  • Client- Manipulates objects in the composition through the Component interface.

Usage: Medium / High.

Example: The AggregatorTree is a custom generic hierarchical collection of cars according to their price.

UML:
Composite UML Class Diagram

Snippet:

 1: using System;
 2: using System.Collections.Generic;
 3: using System.Linq;
 4: using System.Text;
 5:
 6: namespace Composite
 7: {
 8:     class Program
 9:     {
 10:         static void Main(string[] args)
 11:         {
 12:             var root = new AggregatorTree<Car> { Node = new Car("Expensive Cars") };
 13:             root.Add(new Car("Bentley"));
 14:             root.Add(new Car("Lamborghini"));
 15:
 16:             var branch = root.Add(new Car("Cheap Cars"));
 17:             branch.Add(new Car("Fiat"));
 18:             branch.Add(new Car("Daewoo"));
 19:
 20:             var car = new Car("Affordable Cars");
 21:             root.Add(car);
 22:             root.Remove(car);
 23:             root.Add(car);
 24:
 25:             AggregatorTree<Car>.Display(root, 1);
 26:
 27:             Console.ReadKey();
 28:         }
 29:     }
 30:
 31:      /// <summary>
 32:     /// Generic Composite class 
 33:     /// Has a constraint (type T must implement the IComparable interface)
 34:     /// </summary>
 35:     /// <typeparam name="T">Child type</typeparam>
 36:     class AggregatorTree<T> where T : IComparable<T>
 37:     {
 38:         private List<AggregatorTree<T>> _children = new List<AggregatorTree<T>>();
 39:
 40:         // Add a child tree node
 41:         public AggregatorTree<T> Add(T child)
 42:         {
 43:             var newNode = new AggregatorTree<T> { Node = child };
 44:             _children.Add(newNode);
 45:             return newNode;
 46:         }
 47:
 48:         // Remove a child tree node
 49:         public void Remove(T child)
 50:         {
 51:             //A little task parallel library here...
 52:             _children.ToList().AsParallel().ForAll(treeNode =>
 53:                 {
 54:                     if (treeNode.Node.CompareTo(child) == -1)
 55:                     {
 56:                         _children.Remove(treeNode);
 57:                         return;
 58:                     }
 59:                 });
 60:         }
 61:
 62:         // Gets or sets the node
 63:         public T Node { get; set; }
 64:
 65:         // Gets AggregatorTree children
 66:         public List<AggregatorTree<T>> Children
 67:         {
 68:             get { return _children; }
 69:         }
 70:
 71:         // Recursively displays node and its children 
 72:         public static void Display(AggregatorTree<T> node, int indentation)
 73:         {
 74:             string line = new String('-', indentation);
 75:             Console.WriteLine(line + " " + node.Node);
 76:
 77:             node.Children.ForEach(n => Display(n, indentation + 1));
 78:         }
 79:     }
 80:
 81:     /// <summary>
 82:     /// Leaf Child Class
 83:     // Implements generic IComparable interface
 84:     /// </summary>
 85:     class Car : IComparable<Car>
 86:     {
 87:         private string _description;
 88:
 89:         // Constructor
 90:         public Car(string description)
 91:         {
 92:             this._description = description;
 93:         }
 94:
 95:         public override string ToString()
 96:         {
 97:             return _description;
 98:         }
 99:
 100:         // IComparable<Child> Member
 101:         public int CompareTo(Car other)
 102:         {
 103:             return (this == other) ? -1 : 0;
 104:         }
 105:
 106:     }
 107: }