Azure DocumentDB and C#

The goal of this post is to write a C# sample application to perform basic requests to Azure DocumentDB:  Create, Read, Update, Delete and Find documents.

You can find the code on my github: https://github.com/softwarejc/documentdb

Relational databases have been the dominant approach to store data for decades and they will probably be used for a very long time. However a lot of modern applications work with JSON, a format that does not fit naturally in a relational system.

NoSQL databases came to solve this problem and to improve the scalability of relational databases.  NoSQL also allows working with data that change fast without having to change the database.

There are different types of NoSQL databases:

  • Document stores: MongoDB, Azure DocumentDB
  • Key/Value stores: Riak
  • Column stores: Cassandra
  • Big data analytics: HDInsight, Hadoop

The focus of this post is the document store offered by Microsoft: Azure DocumentDB.

You can read more about MongoDB vs DocumentDB here: http://justazure.com/mongodb-vs-azure-documentdb/

Create a DocumentDB in Azure

The creation of a DocumentDB is very straight forward.

Scott Hanselman explains it very good in this video:

https://channel9.msdn.com/Blogs/Windows-Azure/Create-DocumentDB-on-Azure

You can read the about pricing information here:

http://azure.microsoft.com/en-us/pricing/details/documentdb/

How to use DocumentDB with C#

DocumentDB officially supports the following programming languages:

  • .NET
  • Node.js
  • Javascript
  • Python
  • Java

We will be using .NET C# 6.

The first thing that we have to do is to add a Nuget package that will do part of the job for us: Microsoft.Azure.DocumentDB:

Nuget

Continue reading

AngularJS and SignalR

The goal of this post is to connect and use SignalR from AngularJS. All the code is available in GitHub.

All code is available here: GitHub Link

The application used in this post allows to add tasks to a collaborative list of tasks to do. The application displays a list with all the tasks pending to do and also allows to remove them from the list. SignalR will push the notification “newTask” and “taskDone” to all connected users.

Feel free to get the code from github and run the application in more than one place (different tabs in your explorer) to see how SignalR synchronizes all of them.

The simplicity of the application allows to focus on the goal of this post: SignalR and AngularJS.

This is a screenshot of the running application.

Screenshot of the signalR and angularJS app.

SignalR Hub

The first thing that we need is to configure the OWIN startup, we need this class in our project:

[assembly: OwinStartup(typeof(Startup))]
namespace AngularJS_SignalR
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // SignalR
            app.MapSignalR();
        }
    }
}

The signalR hub type is “INotesCallbacks”, this interface defines the callbacks that the hub can make to the connected clients.

    // Client callbacks
    public interface INotesCallbacks
    {
        // Notify note added
        Task BroadcastNewNote(Note newNote);
        // Notify note removed
        Task BroadcastRemoveNote(int noteId);
    }

The hub also implement the interface “INotesCalls” this interfaces defines the hub methods that clients can call.

    // Client calls
    public interface INotesCalls
    {
        // Add note
        Task AddNote(string note);
        // Get all notes
        IEnumerable<Note> GetAllNotes();
        // Remove note
        Task RemoveNote(int roomId);
    }

This is the implementation of the hub:
Continue reading

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

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