RSS

Tag Archives: json

More Comprehensive Naming Convention

Indentation

Indentation

Indentation must be used if the line is associated with the previous line. When indentation is needed, use conventional indentation (one “Tab”).

Example 1:

<div id="content">
    <table>
        <tr>
            <td class="control_title">
            </td>
        </tr>
    </table>
</div>

Example 2:

public string indentation
{
    get
    {
        return _indentation;
    }
    set
    {
        _indentation = value;
    }
}

Wrapping Lines

Avoid lines longer than 120 characters. When an expression will not fit on a single line, break it with conventional indentation in new line.

Example:

string _xmlData = "<?xml version=\"1.0\"?>" + "\r\n" +
    "<!DOCTYPE ddtp=\"http://dtd.wctp.org/wctp-dtd-v1r1.dtd\">" + "\r\n" +
    "<wctp-Operation wctpVersion=\"wctp-dtd-v1r1\">" + "\r\n" +
    "<wctp-SubmitRequest>" + "\r\n" +
    "<wctp-SubmitHeader submitTimestamp=\"" + _timestamp + "\">" + "\r\n" +
    "<wctp-Originator senderID=\"application@chron.com\"/>" + "\r\n" +
    "<wctp-MessageControl messageID=\"001\"/>" + "\r\n" +
    "<wctp-Recipient recipientID=\"" + recipient + "@arch.com\"/>" + "\r\n";

 

Naming Convention (Server Code)

Identifier Naming Convention

Identifier Case Examples Rules
Comment Clear, short and descriptive.
Class PascalCase Person
BankVault
ImageSprite
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
Keep names simple and descriptive.
No underscores.
Nouns.
Method(Private) PascalCase with “_” prefix _UpdateScore(…)
_UpdateUrl(…)
_UpdateID(…)
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Verbs.
Method(Public) PascalCase UpdateScore(…)
UpdateUrl(…)
UpdateID(…)
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Verbs.
Method for Ajax (Private and public) PascalCase following text “Ajax” SavePeopleAjax
GetPropertyAjax
_DeleteGroupAjax
Method for ajax is a method that only called with ajax.
For private, prefix with “_”.
Common Method (Private and public) PascalCase following text “Common” GetStateCommon
_GetAnswerCommon
_SaveStateCommon
Common method is a method that could be use in different controllers/pages.
For private, prefix with “_”.
Namespace PascalCase Chronicle.IT.BasicFunctions
Chronicle.IT.Ftp
Chronicle.IT.Xml
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Use $lt;company_name$gt; as root.
Interface PascalCase with “I” prefix IDisposable
IWidgetXml
IUserID
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Parameter camelCase recordID
personName
previousUrl
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Optional object type can be added. See “Object Type Naming Convention” section.
Property / Variable (Private) camelCase with “_” prefix _backColor
_internalXml
_userID
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores (except the prefix).
Optional object type can be added. See “Object Type Naming Convention” section.
Property / Variable (Public) PascalCase BackColor
InternalXml
UserID
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Optional object type can be added. See “Object Type Naming Convention” section.

Object Type Naming Convention

Additional object’s type can be added to precede some identifiers in order to distinguish the object type. If the object’s type is added, abbreviate the object type according to the following rules:

Object Type Abbreviated Object Type Examples
Array arr _arrBackColors
_arrInternalXml
arrUserID
String str _strBackColor
_strInternalXml
strUserID

 

Naming Convention (Client Code)

CSS & HTML

Identifier Case Examples Rules
Class dash-separated sort-column
portlet-header
portlet-content
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
Keep names simple and descriptive.
No underscores.
Nouns.
All lowercase.
HTML Element camelCase ddlPropertyType
txtName
Start with 3 letters of specified element.
HTML Element (For) PascalCase Group
Property
People.FirstName
For is html element generated by mvc html helper that bound to the specific property.

JavaScript

Identifier Case Examples Rules
Comment Clear, short and descriptive.
Parameter camelCase dashboardResult
peopleResult
currentUrl
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Optional object type can be added. See “Object Type Naming Convention” section.
Nouns.
Property / Variable (Private) camelCase with “_” prefix _savePreference
_currentUrl
_parent
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores (except the prefix).
Optional object type can be added. See “Object Type Naming Convention” section.
Nouns.
Property / Variable (Public) PascalCase SavePreference
CurrentUrl
Parent
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores (except the prefix).
Optional object type can be added. See “Object Type Naming Convention” section.
Nouns.

Json

Identifier Case Examples Rules
Name PascalCase Person
Status
Parent
Children
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
Keep names simple and descriptive.
No underscores.
Nouns.
Avoid using two words or more.
 
Leave a comment

Posted by on October 9, 2014 in General

 

Tags: , , , ,

ASP.NET Web API and OData’s Verbose JSON

OData v3 and Verbose JSON

Whenever you work with OData in ASP.NET Web API, the return result will be JSON format. It’s noteworthy to know that by default Web API will return new OData JSON format specified in OData version 3. For older OData, the JSON format is different. It has more ‘unnecessary’ placeholders. This old OData JSON is also referred as ‘Verbose JSON’. In short, there are two types of OData JSON:

  • OData v3 has new JSON format
  • Verbose JSON is used in older OData versions.

ASP.NET Web API (.Net 4.5) and Verbose JSON

As mentioned before, by default Web API will return new OData JSON.

To change this behavior, you can request Web API to return old OData JSON format by specifying ‘odata=verbose’ in Accept header. Below is the sample of jQuery Ajax call specifying verbose JSON:

$.ajax({
    url: "/api/Products",
    dataType: "json",
    accepts: { json: "application/json;odata=verbose" }
}).done(function() {
    // do work ...
});

How it Looks Like?

For the curious:

Verbose JSON

{
    "d" : {
        "results": [
            {
                "__metadata": {
                    "uri": "http://demos/Orders(10248)",
                    "type": "SampleModel.Order"
                },
                "ProductId": 10248,
                "Name": "Vgnon"
            }
        ],
        "__count": "1"
    }
}

OData v3 (and above) JSON

{
    "odata.metadata":"http://localhost:43111/api/$metadata#Products",
    "odata.count":"1",
    "value":
    [
        {
            "ProductId":2,
            "CreatedDate":"2013-06-10T23:53:26",
            "CreatedBy":0,"Name":"Camera"
        }
    ]
}
 
Leave a comment

Posted by on October 7, 2013 in General

 

Tags: , ,

JSON And C# Object Serialization Quick Reference

With JavaScriptSerializer, you can pretty much serialize / deserialize json-formatted string to any object and vice versa. Some of example below use class object, you can find this class object at the very bottom.

Here’s the quick reference:

string[] _testJsonStringArray = new string[8];
_testJsonStringArray[0] = "Id";
_testJsonStringArray[1] = "Firstname";
_testJsonStringArray[2] = "Lastname";
_testJsonStringArray[3] = "Age";
_testJsonStringArray[4] = "Job Description";
_testJsonStringArray[5] = "Address";
_testJsonStringArray[6] = "Email";
_testJsonStringArray[7] = "Hometown";

// Serialize Output:
// ["Id","Firstname","Lastname","Age","Job Description","Address","Email","Hometown"]
IEnumerable _testJsonList = new List() {
    "Id", "Firstname", "Lastname", "Age", "Job Description", "Address", "Email", "Hometown"
};

// Serialize Output:
// ["Id","Firstname","Lastname","Age","Job Description","Address","Email","Hometown"]
IEnumerable> _testJsonNestedList = new List>()
{
    new List()  {
        "31", "Test"
    },
    new List(){
        "12", "Also Test"
    }
};

// Serialize Output:
// [["31","Test"],["12","Also Test"]]
Person _testJsonClass = new Person()
{
    Firstname = "Alexander",
    Lastname = "The Great",
    Age = 99,
    JobDescription = "Eat and sleep",
    Address = "11 NoAddress St",
    Email = "alexander.thegreat@thegreat.com",
    Birthday = new DateTime(1999, 1, 1),
    Hometown = "Nowhere"
};

// Serialize Output:
// {"Firstname":"Alexander","Lastname":"The Great","Age":99,"JobDescription":"Eat and sleep","Address":"11 NoAddress St","Email":"alexander.thegreat@thegreat.com","Birthday":"\/Date(915170400000)\/","Hometown":"Nowhere"}
IEnumerable _testJsonClassCollection = new List()
{
    new Person() {
        Firstname = "Alexander",
        Lastname = "The Great",
        Age = 99,
        JobDescription = "Eat and sleep",
        Address = "11 NoAddress St",
        Email = "alexander.thegreat@thegreat.com",
        Birthday = new DateTime(1999, 1, 1),
        Hometown = "Nowhere"
    },
    new Person() {
        Firstname = "Smith",
        Lastname = "The Great",
        Age = 88,
        JobDescription = "Shopping and coding",
        Address = "12 NoAddress St",
        Email = "smith.thegreate@thegreate.com",
        Birthday = new DateTime(1980, 1, 1),
        Hometown = "Somewhere"
    }
};

// Serialize Output:
// [{"Firstname":"Alexander","Lastname":"The Great","Age":99,"JobDescription":"Eat and sleep","Address":"11 NoAddress St","Email":"alexander.thegreat@thegreat.com","Birthday":"\/Date(915170400000)\/","Hometown":"Nowhere"},{"Firstname":"Smith","Lastname":"The Great","Age":88,"JobDescription":"Shopping and coding","Address":"12 NoAddress St","Email":"smith.thegreate@thegreate.com","Birthday":"\/Date(315554400000)\/","Hometown":"Somewhere"}]
Building _testJsonClassContainCollection = new Building()
{
    Rooms = new List() {
        "401",
        "213",
        "523"
    }
};

// Serialize Output:
// {"Rooms":["401","213","523"]}
IEnumerable _testJsonClassCollectionContainCollection = new List()
{
    new Building() {
        Rooms = new List() { "White", "Blue", "Red" }
    },
    new Building() {
        Rooms = new List() { "A23", "23C", "G34" }
    }
};

// Serialize Output:
// [{"Rooms":["White","Blue","Red"]},{"Rooms":["A23","23C","G34"]}]
NestedBuilding _testJsonClassNestedList = new NestedBuilding()
{
    Rooms = new List>() {
        new List() { "Blue Room", "Orange Room", "Gray Room" },
        new List() { "Hot Room", "Cold Room", "Warm Room" }
    }
};

// Serialize Output:
// {"Rooms":[["Blue Room","Orange Room","Gray Room"],["Hot Room","Cold Room","Warm Room"]]}

And here’s the classes I used:

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public int Age { get; set; }
    public string JobDescription { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
    public DateTime Birthday { get; set; }
    public string Hometown { get; set; }
}

public class Building
{
    public IEnumerable Rooms { get; set; }
}

public class NestedBuilding
{
    public IEnumerable> Rooms { get; set; }
}
 
1 Comment

Posted by on December 1, 2011 in General

 

Tags: , ,

System.Web.Script.Serialization.JavaScriptSerializer

In my earlier post and here, I make use of System.Web.Script namespace for its JavaScript serialization. Worth noting that in order to use the namespace, we will need to add the following references:

  • System.Web
  • System.Web.Extensions
 
1 Comment

Posted by on September 19, 2011 in General

 

Tags: , , ,

JSON Array Deserialization in C# With Extension Method

After my first post about Json Serialization and Deserialization, I quickly realize I also need to deserialize object from Json array. Well, the previous code doesn’t work on deserializing Json array. My Json array looks like this:

[ { "firstname": "Alexander", "lastname": "Smith", "email": "asmith@company.com" }, { "firstname": "George", "lastname": "McAllen", "email": "gmcallen@company.com" } ]

The code for deserializing Json array is:

public static List<T> FromJsonArray(this string s)
{
    javaScriptSerializer = new JavaScriptSerializer();

    javaScriptSerializer.Deserialize<List<T>>(s);
}

It pretty much works the same way, only difference is instead of using just T, I use List<T> as return type. Everything else is still the same.

 
3 Comments

Posted by on May 11, 2011 in General

 

Tags: , , ,

JSON Serialization and Deserialization in C# with Extension Method

Starting its 3.5 framework, .Net has already support JSON object serialization from System.Web.Script.Serialization.JavaScriptSerializer namespace.

Please note that the code below is an extension method to add ToJson() method to my object.

public static class JsonExtensionMethod
{
    public static string ToJson(this object o)
    {
        System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        return jsonSerializer.Serialize(o);
    }

    public static T FromJson<T>(this string s)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        return serializer.Deserialize<T>(s);
    }
}

The usage is pretty simple and straight-forward. All we need to do is create JavaScriptSerializer instance and call its Serialize method. The method takes object type as its parameter which mean, you can pass all types that derive from System.Object.

To deserialize it, we use Deserialize method of JavaScriptSerializer class.

According to Scott Gu’s post, System.Web.Script.Serialization.JavaScriptSerializer is obsoleting, but will still be available in few versions to come.

Beside System.Web.Script.Serialization.JavaScriptSerializer, you also can use new System.Runtime.Serialization.DataContractJsonSerializer class

 
3 Comments

Posted by on May 10, 2011 in General

 

Tags: , , ,

Return JSON Data Type in ASP.NET MVC for Jquery Ajax Call

I have this javascript (jquery) code to call a url, “Home/Weather”, that will return JSON data type.

function GetWeatherCondition()
{
    $.ajax({
        url: "Home/Weather",
        dataType: "json",
        success: function (data) {
            alert(data.avgWindDeg);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + " - " + errorThrown);
        }
    });
}

And this is my Weather controller:

public JsonResult Weather()
{
    string urlWebService = "http://i.wxbug.net/REST/Direct/GetObs.ashx?la=41.7233&lo=44.7928&&ic=1&api_key=xxxx";
    string urlWebServiceResponse = "";

    System.Net.WebClient weatherClient = new System.Net.WebClient();
    urlWebServiceResponse = weatherClient.DownloadString(urlWebService);

    return Json(urlWebServiceResponse, JsonRequestBehavior.AllowGet);
}

As you can see, the Weather controller will return JSON object (JsonResult) and the javacsript code will load it in and display data.avgWindDeg. However, there is a problem when I run my javascript code. Instead of data.avgWindDeg, it returns undefined as you can see below:

The Weather controller is actually returning JSON object if I visit the url. So, what’s wrong here?

For some reason, the controller will need to return a JSON string instead of JSON object (JsonResult) for the jquery ajax call ($.ajax()) to understand. Changing my controller to ContentResult instead of JsonResult works like charm.

public ContentResult Weather()
{
    string urlWebService = "http://i.wxbug.net/REST/Direct/GetObs.ashx?la=41.7233&lo=44.7928&&ic=1&api_key=xxxx";
    string urlWebServiceResponse = "";

    System.Net.WebClient weatherClient = new System.Net.WebClient();
    urlWebServiceResponse = weatherClient.DownloadString(urlWebService);

    return Content(urlWebServiceResponse);
}
 
3 Comments

Posted by on May 8, 2011 in General

 

Tags: , , , ,

 
%d bloggers like this: