Ibraheem Osama Mohamed (ابراهيم اسامه محمد)

Welcome to my blog :)

Client Dynamic Application : Read remote text file (using Drop Box) in Windows 8 C# Application using Deserialization

with 3 comments

In the last post I explained how to read data from a remote text file hosted in Drop Box using Windows 8 JavaScript Application.
The idea behind this is that you can change the data displayed in your application by just changing the content of the text file that is hosted in the Drop Box.
This post is a special post for me of my friends

Lets start
1)Add a public text file in the public folder in drop box and name it quotes.json
1

2)Write the following JSON Data in the file
{“quotes”:[{ “Text”: “Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius — and a lot of courage — to move in the opposite direction”,
“By”: “Albert Einstein”, “Situation”: “Enter the situation”, “Date”: “2020” },
{ “Text”: “Imagination is more important than knowledge”, “By”: “Albert Einstein”, “Situation”: “Enter the situation”, “Date”: “2020” },
{ “Text”: “I Love Windows 8 and I Love JavaScript”, “By”: “Ibraheem Osama Mohamed”, “Situation”: “Thinking of ..”, “Date”: “2050” }]}

3)Close the file but think of the JSON First
A)We have a JSON object name quotes this object’s value is an array.
B)This array Contains 3 JSON values each value contains 4 objects Text , By , Situation and Date.

4)Now we want to display the application as following
1
5)So what we need is a ListView and make a very easy item template Text,By,Situation,Date

<ListView Name="DataListView" ItemsSource="{Binding}">
             <ListView.ItemTemplate>
                 <DataTemplate>
                     <StackPanel>
                         <TextBlock Text="Text :" Foreground="Red"></TextBlock>
                         <TextBlock Text="{Binding Text}"></TextBlock>
                         <TextBlock Text="By :" Foreground="Red"></TextBlock>
                         <TextBlock Text="{Binding By}"></TextBlock>
                         <TextBlock Text="Situation :" Foreground="Red"></TextBlock>
                         <TextBlock Text="{Binding Situation}"></TextBlock>
                         <TextBlock Text="Date :" Foreground="Red"></TextBlock>
                         <TextBlock Text="{Binding Date}"></TextBlock>
                     </StackPanel>
                 </DataTemplate>
             </ListView.ItemTemplate>
         </ListView>

6)Now we need to create a Class with attributes Text , By , Situation and Date so we can Deserialize the received data.
7)Create Class Quotes with the mentioned attributes

         [DataContract]
         class Quotes
         {             
             [DataMember]
             public string Text { get; set; }
             [DataMember]
             public string Situation { get; set; }
             [DataMember]
             public string By { get; set; }
             [DataMember]
             public string Date { get; set; }
          }
8)On the Class Add DataContract attribute so we can DeSerialize the Class and also DataMember in the properties

9)Get the Drop box File URL https://dl.dropboxusercontent.com/u/YourUserIDandFileName.json

10)Check the URL is is a https so we need to call a httpClient in your applicaion.

11)In the OnNavigatedTo methind in the main Page add the HTTPClient

var client = new HttpClient();
client.MaxResponseContentBufferSize = 1024 * 1024;
var response = await client.GetAsync(new Uri("https://YOUrURL"));
var result = await response.Content.ReadAsStringAsync();

12)After you get the Data we need to parse it so we will use JsonObject.Parse and get the first value of it(The Array).

var QuotesRecieved = JsonObject.Parse(result);
string DataArraySt = QuotesRecieved.Values.FirstOrDefault().GetArray().Stringify();

13)No we need to Deserializa the Data , I get this function for this helpful answer

 

 public static T Deserialize<T>(string json)
         {             
var _Bytes = Encoding.Unicode.GetBytes(json);
             using (MemoryStream _Stream = new MemoryStream(_Bytes))
             {                 
var _Serializer = new DataContractJsonSerializer(typeof(T));
                 return (T)_Serializer.ReadObject(_Stream);             
}         
}

14)So let’s use it and set the DataListView itemSource to the returned List

 var QL = Deserialize<List<Quotes>>(DataArraySt);
             DataListView.ItemsSource = QL;



Here is the full Code
public MainPage()
         {
             this.InitializeComponent();
         }
         protected async override void OnNavigatedTo(NavigationEventArgs e)
         {
             var client = new HttpClient();
             client.MaxResponseContentBufferSize = 1024 * 1024;
             var response = await client.GetAsync(new Uri("https://dl.dropboxusercontent.com/u/113685979/quotes.json"));
             var result = await response.Content.ReadAsStringAsync();
             var QuotesRecieved = JsonObject.Parse(result);
             string DataArraySt = QuotesRecieved.Values.FirstOrDefault().GetArray().Stringify();
             var QL = Deserialize<List<Quotes>>(DataArraySt);
             DataListView.ItemsSource = QL;
                      }
         public static T Deserialize<T>(string json)
         {
             var _Bytes = Encoding.Unicode.GetBytes(json);
             using (MemoryStream _Stream = new MemoryStream(_Bytes))
             {
                 var _Serializer = new DataContractJsonSerializer(typeof(T));
                 return (T)_Serializer.ReadObject(_Stream);
             }
         }

         [DataContract]
         class Quotes
         {
             [DataMember]
             public string Text { get; set; }
             [DataMember]
             public string Situation { get; set; }
             [DataMember]
             public string By { get; set; }
             [DataMember]
             public string Date { get; set; }
         }
2056910448_thanks_xlarge
@IbraheemOM
Advertisements

Written by Ibraheem Osama Mohamed

September 20, 2013 at 12:15 pm

Posted in Windows 8

3 Responses

Subscribe to comments with RSS.

  1. Thanks for the tip , but can we modify the content of the JSON file programmatically , for example allow user to add a specific quotes

    Ahmed Kamal

    September 20, 2013 at 2:33 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: