Chained null checks

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

Null-conditional operators is one of the features in C# 6 that will save the world from a lot of boilerplate code and a bunch of NullReferenceExceptions. It works as chained null checks!

Console.WriteLine(person?.HomeAddress?.City ?? "City unknown");

Note the null-conditional operator (?.) after person and HomeAddress, it returns null and terminates the object reference chain, if one of the references are null.

It is the same logic as the below code that you can use today.

if (person != null)
    person.HomeAddress != null)
{
  Console.WriteLine(person.HomeAddress.City);
}
else
{
  Console.WriteLine("City unknown");
}

The null-conditional operator will also make it easier to trigger events. Today it is required to reference the event, check if it is null before raising the event like so.

protected void OnPropertyChanged(string name)
{
  PropertyChangedEventHandler handler = PropertyChanged;

  if (handler != null)
  {
    handler(this, new PropertyChangedEventArgs(name));
  }
}

But the null-conditional operator provides a tread-safe way of checking for null before triggering the event.

PropertyChanged?.Invoke(this, args);

AJAX paging for ASP.NET MVC sites

When working with lists of data paging is a necessity, but trivial to implement in an ASP.NET MVC. The article Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application on www.asp.net makes use of the PackedList.MVC NuGet package and each step is described in detail. The implementation requires full-page refresh and does not make use of AJAX capabilities.

Let us extend the implementation and make full use of the AJAX capabilities.

Wrap the entire table in a div-tag and give it an id of content – it will enable us to replace the table without refreshing the entire webpage.

<div id="content">
    <table>
        ... removed for brevity
    </table>

    <div id="contentPager">
        @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
    </div>
</div>

Also wrap the @Html.PagedListPager in a div-tag and set the id to contentPager – it will let us alter the behavior of the click-event.

The below JQuery code attaches the anonymous function to every a-tag within the contentPager element and the function replaces the html within the content element with whatever is returned from the AJAX call.

$(document).on("click", "#contentPager a", function () {
    $.ajax({
        url: $(this).attr("href"),
        type: 'GET',
        cache: false,
        success: function (result) {
            $('#content').html(result);
        }
    });
    return false;
});

Move everything within the content element to a new view – let us call the new view List.

@model PagedList.IPagedList<ContosoUniversity.Models.Student>
@using PagedList.Mvc;

<div id="content">
    <table class="table">
      ... removed for brevity
    </table>

    <div id="contentPager">
        @Html.PagedListPager(Model, page => Url.Action("List", new { page }))
    </div>
</div>

Notice in above highlighted code, that the Action URL is changed to List, which is the name of the Action we need to add to the StudentController.

public ActionResult List(int? page)
{
    var students = from s in db.Students
                    orderby s.LastName
                    select s;

    int pageSize = 3;
    int pageNumber = (page ?? 1);
    return View(students.ToPagedList(pageNumber, pageSize));
}

The functionality of the new List Action is the same as in the existing Index Action. Just move all the code from the Index Action, so it just returns the default view as below.

public ViewResult Index()
{
    return View();
}

To wrap it up, the Index view needs to call the List Action to render the table in the Index view.

So the Index view ends up looking like this.

<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
    ViewBag.Title = "Students";
}
<h2>Students</h2>

@Html.Action("List")

@section scripts
{
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $(document).on("click", "#contentPager a[href]", function () {
                $.ajax({
                    url: $(this).attr("href"),
                    type: 'GET',
                    cache: false,
                    success: function (result) {
                        $('#content').html(result);
                    }
                });
                return false;
            });
        });
    </script>
}

That is it.

The solution is inspired by this StackOverflow question.

Download the complete solution, build and open the Student page.

Clean Domain Model via MongoDB Class Map

You can get rid of the dependency from the domain model to MongoDB assemblies, by utilizing Class Map functionality of the Official MongoDB C# Driver.

It is simple to use the property mapping, but you can also use AutoMap combined with one or more overriding mappings. That is often useful when using the MongoDB IdGenerators. However, how do you specify which to use without using attributes?

Below is a simple class with no dependencies – only dependent on the .NET Base Class Library:

public class Person
{
  public string Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Notice that not event an ObjecId is present.
To instruct MongoDB to generate a unique identifier for the Id property:

public class Person
{
  [BsonId]
  public string Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

But now there is a dependency on the BSonId attribute. We can remove it via a Class Map:

BsonClassMap.RegisterClassMap(cm =>
            {
                cm.AutoMap();
                cm.SetIdMember(cm.GetMemberMap(x => x.Id)
                  .SetIdGenerator(StringObjectIdGenerator.Instance));
            });

It is possible to use other data types as unique identifiers; just choose the correspond IdGenerator.

MongoDB auto-increment or sequence

MongoDB is a document database that does not have auto-increment or sequence functionality build-in, like e.g. SQL Server. Auto-increment or sequence numbers are often used to create a consecutive sequence of numbers used as order or invoice identifiers.

This is simple to achieve with MongoDB via the atomic operation $inc. If you use the Official MongoDB C# Driver the operation is exposed via the Update class.

To implement auto-increment or sequence functionality with MongoDB a document is required to keep the state of the sequence. The Id is the natural name of the sequence e.g. orderid and the value is the current counter value.

class Counter
{
  public string Id { get; set; }
  public int Value { get; set; }
}

Then getting the next ordered is done by executing the below statement:

var client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("myDatabase");
var counterCol = db.GetCollection("counters")

var result = counterCol.FindAndModify(new FindAndModifyArgs()
{
  Query = Query.EQ(d => d.Id, "orderId"),
  Update = Update.Inc(d => d.Value, 1),
  VersionReturned = FindAndModifyDocumentVersion.Modified,
  Upsert = true, //Create if the document does not exists
});