Using Twitter API 1.1 with Twitterizer for C#

So, yesterday (June 11, 2013) we published an minor aesthetic update to our website. Shortly after publishing the update, we noticed the twitter feed on our homepage wasn’t working. We initially thought it was caused by the update, but it turns out that Twitter’s API 1.0 was ‘retired’ and version 1.1 of the API was introduced.

The new API requires that all requests be authorized (via OAuth) and served over HTTPS. This is similar to, but still more restrictive than, Facebook’s API because not even basic requests for public information can be done without authentication.

Continue reading

Correcting Dates That Have Been Serialized to JSON

The Problem

The issue with dates in JSON, is that whenever you serialize, say a C# DateTime object, the date comes out in an unexpected format. Observe the output when a date of June 10, 2013 8:45:43PM is serialized to JSON:

DateTime date = new DateTime(2013, 6, 10, 20, 45,43);
String jsonDate = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(date);
// jsonDate = "/Date(1370897143000)/";

In this post we’ll look at how to fix this so that the date can be displayed or manipulated properly in the front-end.

Continue reading

How To: Set No-Cache For IIS or Browser in MVC

The Scenario

Let’s say you have a grid on a page. You also have a “Refresh” button that when clicked, makes a jQuery AJAX call to a Controller’s  GetGridData() JsonResult method which get’s the data from the server and returns it in JSON format. You obviously want this data to be fresh each time you hit “Refresh” but alas, you notice the data is being cached and not updated. That’s not what we want at all!

Continue reading

Initializing Objects With Shorthand C#

Sometimes it is more efficient to create an Object, List, Array, or whatever with shorthand code rather than fully defining an object. If you have not heard of shorthand code, it is simply an object that is defined in one or two lines of code versus using several lines as you would normally do as a beginner or member of a larger team. Shorthand produces less lines of code, but it is not as easy to read (which may be a problem if you are on a team.)

Lets take a look at an example of an Object created in shorthand vs full:

Dictionary

Example 1

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};

Example 2

new Dictionary<String, String>(){{"class","GridControl"}}

MVC3: Returning JSON via JsonResult

Returning JSON in an MVC project is actually easier than one might think. Typically, this would be a job for the JavascriptSerializer utility, but with MVC you don’t need to bother with that. Simply define your Controller’s Action as a JsonResult instead of the normal ActionResult.

Example

public JsonResult GetUsers()
{
    Dictionary<String,String> users = new Dictionary<string,string>();
    users.Add("James Bond", "jb007@mi6.co.uk");
    users.Add("Bruce Wayne", "bruce@wayneenterprises.com");
    users.Add("Peter Parker", "pparker22909@yahoo.com");

    return Json(users, JsonRequestBehavior.AllowGet);
}

See how easy that was? instead of returning a View() object, we return a Json() object, passing in the object we want to serialize to JSON. It takes care of the rest and spits out a single line (unindented) of JSON.

More Information

MVC JSON: JSONResult & jQuery

Getting System Language and Country Information in C#

Retrieving System Language Data

The CultureInfo object contains all relevant information regarding the user’s system language. It includes many useful properties such as Name, TwoLetterISOLanguageName, DateTimeFormat, NumberFormat, KeyboardLayoutId and Calendar.

Accessing the CultureInfo object is simply achieved as demonstrated by the following example:

String twoLetterISOName = System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName; // en
String systemName = System.Globalization.CultureInfo.CurrentCulture.Name; // en-US 
String displayName = System.Globalization.CultureInfo.CurrentCulture.DisplayName; // English (United States)

Retrieving System Country Data

The RegionInfo object contains all relevant information regarding the user’s system country/location. It includes many useful properties such as Name, DateTimeFormat, ThreeLetterISOLanguageName, CurrencySymbol, CurrencyEnglishName,  and Calendar.

Accessing the RegionInfo object is simply achieved as demonstrated by the following example:

String countryName = System.Globalization.RegionInfo.CurrentRegion.Name; // United States
String currencyEnglishName = System.Globalization.RegionInfo.CurrentRegion.CurrencyEnglishName; // US Dollar
String currencyEnglishName = System.Globalization.RegionInfo.CurrentRegion.CurrencySymbol; // $
this.cboCountry.SelectedValue = System.Globalization.RegionInfo.CurrentRegion.ThreeLetterISORegionName; // USA

JSON + C# Objects: Serializing and Deserializing

What’s it for?

JSON is great for storing large amounts of data into a single string. Facebook and a host of other major services store, serve and consume JSON as their primary means of data communication. With JSON you can actually deserialize an object such as a custom MyCustomer object and save it directly as JSON.

Serializing a C# Object into JSON

Serializing an object to JSON can be accomplished with just two lines of code. In the following example, we look at how to serialize a custom UserPreferences object:

UserPreferences preferences = new UserPreferences();
//set some values

//serialize
System.Web.Script.Serialization.JavaScriptSerializer serializer = new JavaScriptSerializer();
String JSONdata = serializer.Serialize(preferences);

From here, we are now ready to do all sorts of cool things with JSON. Please note that said cool things are outside of the scope of this post, so I will leave it to you to explore.

Deserializing JSON back into C# Object

Deserializing JSON back in an object is also easily accomplished in just two measly lines of code (actually, it can be done in 1 line.) In the following example, we deserialize the JSON equivilant of our UserPreferences object back into a C# object.

JavaScriptSerializer serializer = new JavaScriptSerializer();
UserPreferences preferences = serializer.Deserialize<UserPreferences>(JSONdata);

Many examples on deserializing JSON to C# Objects will tell you to use DeserializeObject() instead, but this gives you an Object object which then has to be casted to our UserPreferences object. If you already know what type of Object the JSON data is, the method outlined above is the way to go.