Category Archives: .Net

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
});

Instrumentation presentation at Campus Days 2013

Campus Days 2013 logoI was fun to present today at Campus Days 2013 in Copenhagen, Denmark. The talk was about how to instrument software by using frameworks like TraceSource, EventSource, Event Tracing for Windows and how to perform post-mortem debugging via Visual Studio and PerfView.

Here is a great resource for enabling diagnostics in Azure.

Automatic Retry and Circuit Breaker made easy

Polly library logoIf you do not know Polly, you are missing out! I did not know about it until a couple of days ago and you properly never heard about it either, as this wonderful little library only has 63 downloads on NuGet at the time of writing.

Polly is an easy to use retry and circuit breaker pattern implementation for .Net – let me show you.
Start by specifying the policy – what should happen when an exception thrown:

  var policy = Policy
    .Handle<SqlException(e => e.Number == 1205) // Handling deadlock victim
    .Or<OtherException>()
    .Retry(3, (exception, retyCount, context) =>
    {
      // Log...
    });

The above policy specifies a SqlExeption with number 1205 or OtherException should be retried three times – if it still fails log and bobble the original exception up the call stack.

  var result = policy.Execute(() => FetchData(p1, p2));

It is also possible to specify the time between retries – e.g. exponential back off:

  var policy = Policy
    .Handle<MyException>()
    .WaitAndRetry(5, retryAttempt =>
      TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)
    );

Or the circuit breaker safeguarding against the same error occurs again and again if an external system is temporarily unavailable:

  var policy = Policy
    .Handle<TimeoutException>()
    .CircuitBreaker(2, TimeSpan.FromMinutes(1));

Go get it – I’m already using it :)