Oct 1, 2012

Parsing JSON in a Windows Phone Application


I see questions regarding JSON parsing/deserializing almost everyday in Stackoverflow. Hence decided to write a blog post to show you how to easily parse JSON strings in Windows Phone applications.

***Please read entire blog for a complete overview before implementing in your applications***

I would like to divide this post into 2 categories.
One is, where you will have to parse a similar json data in many places in your application or you will use the parsed data in many instances of your code
Other is, you just parse the data once, get your values and no need of the data else where in your project i.e one time usage.

CASE I:

Step 1: Go to Json2Csharp site and paste either your entire JSON string or URL to the JSON and click on Generate button. This creates all the required classes for your JSON response.

I am taking this sample json data

{"MyBookList": [{"ID":5,"TYPE":"History","TITLE":"XYZbook","PRICE":"200","IMAGE":"Ekannoborti.jpg","DOWNLOADLINK":"http://www.amazon.com/"}],"success":3}

And here are the classes generated
public class MyBookList
{
    public int ID { get; set; }
    public string TYPE { get; set; }
    public string TITLE { get; set; }
    public string PRICE { get; set; }
    public string IMAGE { get; set; }
    public string DOWNLOADLINK { get; set; }
}

public class RootObject
{
    public List<MyBookList> MyBookList { get; set; }
    public int success { get; set; }
}
Now place this classes somewhere in your project, so that they are available in all the locations you require them.

Step 2: ( Here I am assuming that you get your json from a web service)
Make a web request to get the JSON response

WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("http://somedomain.com/xyz/myjson.aspx"));

And then in the response handler, use the following code to parse the data and convert into classes

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);

    foreach (var book in rootObject.MyBookList)
    {
         Console.WriteLine(book.TITLE);
    } }

There you go, you can play with the response classes and data bind them with the UI elements :)


CASE II:

Here as your requirement is one time parsing and one time usage, instead of storing them in unnecessary classes, we just wisely parse the data and get the task done.

Consider this sample,

String jsonData = @"{""MyBookList"": [{""ID"":5,""TYPE"":""History"",""TITLE"":""XYZbook"",""PRICE"":""200"",""IMAGE"":""Ekannoborti.jpg"",""DOWNLOADLINK"":""http://www.amazon.com/""}],""success"":3}";

And inorder to get the title of each book here

JObject obj = JObject.Parse(jsonData);
JArray jarr = (JArray)obj["MyBookList"];
string bookTitle = (string)jarr[0]["TITLE"]; //To get the title of First book
or
foreach(var item in jarr)
     Console.WriteLine(item["TITLE"]); //Gets the title of each book in the list

NOTE : For both the cases, I have used json.net for parsing the json data. You can get it from this Nuget package. And if you dont know how to install and use a Nuget package, Check Here
Hope it helps. Please dont forget to +1 or leave a comment.
Thank you
View Kishor Chandra's profile on LinkedIn

Jun 26, 2012

Upload image to Twitter from a Windows Phone Application

Here is a blog post for Windows Phone Application developers. In this blog post I will show you how to implement photo upload feature for Twitter from your Windows Phone Application.

If you want to implement basic text sharing functionality for Twitter(No photo or customized sharing), I would suggest to use ShareStatusTask and ShareLinkTask which makes the work much easier for the developers.But if you want to implement some customized sharing like photo upload, you need to put in a little effort. In this blog post, I will demo the photo upload feature with the help of the Hammock library.


Step 1: Install the latest version of Hammock library from Nuget, which helps in the implementation of Oauth process.


Step 2: Refer this blog post on How to implement Oauth authentication process for Twitter using hammock (The post may not be directly compatible with latest version of Hammock, check for any inconsistency).


Step 3: Obtain the required oauth tokens as specified in the above blog post from step 2.


Step 4: Post a sample tweet as specified in this blog post Post a Tweet on a User’s behalf

Step 5: After successfully completing all the above steps, now here is the code to upload a photo along with a tweet..
(Check the Twitter documentaion on Status Update with Media)

        private void PostImageButtonClick(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
            photoChooserTask.Show();
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                uploadPhoto(e.ChosenPhoto, e.OriginalFileName);
            }
        }

        public void uploadPhoto(Stream photoStream, string photoName)
        {
            var credentials = new OAuthCredentials
            {
                 Type = OAuthType.ProtectedResource,
                 SignatureMethod = OAuthSignatureMethod.HmacSha1,
                 ParameterHandling =OAuthParameterHandling.HttpAuthorizationHeader,
                 ConsumerKey = TwitterSettings.consumerKey,
                 ConsumerSecret = TwitterSettings.consumerKeySecret,
                 Token = TwitterSettings.accessToken,
                 TokenSecret = TwitterSettings.accessTokenSecret,
                 Version = "1.0a"
             };


             RestClient restClient = new RestClient
             {
                 Authority = "https://upload.twitter.com",
                 HasElevatedPermissions = true,
                 Credentials = credentials,
                 Method = WebMethod.Post
               };

               RestRequest restRequest = new RestRequest
               {
                    Path = "1/statuses/update_with_media.json"
                };

                 restRequest.AddParameter("status", textBoxNewTweet.Text);
                 restRequest.AddFile("media[]", photoName, photoStream, "image/jpg");

            restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
        }


        private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
        {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                //Success code
                }
        }



and the 4th parameter for .AddFile() should be taken care of(I have not considered other formats while doing this sample, you have to take care in your apps)
Note: If you like this Blog Post, Plz share this and Plz Upvote my answer in StackOverflow
View Kishor Chandra's profile on LinkedIn

Mar 17, 2012

Windows 8 Developer Camp in hyderabad by Microsoft India.


Windows 8 Developer Camp in hyderabad by Microsoft India.

It was the first ever developer camp on windows 8 and was excited to attend it. As it was an invite based event submitted two app ideas and fortunately got invitation for both.

Venue was The PARK hotel, somajiguda. Had a good time in The Park, well hosted and nice food as well. Registration was simple and directly went to the seminar hall. First session started with the Windows 8 consumer preview demo by Rajashekaran from Microsoft. After that had continuous sessions by other Microsoft techies like Sandeep Alur, Aditee gupte, Harish V etc. All the sessions are nice with useful samples and demos.


The features that impressed me in Windows 8 Consumer preview are The Metro style home screen and Metro style apps, faster app switching, integration of multiple technologies like C#, VB, C/C++, HTML5, CSS, JS etc into the WinRT metro application development. We were given access to the Visual studio 2011 beta version, which includes some cool new features like integration with Blend, Edit and continue in debugging, improved Team development, deeply integrated testing, Unit testing and I felt the best of all is the support for languages like CPP, HTML5, CSS, JS in VS (as if they are native .NET languages).

After the successful completion of the sessions, actual fun started at 6PM a nonstop 24 hour development and coding session of Windows 8 Metro apps. A big spacious seminar hall with well planned seating arrangement is provided to all the developers. Most of the people worked seriously on their own ideas. Some people worked as a team also. Eventhough its a continuous development session, there was no moment we felt bore. There were continuous efforts from microsoft team to cheer us and to encourage us. They arranged a funny Magic show, a nice music show by a guitarist and a yoga session on how to perform Mudras. 

One best thing other than the sessions is the food provided by The PARK, lunch, dinner, breakfast everything is good. We were provided with various kinds of snacks throughout the night. Microsoft also provided nice T-shirts for all the attendees along with a participation certificate.

Finally before the end of the Camp, we were asked to demonstrate our ideas on the stage. I have demoed two simple apps, one shows the public timeline of the twitter and another is a cocktail app, which got a good response from all. Microsoft team felt good with my presention and asked me to give the visual feedback about the event. Overall its a nice Metro journey with all surprises and memories. Btw, met some new friends from different companies. 

Mar 5, 2012

Papikondalu Tour @ Ravi marriage


 Hi everyone, had a nice 2 days trip to papikondalu and rampa waterfalls near rajamundry.
       All my office colleagues planned for a 2 days trip to papikondalu and rajamundry on the occassion of our beloved iphone developer Ravi. Prasad and co planned well and arranged a 40 seater super luxury bus for 31 persons and we started at 9.30 pm on friday (24 feb) and reached Rajamundry by 8 am nextday. Ravi arranged rooms in a lodge near kotipalli bus-stand in Rajamundry. After refreshing we reached the Papikondalu boat by 11.30am (3 hours lately).
       Boat journey on Godavari river was an Amazing experience for all of us. I was thrilled with the beauty of the Godavari and its surroundings. We all had fun. We reached Papikondalu by 4pm and had a halt at Perantalapalli . And while returning, in the evening the Godavari became much more beautiful and Sunset was so good. I spent some time sitting alone at the back of the boat by keeping my legs into the river. Wowwwwwwwwwwww its an amazing experience.
      Got down from the boat at 7.30 and from there went directly to the marriage reception at Rajamundry. we reached the lodge by 11pm. Slept for 3 hrs and again attended the marriage at 3am. Had some fun at the marriage venue after the marriage.
Sunday morning we started to Rampa chodavaram waterfalls at 7 from Rajamundry and reached by 9.30. Water falls are small but good for enjoyment. Water is pure and very cool. We were almost frozen with the chillness of the water. After spending around 2hrs there, we returned back to Hyderabad via Rajamundry, and reached Hyderabad by 4am on Monday.
And Ravi, we had a great time bcoz of You. We wish you a Happie married Life. :)