1 2 3 4 5 6 7 8 9 10 11 12

JSON.NET

05/08/2014

JSON.NET by James Newton-King is the library for working with JSON in .NET. The following is a small guide for using JSON.NET. It is in no way a substitute for the full documentation.

To follow along obtain the JSON.NET package using NuGet and the Newtonsoft.Json dll will be added to your project's references. Alternatively download from the official website and add the reference manually.

Serialize An Object And De-serialize

Serialization is the process of translating data structures or object state into a format that can be stored - Wikipedia.

We will start our investigation with a very simple C# object and continue from there. As always, we are using the Dog class:

public class Dog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Breed { get; set; }
    public DateTime Birthday { get; set; }

    public int CalculateAgeInDays()
    {
        return (DateTime.Now - Birthday).Days;
    }
}

This is very simple class but might mirror something you need to serialize.

To start, let's create a dog and convert it to a string of Json (which I'll stop capitalising because it's a pain to type).

Dog dog = new Dog
{
    Id = 4,
    Breed = "Labradoodle",
    Name = "Baron Von Lassie",
    Birthday = Convert.ToDateTime("2013-01-07"),
};
string json = JsonConvert.SerializeObject(dog);

The string that we obtain is 'minified':

{"Id":4,"Name":"Baron Von Lassie","Breed":"Labradoodle","Birthday":"2013-01-07T00:00:00"}

As you can see all extraneous whitespace and extra line-breaks have been removed. This is ideal for data transfer objects such as a response from a Web Service, however if we're trying to present our data in a human readable way it's nicer to set Formatting.Indented like so:

...

What Is JSON?

04/08/2014

This is intended as a simple guide to JSON.

The more programming you do the more you hear about the data format "JSON".

However I've never actually used it until the changes to ASP.NET in vNext encouraged me to use it, basically the old XML format of the Web.Config is out and JSON is in (though you can swap back if I recall correctly).

What's In A Name?

JSON stands for "JavaScript Object Notation".

JavaScript Objects

The origin for this name is clear when you consider JavaScript objects. JavaScript objects are effectively dictionaries of key value pairs.

For those of you not familiar with a dictionary, the concept of JavaScript objects is as follows.

Let's describe your house:

var yourHouse = {
    number : 25,
    numberOfWindows : 20,
    name : "Honeysuckle Cottage",
    dog : new Dog(),
    openDoor : function() {
        alert("Hello!");
        }
};

Now this isn't the best way to express a JavaScript Object with methods (or at all for that matter) but it expresses that JS objects are just collections of names for things and their values.

...

POCOs from DataTable

30/07/2014

Edit: There were a few code errors in the original post, these have now been fixed.

For those of us still using Stored Procedures to retrieve information from a database it's useful to have a quick way to pass the resulting DataSet to a collection of POCOs (Plain Old CLR Objects).

A dataset in Visual Studio debugger

The problem is manual mappings are a pain and if they're spread around your data access logic lead to a maintenance headache. That's why this approach by Ricardo Rodrigues is so appealing. As soon as I came across it I decided to use it for all future data access logic on the application I maintain.

...

Create Table SQL Server

29/07/2014

Most guides on the SQL 'Create Table' command seem to only include the most basic arguments necessary to create a table with a few columns.

They don't go on to detail how to name constraints, create indexes and add foreign keys or similar.

If you're one of the (seemingly very few) people not using code/model-first Entity Framework I've posted this small snippet to help you. It includes how to:

  • Create and name a primary key.
  • Create and name a foreign key.
  • Create and name a default constraint.
  • Create and name a non-clustered index.
  • Cascade delete.

It does not detail how to create a composite non-clustered index (a non-clustered index on multiple columns).

So, the whole statement is here (note that having a column with the same name as the table will cause problems in EF database-first, the Question property will be renamed Question1):

CREATE TABLE Dog
        (
                Id              INT IDENTITY(-2147483648, 1) CONSTRAINT PK_Dog_Id PRIMARY KEY NOT NULL,
                Title           NVARCHAR(MAX) NULL,
                Name            NVARCHAR(MAX) NOT NULL,
                OwnerId         INT INDEX IX_Dog_Owner NONCLUSTERED 
                CONSTRAINT  FK_Dog_Owner FOREIGN KEY REFERENCES dbo.Owner(Id) 
                ON DELETE CASCADE,
                UserId          INT NOT NULL INDEX IX_Dog_User NONCLUSTERED 
                CONSTRAINT FK_Users_Dog FOREIGN KEY REFERENCES dbo.AspNetUsers(Id),
                CreatedDate     DATETIME2(0) NOT NULL CONSTRAINT DF_Dog_CreatedDate DEFAULT GETDATE(),
                ModifiedDate    DATETIME2(0) NOT NULL CONSTRAINT DF_Dog_ModifiedDate DEFAULT GETDATE(),
                RowVersion      ROWVERSION
        )

To run through a few things to note:

INT IDENTITY(-2147483648, 1)
There's an interesting debate about whether to use a GUID or integer for a primary key, I've gone with integer since to me it's more readable, but a quick Google will provide more than enough reading to the interested coder. I've seeded this primary key with the minimum value for INT, this means values from -2147483648 to 1 aren't wasted.

NVARCHAR(MAX)
NVARCHAR should generally always be used for text columns because it supports Unicode. VARCHAR supports ASCII.

...

You sank my battleship

02/07/2014

The Board Game Battleship

So this is probably one of those things that everyone else but me knows and I'm just going to reveal my ignorance, but as a note to myself for future and for those who don't know, here's how you remove the need for battleship debugging (scatter the code with breakpoints and hope you hit something) in Visual Studio.

This is the same as 'Pause On Exceptions' in a Javascript debugger such as that in Google Chrome and other debuggers, but if you are new to debugging and debuggers, it's not immediately obvious.

Break on all Javascript Exceptions

...
1 2 3 4 5 6 7 8 9 10 11 12