Keeping BreezeJS magic intact with SummerBreeze

If you´re using BreezeJS to create and manage your app BDO´s on the client-side, with Entity Framework as your ORM and you have 1:1 mappings between your server and client objects, then breeze works just like magic.magician

But if you´re using DTO´s instead of the complete server-side models, or if your app relies on a different ORM framework rather than EF, or simply because you don´t have any back-end database at all, then you know you have to do a bit of “plumbing” for BreezeJS to do its job.

That happens because currently out-of the box there is no ContextProvider implemented rather than the EFContextProvider (crafted for Entity Framework). BreezeJS uses metadata to describe server-side entity types and their relationships in order to automatically map and build your business objects as “first class” breeze entities on the client-side.

If no metadata is supplied the far as you can play with the awesome BreezeJS features, is the ability to have your client side queries “translated” into valid linq queries against the IQueryable provided on the server.

This is like driving a Ferrari on a 20 mph speed limit zone.

The widely used approach is to create all the metadata by hand and include it in a model.js script file as you can see on the nodb sample.

There´s no problem at all with that but when you have quite a few business entities to create this process can turn into a real pain.

In order to overcome this situation and maintain the BreezeJS magic intact I´ve created SummerBreeze, a metadata generator library and entity creation client script to use with BreezeJS for no DB, no EF ORM or EF ORM with DTO scenarios (non 1:1 entity mappings).

With SummerBreeze the automatic entity type creation process on the client-side is kept alive.

Here are some nice features of SummerBreeze:

  • Simple inclusion – just add reference to the SummerBreeze assembly on the server and the summerbreeze.js script on the client.
  • Eazy bootstrapping – decorate your POCOS with attributes, pass the type of your datacontext or repository class that implements the ISummerBreezeDbContext interface to SummerBreezeContextProvider class, and use the summerbreeze.js script to create a generator instance to generate your entity types. Simple!
  • Property cherry picking – If you don´t want to serialize metadata from all your model´s properties, just select the ones you want by their name.
  • Wide coverage – Data Properties, Navigation Properties, Validation Properties and Unmaped Properties supported.
  • Compatibility – Can work with both EF scenarios and non-EF scenarios. It supports having both EFContextProvider and other metadata providers.
  • Entity saving – Both ways supported, not only entity creation.

I think this is a nice-to-have feature that the guys at IdeaBlade could implement on the next versions of BreezeJS. It´s a more consistent approach to what BreezeJS already does with EF, does not give you the impression that it is “tied” to a specific technology (which is not) but above all it maintains the productivity boosts that this library used us to.

SummerBreeze is available as a nuget package and you can get more information about this library at the github project site.

Go check it out.

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: }