Azure DocumentDB – Point in time Backups

I have been reading and learning about DocumentDB the last month. I like it more and more…

I wrote a small DocumentDB C# 6.0 library that I want to share with you. The library offers a service to perform common requests to DocumentDB and a service to create and restore point in time backups.

A complete Microsoft backup solution is already planned: http://feedback.azure.com/forums/263030-documentdb

Wait… why did you write a DocumentDB backup solution if Microsoft said that they will implement it?

The reason why I wrote this quick and dirty point in time backup solution is that I want to use DocumentDB today and I don’t want to lose my data Sonrisa! I now that the database in Azure is safe but… what my application does something wrong and the data stored in azure gets damaged? I want to have the possibility to restore the data I had 1 hour ago, or yesterday, or last week…

In this first version only the documents are backed up.

You can find the library on my github:
https://github.com/softwarejc/documentdb-backups-csharp

Class Diagram

DocumentDB.Framework.classdiagram

How to use the library

We can extend the DocumentDBService class to define services to work with our collections:

Service definition:

image

How to use the service:

image

Fell free to leave me a comment and/or send me a pull request on Github!

JavaScript – first steps for a c# developer

The goal of this post is to compare some basics features of JavaScript with C#.

Objects Initialization

The initialization of JavaScript objects is similar to c# anonymous initialization.

// c# Anonymous initialization
var car = new
{
  Name = "myCar",
  PlateNumber = 12435
};
// JavaScript Initialization
var car =
{
  Name: "myCar",
  PlateNumber: 12435
};

Dynamic members

JavaScript objects can be dynamically expanded or updated. The behavior is like dynamic + ExpandoObjects in C#.

// c# Dynamic objects
dynamic car = new ExpandoObject();
car.Name = "myCar";
car.PlateNumber = 1234;
// JavaScript objects
var car = {}
car.Name = "myCar";
car.PlateNumber = 12435;

Classes and object oriented programming

JavaScript is a function oriented language. This means that classes in JavaScript are fairly different to classes in c#.

A class in JavaScript looks like a function. We need to use the keyword ‘this’ inside a function to define fields and methods of our class and the keyword ‘new’ to create instances. The function itself is the constructor of the class.

// c# class
Car myCar = new Car("myCar", "12345");

class Car
{
  public Car(string name, string plateNumber)
  {
    this.Name = name;
    this.PlateNumber = plateNumber;
  }

  public string Name { get; set; }
  public string PlateNumber { get; set; }

  public void Move(object position)
  {
    // move
  }

  private int Speed = 50;
}
// JavaScript class
var car = new Car("myCar", 12345);

function Car(name, plateNumber) {
  // public
  this.name = name;
  this.plateNumber = plateNumber;
  this.move = function (position) { /* move*/ }

  // private
  var speed = 50;
}

Properties

The previous javascript code is not creating properties because they have no getter and setter, if we need the getter and setter methods we need to use the following special syntax. This syntax also allows to define read-only properties.

// private backing field
var _name;
// property with public getter and setter
Object.defineProperty(this, "name", {
  get: function() { return _name; },
  set: function(value) { _name = value; }
});

Static methods and fields

Static members needs to be added dynamically to the class function:

// Define static field
Car.wheels = 4;
// Create instance
var myCar = new Car("myCar", 12345);
// Use static field
var test = myCar.wheels; // ERROR, static methods cannot be called from an instance
var test = Car.wheels; // OK

Prototype and inheritance

Prototype is an object contained by all classes. We can be extended dynamically this object (like all objects in JavaScript) with data and methods that will be accessible from our class.

Car.prototype.wheels = 4;
Car.prototype.move = function(position) { /* move*/ };

Inheritance in JavaScript is implemented changing the prototype of the child class. Let’s create a class “Car” that should have “Vehicle” class as base class:

function Vehicle(...) {
...
}
function Car(...){
...
}
Ferrari.prototype = new Vehicle();

What’s new in C# 6.0

I just installed Visual Studio 2015 Preview on a Windows 10 tech. preview, the first thing I wanted to try out was C# 6.0.

Source code

VisualStudio2015 in Windows10

VisualStudio 2015 in Windows10

The are a lot of videos and posts on internet about the new features of C# 6.0. The goal of this post is to test them by myself and share my impressions. I will use this post in the future as a personal reference for C# 6.0 new features.

C# 6.0 new feautures

This is the list of new features I have collected so far:

  • Getter only auto properties
  • Auto-Initialization of properties
  • Calculated properties with body expressions
  • Null conditional operators ?.
  • Operator nameof()
  • Strings projections
  • Exceptions filters
  • Await in catch and finally
  • Index initializers

I wrote a small sample class that I will use as an example to test the new features.

This is the C# 5 sample class:

using System;

namespace ConsoleApplication1
{
    public class Person
    {
        public Person(string name, int age)
        {
            if (name == null)
            {
                throw new NullReferenceException("name");
            }

            Name = name;
            Age = age;
            Id = GetNewId();
        }

        public string Name { get; set; }
        public int Id { get; private set; }
        public int Age { get; set; }

        public event EventHandler Call;

        protected virtual void OnCall()
        {
            EventHandler handler = Call;
            if (handler != null) handler(this, EventArgs.Empty);
        }

        public int GetYearOfBirth()
        {
            return DateTime.Now.Year - Age;
        }

        public JObject ToJSon()
        {
            var personAsJson = new JObject();

            personAsJson["id"] = this.Id;
            personAsJson["name"] = this.Name;
            personAsJson["age"] = this.Age;

            return personAsJson;
        }

        #region Get new person id

        private static int lastId;

        private static int GetNewId()
        {
            lastId++;
            Logger.WriteInfo(string.Format("New Id = {0}", lastId));
            return lastId;
        }

        #endregion
    }
}

Applying C# 6.0 new features to a C# 5.0 class:

Now lets go throw the list of new features and apply them to our sample class:

Getter only auto properties

We can remove “private set” from read-only properties, properties with only a “setter” can be initialized only from the constructor or with auto-initialization.

public int Id { get; }     

Auto-Initialization of properties

Using auto initialization we can auto initialize the Id property calling a method. It is also possible to set a default value to editable properties:

public int Id { get; } = GetNewId();    
public int Age { get; set; } = 18;    

Calculated properties with body expressions

It is common to have a lot of single line calculated properties or methods on our code. In lambda expressions it was already possible to write only the value to return. Now this is also possible in normal methods:

Our “GetYearOfBirth” method can be re-write like this:

     
public int GetYearOfBirth => DateTime.Now.Year - Age;

Note that if the method has not parameters we can also avoid the parentheses.

Null conditional operators ?.

Continue reading

WPF – State machine and ICommand

The goal of this post is to test the usage of MVVM Delegate commands together with a state machine.  You can read more about the state machine pattern here, and about commands here.

WPF allows to bind a command to some controls, the ICommand interface has two methods:  one that executes an action and one that returns  a Boolean indicating if the command can be executed or not.

E.g. Command bound to a button: When the button is clicked the action defined within the command is executed, when the command cannot be executed the button is disabled.

This is the ICommand interface.

public interface ICommand {
	event EventHandler CanExecuteChanged;
	bool CanExecute(object parameter);
	void Execute(object parameter);
}

I will use the Microsoft PRISM 5 Delegate ICommand implementation and the stateless state machine.

ICommand + State Machine Trigger

On a state machine there are states and triggers, within one state some triggers are forbidden and other are allowed, when a trigger is fired the state machine could change its state.

Our commands shall be associated to a trigger, the behaviour should be:

  • CanExecute: Shall return true only if the associated trigger can be fired on the current state.
  • Execute: Shall fire the associated trigger, the machine could change its state.

The coffee machine

The application that we will write will be a very simple coffee machine with only one type of coffee:

States

  1. Idle: Machine waiting to be used.
  2. With money: The user entered some money but is not enough to get a coffee.
  3. Can get coffee: The user entered enough money to get a coffee.
  4. Preparing coffee: The coffee is being prepared.
  5. Coffee ready: The user can take the coffee.
  6. Refunding money: The machine is returning the money to the user.

Triggers

  1. Insert money: Fired when the user insert money.
  2. Refund money: Fired when the user press the refund money button and after the user takes the coffee.
  3. Enough money: Automatically fired when the user inserted enough money.
  4. Prepare coffee: Fired when the user select a coffee, (our machine is that simple that has only one…)
  5. Coffee prepared: Automatically fired when the coffee is prepared.
  6. Take coffee: Fired when the user takes the coffee.
  7. Money refunded: Automatically fired when the machine refunded the money.

The diagram

image

Implementation

States

    public enum CoffeeMachineState
    {
        Idle,
        WithMoney,
        CanSelectCoffee,
        PreparingCoffee,
        CoffeeReady,
        RefundMoney
    }

Triggers

    public enum CoffeeMachineTrigger
    {
        InsertMoney,
        RefundMoney,
        PrepareCoffee,
        TakeCoffe,

        // Automatic triggers
        EnoughMoney,
        CoffeePrepared,
        MoneyRefunded
    }

Configuration

        /// <summary>
        /// Configures the machine.
        /// </summary>
        private void ConfigureMachine()
        {
            // Idle
            this.Configure(CoffeeMachineState.Idle)
                .Permit(CoffeeMachineTrigger.InsertMoney, CoffeeMachineState.WithMoney);

            // Refund money
            this.Configure(CoffeeMachineState.RefundMoney)
                .OnEntry(RefundMoney)
                .Permit(CoffeeMachineTrigger.MoneyRefunded, CoffeeMachineState.Idle);


            // WithMoney
            this.Configure(CoffeeMachineState.WithMoney)
                .PermitReentry(CoffeeMachineTrigger.InsertMoney)
                .Permit(CoffeeMachineTrigger.RefundMoney, CoffeeMachineState.RefundMoney)
                .Permit(CoffeeMachineTrigger.EnoughMoney, CoffeeMachineState.CanSelectCoffee);

            // CanSelectCoffee
            this.Configure(CoffeeMachineState.CanSelectCoffee)
                .PermitReentry(CoffeeMachineTrigger.InsertMoney)
                .Permit(CoffeeMachineTrigger.RefundMoney, CoffeeMachineState.RefundMoney)
                .Permit(CoffeeMachineTrigger.PrepareCoffee, CoffeeMachineState.PreparingCoffee);

            // PreparingCoffee
            this.Configure(CoffeeMachineState.PreparingCoffee)
                .OnEntry(PrepareCoffee)
                .Permit(CoffeeMachineTrigger.CoffeePrepared, CoffeeMachineState.CoffeeReady);

            // CoffeeReady
            this.Configure(CoffeeMachineState.CoffeeReady)
                .Permit(CoffeeMachineTrigger.TakeCoffe, CoffeeMachineState.RefundMoney);

            this.OnTransitioned(NotifyStateChanged);
        }

StateMachine command factory

Continue reading

AngularJS – CRUD Data Grid III

The goal of this post is to extend the AngularJS CRUD Grid that we created in previous posts:

We will add now the following requirements:

  • # 1 Filter items.
  • # 2 Custom buttons: This will allow us to add button columns that will call the parent controller with the id of the button clicked and the associated item as parameter.

Results

Code is available on github: https://github.com/softwarejc/angularjs-crudgrid. Feel free to play with it, find errors and write improvements.

You can see a live demo here: AngularJS CRUD Grid III demo.

Filters:

All items

image

Items containing the letter ‘c’

image

Custom buttons:

image

Button click, callback that shows a popup:

image

Implementation

Continue reading

AutoMapper – Model/ViewModel mapping and validation

The goal of this post is to implement a base class to map and initialize view models using the domain object. This base class should make not only the mapping between the model and the view model but also the validation of the view model using the model annotations.

Each requirement will be implemented in two different base classes, the validation class will inherit from the mapping one as the domain object is needed to validate the view model. It makes sense to split the logic to keep the code cleaner and also to be able to use only the mapping functionality in case that we don’t need the validation.

Result

When this class is implemented we can implement our view models like this:

public class ItemViewModel : BaseEntityMapperViewModel<ItemViewModelItem>
{
    public int Id { getset; }
    public string Name { getset; }
}

The Model

public class Item
{
    [Key]
    public int Id { getset; }
 
    [MaxLength(200)] 
    [Index(IsUnique = true)]
    public string Name { getset; }
}

Sample of usage:

ViewModel – Model

My WebAPI controllers send and receive to the client a view model instance, when a instance needs to be updated in database it needs to be mapped to the domain first. This is because my domain services know nothing about view models:

// Update item
public void Put([FromBody]ItemViewModel updatedItem)
{
    if (!_itemsService.Update(updatedItem.MapToEntity()))
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

Model – ViewModel

When a WebAPI need to load a instance from database and send it to the client, it loads a domain instance that needs to be mapped to a view model:

// Read item by id
public ItemViewModel Get(int id)
{
    var item = _itemsService.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return ItemViewModel.MapFromEntity(item);
}

Implementation

Continue reading

ASP MVC – Template Overview

When a new MVC Web Application is created in Visual Studio a lot of files are added to the solution. The goal of this post is to provide a small overview of all these files, this overview should make easier to understand the MVC solution structure.

The files described here are the files created by default when you add a web project using the MVC template.

Create a a Web project:

New Web Project

Use the MVC Template:

MVC Template

This is the generated project:

MVC Template Project

ASP MVC Template Overview

Let’s start enumerating some created folders:

  • Content: CSS files with view styles. (Bootstrap)
  • Fonts: Some fonts required by the CSS files.
  • Scripts: JavaScript files. (JQuery)
  • Controllers: C# files with the code that is going to be run at the server side.

Now the rest of files and folders with some more details:

Views

This folder contains *.cshtml files. The Razor engine generates the views of our web application out of these files. Typically we will have a view or a group of views for each controller. This folder also contains a Web.config don’t confuse this one with the Web.config at the root of the solution. Razor engine is configured here.

Continue reading