WebClient event firing order - json

I'm new to WP7 app development and I'm having trouble passing parameters to an API on a website.
It's my understanding that the onNavigatedTo() is fired first when a page is open on the WP7, however when I try to grab the parameters the webClient_DownloadStringCompleted() is fired first.
public partial class Ranks : PhoneApplicationPage
{
private WebClient webClient;
private string pageType;
private string pagePosition;
public Ranks()
{
InitializeComponent();
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string myJsonString = e.Result;
List<PlayerDetails> dataSource = new List<PlayerDetails>();
//load into memory stream
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myJsonString)))
{
//parse into jsonser
var ser = new DataContractJsonSerializer(typeof(PlayerDetails[]));
PlayerDetails[] obj = (PlayerDetails[])ser.ReadObject(ms);
foreach (PlayerDetails plyr in obj)
{
dataSource.Add(plyr);
}
playerList.ItemsSource = dataSource;
}
}
Whenever the URI string is built it's missing the parameters 'pageType' and 'pagePosition'
Any help would be greatly appreciated!

The class constructor will always get called before OnNavigatedTo. you should move that code from the constructor, and into OnNavigatedTo (or Loaded).
I'm guessing that you have that code in the constructor because you only want it to happen once per page load (i.e. not when the user navigates Back onto the page). If that's the case, you can check the NavigationMode.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.New)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
}

Related

How to correctly handle data management with SharedPreferences?

Right now, I am in the process of "optimizing" my app. I am still a beginner, so what I am doing is basically moving methods from my MainActivity.class to their separate class. I believe it's called Encapsulation (Please correct me if I'm wrong).
My application needs to :
Get a YouTube Playlist Link from the YouTube App (with an Intent, android.intent.action.SEND).
Use the link to fetch data from the Google Servers with the YouTubeApi and Volley.
Read the data received and add it to an arrayList<String>.
What my YouTubeUsage.java class is supposed to do, is fetch data with the YouTubeApi and Volley then store the data using SharedPreferences. Once the data is saved, the data is being read in my ConvertActivity.class (It's an activity specifically created for android.intent.action.SEND) with my method getVideoIds() before setting an adapter for my listView in my createRecyclerView() method.
YouTubeUsage.java
public class YoutubeUsage {
private Boolean results = false;
private String mResponse;
private ArrayList<String> videoIds = new ArrayList<>();
String Url;
public String getUrl(String signal) {
String playlistId = signal.substring(signal.indexOf("=") + 1);
this.Url = "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails%2C%20snippet%2C%20id&playlistId=" +
playlistId + "&maxResults=25&key=" + "API_KEY";
return this.Url;
}
public void fetch(String Url, final Context context){
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.GET, Url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
sharedPreferences(response, context);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", Objects.requireNonNull(error.getMessage()));
}
});
queue.add(request);
}
private void sharedPreferences(String response, Context context){
SharedPreferences m = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = m.edit();
if (m.contains("serverResponse")){
if (!m.getString("serverResponse", "").equals(response)){
editor.remove("serverResponse");
editor.apply();
updateSharedPreferences(response, context);
}
} else{
updateSharedPreferences(response, context);
}
}
private void updateSharedPreferences(String mResponse, Context mContext){
SharedPreferences m = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = m.edit();
editor.putString("serverResponse", mResponse);
editor.apply();
}
}
ConvertActivity.java
public class ConvertActivity extends AppCompatActivity {
YoutubeUsage youtubeUsage = new YoutubeUsage();
ArrayList<String> videoIDs = new ArrayList<>();
String Url = "";
ListView listView;
MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
listView = findViewById(R.id.listview_convert);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if ("android.intent.action.SEND".equals(action) && "text/plain".equals(type)) {
Url = youtubeUsage.getUrl(Objects.requireNonNull(intent.getStringExtra("android.intent.extra.TEXT")));
}
//I would like to avoid the try/catch below
try {
videoIDs = getVideoIDs(Url, this);
createRecyclerView(videoIDs);
Log.i("ResponseVideoIDs", String.valueOf(videoIDs.size()));
} catch (JSONException e) {
e.printStackTrace();
}
}
private ArrayList<String> getVideoIDs(String Url, Context context) throws JSONException {
ArrayList<String> rawVideoIDs = new ArrayList<>();
youtubeUsage.fetch(Url, context);
SharedPreferences m = PreferenceManager.getDefaultSharedPreferences(context);
String serverResponse = m.getString("serverResponse", "");
JSONObject jsonObject = new JSONObject(serverResponse);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId = jsonObject1.getJSONObject("contentDetails");
rawVideoIDs.add(jsonVideoId.getString("videoId"));
}
return rawVideoIDs;
}
private void createRecyclerView(ArrayList<String> videoIDs){
myCustomAdapter = new MyCustomAdapter(this, videoIDs);
listView.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
}
}
Everything works fine, however, my sharedPreferences never gets updated. Which means, if I share a YouTube playlist from the YouTube App to my app with 3 items in it, it will work fine. The Listview will show 3 items with their corresponding IDs as it should. But, if I share a YouTube playlist again, my app will still hold on to the data of the previous playlist I shared (even if I close it), showing the item number and the IDs of the previous link. If i continue to share the same playlist over and over, it will eventually show the correct number of items and the correct IDs.
I could totally put all my methods from the YouTubeUsage.java in my ConvertActivity.class preventing me from using SharedPreferences to transfer data between the two java classes. However, JSON throws an exception. That means I have to encapsulate my code with try/catch. I would like to avoid those since I need to do a lot of operations on the data just received by Volley (check a class size, look for certains strings). I find that doing this in these try/catch don't work like I want. (i.e. outside the try/catch, the values remains the same even if I updated them in the try/catch).
I want to know two things.
How can I correct this problem?
Is this the most efficient way to do this (optimization)? (I though of maybe
converting the VolleyResponse to a string with Gson then store the String file, but I don't know if that's the best way to do it since it's supposed to be
provisional data. It feels like just more of the same).
Thank You!
There is an issue with making assumptions about order of events. Volley will handle requests asynchronously, so it is advisable to implement the observer pattern here.
Create a new Java file that just contains:
interface MyNetworkResponse {
void goodResponse(String responseString);
}
Then make sure ConvertActivity implements MyNetworkResponse and create method:
void goodResponse(String responseString) {
// handle a positive response here, i.e. extract the JSON and send to your RecyclerView.
}
within your Activity.
In your YoutubeUsage constructor, pass in the Activity context (YoutubeUsage) and then store this in a YoutubeUsage instance variable called ctx.
In onCreate, create an instance of YoutubeUsage and pass in this.
In onResponse just call ctx.goodResponse(response).
Amend the following block to:
if ("android.intent.action.SEND".equals(action) && "text/plain".equals(type)) {
Url = youtubeUsage.getUrl(Objects.requireNonNull(intent.getStringExtra("android.intent.extra.TEXT")));
youtubeUsage.fetch(Url);
}
Delete the try/catch from onCreate.
And no need to use SharedPreferences at all.
UPDATE
Try this code:
MyNetworkResponse.java
interface MyNetworkResponse {
void goodResponse(String responseString);
void badResponse(VolleyError error);
}
YoutubeUsage.java
class YoutubeUsage {
private RequestQueue queue;
private MyNetworkResponse callback;
YoutubeUsage(Object caller) {
this.callback = (MyNetworkResponse) caller;
queue = Volley.newRequestQueue((Context) caller);
}
static String getUrl(String signal) {
String playlistId = signal.substring(signal.indexOf("=") + 1);
return "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails%2C%20snippet%2C%20id&playlistId=" + playlistId + "&maxResults=25&key=" + "API_KEY";
}
void fetch(String url){
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.goodResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.badResponse(error);
}
});
queue.add(request);
}
}
ConvertActivity.java
public class ConvertActivity extends AppCompatActivity implements MyNetworkResponse {
YoutubeUsage youtubeUsage;
ArrayList<String> videoIDs = new ArrayList<>();
ListView listView;
MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
listView = findViewById(R.id.listview_convert);
youtubeUsage = new YoutubeUsage(this);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if ("android.intent.action.SEND".equals(action) && "text/plain".equals(type)) {
String url = YoutubeUsage.getUrl(Objects.requireNonNull(intent.getStringExtra("android.intent.extra.TEXT")));
youtubeUsage.fetch(url);
}
}
private ArrayList<String> getVideoIDs(String serverResponse) throws JSONException {
ArrayList<String> rawVideoIDs = new ArrayList<>();
JSONObject jsonObject = new JSONObject(serverResponse);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId = jsonObject1.getJSONObject("contentDetails");
rawVideoIDs.add(jsonVideoId.getString("videoId"));
}
return rawVideoIDs;
}
private void createRecyclerView(ArrayList<String> videoIDs) {
myCustomAdapter = new MyCustomAdapter(this, videoIDs);
listView.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
}
#Override
public void goodResponse(String responseString) {
Log.d("Convert:goodResp", "[" + responseString + "]");
try {
ArrayList<String> rawVideoIDs = getVideoIDs(responseString);
createRecyclerView(rawVideoIDs);
} catch (JSONException e) {
// handle JSONException, e.g. malformed response from server.
}
}
#Override
public void badResponse(VolleyError error) {
// handle unwanted server response.
}
}

I want to create highchart widget by Eclipse RAP and i follow "RAP/Custom Widgets FAQ",but there is error?

i want to create some highchart widget by Eclipse RAP ,and i follow the official guide like this
handlejs:
var CKEDITOR_BASEPATH = "rwt-resources/";
(function(){
'use strict';
rap.registerTypeHandler( "rap.sunline.HighCharts", {
factory : function( properties ) {
var parent = rap.getObject( properties.parent );
// var element = document.createElement( "div" );
// parent.append( element );
// $(element).html("askldfjaskljdk");
return {};
}
});
}());
widget.java:
public class HightChartComposite extends Composite {
private static final String RESOURCES_PATH = "resources/";
private static final String REGISTER_PATH = "hightcharts/";
private static final String[] RESOURCE_FILES = { "jquery-2.1.0.min.js", "highcharts.js","ChartPaintListener.js" };
private static final String REMOTE_TYPE = "rap.sunline.HightCharts";
private final RemoteObject remoteObject;
private final OperationHandler operationHandler = new AbstractOperationHandler() {
#Override
public void handleSet(JsonObject properties) {
// JsonValue textValue = properties.get("text");
// if (textValue != null) {
// text = textValue.asString();
// }
}
};
public HightChartComposite(Composite parent, int style) {
super(parent, style);
registerResources();
loadJavaScript();
Connection connection = RWT.getUISession().getConnection();
remoteObject = connection.createRemoteObject(REMOTE_TYPE);
remoteObject.setHandler(operationHandler);
remoteObject.set("parent", WidgetUtil.getId(this));
}
private void registerResources() {
ResourceManager resourceManager = RWT.getResourceManager();
boolean isRegistered = resourceManager.isRegistered(REGISTER_PATH + RESOURCE_FILES[0]);
if (!isRegistered) {
try {
for (String fileName : RESOURCE_FILES) {
register(resourceManager, fileName);
}
} catch (IOException ioe) {
throw new IllegalArgumentException("Failed to load resources", ioe);
}
}
}
private void loadJavaScript() {
JavaScriptLoader jsLoader = RWT.getClient().getService(JavaScriptLoader.class);
ResourceManager resourceManager = RWT.getResourceManager();
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "jquery-2.1.0.min.js"));
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "highcharts.js"));
jsLoader.require(resourceManager.getLocation(REGISTER_PATH + "ChartPaintListener.js"));
}
private void register(ResourceManager resourceManager, String fileName) throws IOException {
ClassLoader classLoader = HightChartComposite.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(RESOURCES_PATH + fileName);
try {
resourceManager.register(REGISTER_PATH + fileName, inputStream);
} finally {
inputStream.close();
}
}
// //////////////////
// overwrite methods
#Override
public void setLayout(Layout layout) {
throw new UnsupportedOperationException("Cannot change internal layout of CkEditor");
}
}
the error is occur:
Uncaught Error: Operation "create" on target "r6" of type "null" failed:
No Handler for type rap.sunline.HightCharts
Properties:
parent = w5
and i have a question about this , what differents from extends Canvas and Composite;
You forget to implement setters in your javascript code.
The created object is stored by the framework under its object id. This object has to implement setter methods that match the properties defined in the handler, which will then be called when the server sends a set operation for a given property.

Accurate Windows phone 8.1 geolocation?

Im working with windows phone 8.1 geolocation. The problem that I currently have is that my code only shows the first numbers of my coordinate. Example: If the coordinate is "41.233" the app only shows "41.00" . I need it to be as accurate as possible. In case it matters, im using windows phone 8.1 emulator to try the app, not an actual phone.
My code:
public sealed partial class MainPage : Page
{
bool shouldSend = false;
DispatcherTimer timer = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async Task GetLocation()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromSeconds(1),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
LatLonTxt.Text = LatitudeTxt.Text + ", " + LongitudeTxt.Text;
var speed = geoposition.Coordinate.Speed.ToString();
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://proyecto-busways.rhcloud.com/colectivos?p=lta123&l=80&d=moyano&lat=" + LatitudeTxt.Text + "&lon=" + LongitudeTxt.Text + "&v=" + speed + "&Accion=Agregar");
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
result = streamRead.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
}
//else
{
// something else happened acquring the location
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void StartSending_Click(object sender, RoutedEventArgs e)
{
await GetLocation();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
StartSending.IsEnabled = false;
}
async void timer_Tick(object sender, object e)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Visible;
await GetLocation();
}
private void EndSending_Click(object sender, RoutedEventArgs e)
{
timer.Tick -= timer_Tick;
timer.Stop();
StartSending.IsEnabled = true;
EndSending.IsEnabled = false;
}
private void GPS_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(ContactPage));
}
}
Thanks for your help!
Did you try out the Geolocator.DesiredAccuracyInMeters property?
geolocator.DesiredAccuracyInMeters = 3;
Reference & Sample
In this point LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
You indicated that you have 0.00 decimals, for more accuracy you should put 0.000000

How to send windows phone 8 application data to server

I have only two input parameters in my feedback form, email, feedback and a submit button only.
I want to send(POST) this data to a specific URL like http://questoons.com/data.php
So how can I post data from windows phone 8 app to a specific URL?
Any code sample or web link would be highly appreciated.
I reccomend to write a specific class for working with POST.
public class PostRequestParameters
{
public List<PostRequestParameterObject> prms;
public PostRequestParameters()
{
prms = new List<PostRequestParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new PostRequestParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class PostRequestParameterObject
{
public string id;
public string value;
public PostRequestParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
Then you can use it to send POST data:
private void buttonSend_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
PostRequestParameters prms = new PostRequestParameters();
prms.AddPair("par1", textBox1.Text);
prms.AddPair("par2", textBox2.Text);
prms.AddPair("par3", GetMPar3());
wc.UploadStringAsync(new Uri(url), "POST", prms.FormPostData(), null);
}
// you can parse response here
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// do something
}
You can try using WebClient's UploadStringAsync() function :
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
var wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(new Uri(URI, UriKind.Absolute), myParameters);
[For Reference]

How can I read this json on windows phone 8?

I'm trying to read the following json in a windows phone app using newtonsoft.json
I can't read anything. the also looks pretty strange to me.
{"type": "Menu","menu":
[{"0":"antipasto","tipo_piatto":"antipasto","1":"porchetta","nome_piatto":"porchetta","2":"1","prezzo":"1"},
{"0":"primo","tipo_piatto":"primo","1":"matriciana","nome_piatto":"matriciana","2":"5","prezzo":"5"},
{"0":"secondo","tipo_piatto":"secondo","1":"salsicce","nome_piatto":"salsicce","2":"4","prezzo":"4"},
{"0":"contorno","tipo_piatto":"contorno","1":"patate","nome_piatto":"patate","2":"2","prezzo":"2"},
{"0":"dolce","tipo_piatto":"dolce","1":"gelato","nome_piatto":"gelato","2":"6","prezzo":"6"}]}
this is my c# code for now
public class piatto_menu_giorno
{
public string tipo_piatto { get; set; }
public string nome_piatto { get; set; }
public string prezzo { get; set; }
}
public menu()
{
InitializeComponent();
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.stepapp.it/areacli/extDevice/getMenuOdierno_101.php");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(fine_lettura_web);
webClient.OpenReadAsync(uri);
}
private void fine_lettura_web(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer json = null;
json = new DataContractJsonSerializer(typeof(ObservableCollection<piatto_menu_giorno>));
ObservableCollection<piatto_menu_giorno> menu = json.ReadObject(e.Result) as ObservableCollection<piatto_menu_giorno>;
if(menu==null)
menu_giorno.Text = "null";
else
foreach (piatto_menu_giorno piatto in menu)
{
menu_giorno.Text += piatto.nome_piatto + "\n";
}
}
sorry for all the variables name that are in italian
I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject.
private async Task<List<piatto_menu_giorno>> MyDeserializerFunAsync()
{
List<piatto_menu_giorno> book = new List<piatto_menu_giorno>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<piatto_menu_giorno>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<piatto_menu_giorno>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. I am performing asynchronous operation but you can create your simple method with piatto_menu_giorno return type.