ASP.NET – JSON – Serialization and Deserialization

I was looking around for a simple example which would just do a object serialization to a JSON format, and then deserializing back to the original object. I found few examples on MSDN, but did seem to be too long to try. Here I’ve given a simple code which would make your understanding easy, and simpler.

Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.

What is JSON?

JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.

Okay, I understood a little about JSON. Give me an example!

I know an example will get your understanding much better. Below is a simple example of how an object can be expressed in JSON notation. Let’s take a classical example of a Person object, and expressing myself as an object.

{
   “firstName”: “Rakki”,
   “lastName”:”Muthukumar”,
   “department”:”Microsoft PSS”,
   “address”: {
      “addressline1”: “Microsoft India GTSC”,
      “addressline2”: “PSS - DSI”,
      “city”: “Bangalore”,
      “state”: “Karnataka”,
      “country”: “India”,
      “pin”: 560028
   }
   “technologies”: [“IIS”, “ASP.NET”,“JavaScript”,“AJAX”]
}

In the above example, address is another object inside my Person, and technologies is an array or strings.

Express this as a simple .NET class, please!

Here is a simple example:

public class Address
{
    public string addressline1, addressline2, city, state, country;
    public int pin;
}

public class Person
{
    public string firstName, lastName, department;
    public Address address = new Address();
    public string[] technologies;
}

I get it. Now what? JSON Serialization / Deserialization?

I’m sure you do not want me to write what is serialization, and deserialization here. I’ll touch upon how to use System.Web.Script.Serialization.JavaScriptSerializer to convert an existing object into a JSON string.

JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Rakki";
p1.lastName = "Muthukumar";
p1.department = "Microsoft PSS";
p1.address.addressline1 = "Microsoft India GTSC";
p1.address.addressline2 = "PSS - DSI";
p1.address.city = "Bangalore";
p1.address.state = "Karnataka";
p1.address.country = "India";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

string str = js.Serialize(p1);

Above code just creates a Person object, and assign some values. Look at the last line where we are actually doing a serialization – means dumping the contents of the object to a JSON notation. Below is the string produced by the above code:

{"firstName":"Rakki","lastName":"Muthukumar","department":"Microsoft PSS","address":{"addressline1":"Microsoft India GTSC","addressline2":"PSS - DSI","city":"Bangalore","state":"Karnataka","country":"India","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}

It is the same as how we defined the object before – but in a single line. Now, you have successfully converted your object into a JSON string.

Now how do I deserialize it?

Before going into how to deserialize it, let’s just understand when you might want to deserialize the object. Classical example is a JSON object returned from a web service, or from your client side javascript code, and you will be able to deserialize it in the server side to use the received object.

Person p2 = js.Deserialize(str);
Response.Write(p2.lastName);

p2.lastName would contain “Muthukumar” if your deserialization works fine. I suggest you to use the Deserialize method since it will reduce the type casting you might be doing if you use DeserializeObject() method which returns a System.Object.


Originally Posted: http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx
By Rakki Muthukumar – Last Edited: 30 Jan 2009

Adding groups to the ASP.NET DropDownList control

Introduction

The ASP.NET DropDownList class doesn’t support option groups. (Presumably because it would break the ListItem paradigm that Microsoft has used for all their list orientated controls).

A grouped drop down list

However, it is possible to add basic option group functionality by inheriting from DropDownList and overriding the RenderContents() method. This technique for adding optgroups is fully compatible with ViewState.

Code

public class DropDownListX : DropDownList
{
    public void AddItemGroup(string groupTitle)
    {
        this.Items.Add(new ListItem(groupTitle, "$$OPTGROUP$$OPTGROUP$$"));
    }

    protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
    {
        if (this.Items.Count > 0)
        {
            bool selected = false;
            bool optGroupStarted = false;
            for (int i = 0; i < this.Items.Count; i++)
            {
                ListItem item = this.Items[i];
                if (item.Enabled)
                {
                    if (item.Value == "$$OPTGROUP$$OPTGROUP$$")
                    {
                        if (optGroupStarted)
                            writer.WriteEndTag("optgroup");
                        writer.WriteBeginTag("optgroup");
                        writer.WriteAttribute("label", item.Text);
                        writer.Write('>');
                        writer.WriteLine();
                        optGroupStarted = true;
                    }
                    else
                    {
                        writer.WriteBeginTag("option");
                        if (item.Selected)
                        {
                            if (selected)
                            {
                                this.VerifyMultiSelect();
                            }
                            selected = true;
                            writer.WriteAttribute("selected", "selected");
                        }
                        writer.WriteAttribute("value", item.Value, true);
                        if (item.Attributes.Count > 0)
                        {
                            item.Attributes.Render(writer);
                        }
                        if (this.Page != null)
                        {
                            this.Page.ClientScript.RegisterForEventValidation(
                                this.UniqueID, 
                                item.Value);
                        }
                        writer.Write('>');
                        HttpUtility.HtmlEncode(item.Text, writer);
                        writer.WriteEndTag("option");
                        writer.WriteLine();
                    }
                }
            }

            if (optGroupStarted)
            {
                writer.WriteEndTag("optgroup");
            }
        }
    }
}

Usage

To add the class to your project, simply copy and paste the code into a class file.

You will probably need to add the following line to the section of your web.config. The line gives ASP.NET another namespace to search when it’s resolving the controls in your pages. The namespace needs to match the one that you used for your DropDownListX class.

<add tagPrefix="asp" namespace="YourNameSpace.Goes.Here" />

Once that’s been done you can use the control directly within an ASPX page. The control will operate exactly like a normal DropDownList, except that you can also add groups to it.

<asp:DropDownListX ID="ddlxSomething" runat="server" />

To add grouped items to the control you will need to use the inherited Items.Add() method and our new AddItemGroup() method. (Databinding will still work but then you don’t have an easy way of adding the groups).

this.ddlx.AddItemGroup("Administrators");
foreach(User u in administrators)
{
    this.ddlx.Items.Add(u.Name, u.Id);
}

this.ddlx.AddItemGroup("Users");
foreach(User u in users)
{
    this.ddlx.Items.Add(u.Name, u.Id);
}

Caveats

You can’t add an item with a value that matches the special group value: $$OPTGROUP$$OPTGROUP$$. Of course, if the group value isn’t “unusual” enough you can always change it.


This Article was taken from: http://ignatu.co.uk/articles/Adding_groups_to_the_ASPNET_DropDownList_control/
Last modified: 26 June 2011.

The code is based on this code by Jeff Putz.

c# UK postcode splitting

To maintain consistency with user inputted data, i wrote this small method in order to normalise UK post codes into the standard format.

The logic is as follows:

  1. Convert all the letters to their uppercase variant.
  2. Strip out any character that isn’t letter or a number using regular expressions and remove all spaces from the string.
  3. Split the post code using the substring method. We call this method twice, so we can get the first and last segments of the post code and insert a space before the last 3 characters.

The code:

public string fixPostCode(string postCode)
    {
        postCode = postCode.ToUpper(); //Convert all letters to upper case
        Regex r = new Regex("(?:[^a-z0-9 ]|(?&lt;=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
        postCode = r.Replace(postCode, String.Empty).Replace(" ", "");

        return  postCode.Substring(0, postCode.Length - 3) + 
			" " + postCode.Substring(postCode.Length - 3);
    }

You will need to include the following namespace into your class:

System.Text.RegularExpressions;

Go ahead and test it. Try an input string of something like: “M£$£^%£$£££66£$%££££&A)£$££^£%$(^P” and see what happens ;). N.B: You should get, “M6 6AP” as output.

Uploading a file via FTP C#

As web developers we all communicate with FTP servers. Desktop applications such as, my personal favourite, FileZilla allow us to manage our files between our PCs and the Server. But the downside is that a user needs to be present to select which files to upload, and to initiate the transfer process.

In many occasions, such as one I faced at work, we need a way of uploading a file to an FTP server without a user having to manually go about doing it. Wouldn’t it be great if we can write into our applications, a method automating the process? Well, the .NET framework allows you to do just that.

The FtpWebRequest class as part of the System.NET namespace, allows us to connect and upload flat files (eg text files, csv files etc) to an FTP server. The example shown below is one usage of the FtpWebRequest class. I put this method in it’s own class so that I could use it at various points throughout my project without having duplicate code.

The class:

using System;
using System;
using System.IO;
using System.Net;
using System.Text;

/// &lt;summary&gt;
/// Simple static class for uploading a file to an FTP server.
/// &lt;/summary&gt;
public static class fileUpload
{
    public static string uploadFile(string file)
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/myfile.txt");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("username", "password");

        // Copy the entire contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader(file);
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        // Upload the file stream to the server.
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        // Get the response from the FTP server.
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        // Close the connection = Happy a FTP server.
        response.Close();

        // Return the status of the upload.
        return response.StatusDescription;

    }
}

Basic Usage:

This can be used at any stage in the project without the need of creating a new object, since both the class and the method are defined as static.

fileUpload.uploadFile(myfile.txt);

A better implementation may to be pass the connection and file destination variables as parameters to the uploadFile method, so that the code can be used in a static context with different FTP servers. If anyone would like to know how to achieve this drop a comment below, however this code should get you well on your way 🙂

Source: http://msdn.microsoft.com/en-us/library/ms229715.aspx