user5677145
user5677145

Reputation:

Downloading JSON in UWP (C#)

I'm new in developing for UWP platform.

I writing UWP app for Windows 10 mobile.

I making downloading like this

public async Task<string> FetchAsync(string url)
{
    string jsonString;

    using (var httpClient = new System.Net.Http.HttpClient())
    {
        var stream = await httpClient.GetStreamAsync(url);
        StreamReader reader = new StreamReader(stream);
        jsonString = reader.ReadToEnd();
    }

    return jsonString;
}

Writing to file like this:

  string url = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=82";
        var json = await FetchAsync(url);
        using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
        {
            json.Save(fs);
        }

        Debug.WriteLine(json);

Whole code :

  using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using System.Xml;
using Windows.ApplicationModel.Calls;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace  Murakami
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public  sealed  partial class   MainPage : Page
    {
        public MainPage()
        {




            string url = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=82";
            var json = await FetchAsync(url);
            using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
            {
                json.Save(fs);
            }

            Debug.WriteLine(json);


            this.InitializeComponent();
            XmlDocument doc = new XmlDocument();
            XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Order"));
            el.SetAttribute("CallConfirm", "1");
            el.SetAttribute("PayMethod", "");
            el.SetAttribute("QtyPerson", "");
            el.SetAttribute("Type", "1");
            el.SetAttribute("PayStateID", "0");
            el.SetAttribute("Remark", "{StreetName} , ..");
            el.SetAttribute("RemarkMoney", "0");
            el.SetAttribute("TimePlan", "");
            el.SetAttribute("Brand", "1");
            el.SetAttribute("DiscountPercent", "0");
            el.SetAttribute("BonusAmount", "0");
            el.SetAttribute("Department", "");

            XmlElement el2 = (XmlElement)el.AppendChild(doc.CreateElement("Customer"));

            el2.SetAttribute("Login", "");
            el2.SetAttribute("FIO", "{FIO}");

            XmlElement el3 = (XmlElement)el.AppendChild(doc.CreateElement("Address"));

            el3.SetAttribute("CityName", "");
            el3.SetAttribute("StationName", "");
            el3.SetAttribute("StreetName", "{StreetName}");
            el3.SetAttribute("House", "{HouseName}");
            el3.SetAttribute("Corpus", "");
            el3.SetAttribute("Building", "");
            el3.SetAttribute("Flat", "{FlatName}");
            el3.SetAttribute("Porch", "");
            el3.SetAttribute("Floor", "");
            el3.SetAttribute("DoorCode", "");

            XmlElement el4 = (XmlElement)el.AppendChild(doc.CreateElement("Phone"));

            el4.SetAttribute("Code", "{Code}");
            el4.SetAttribute("Number", "{Phone}");

            XmlElement el5 = (XmlElement)el.AppendChild(doc.CreateElement("Products"));




              using (FileStream fs = new FileStream("test.xml", FileMode.Create))
              {
                  doc.Save(fs);
              }

              Debug.WriteLine(doc);







        }

       async private void TwitterButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://twitter.com/murakami_rest"));

        }

       async private void FacebookButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://www.facebook.com/MURAKAMI.rest"));
        }

       async  private void button9_Click_1(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://vk.com/murakami_restaurant_delivery"));
        }

        async private void InstagramButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("https://instagram.com/murakami_in_ua/"));

        }

        private void PhoneCallButton_Click(object sender, RoutedEventArgs e)
        {
            PhoneCallManager.ShowPhoneCallUI("+380442308888","");
        }

        private void ProMurakamiButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(ProMurakami));

        }

        private void BludoDnyaButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(BludoDnya));
        }

        private void CartButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Cart2));
        }


        /* private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
         {
             PhoneCallManager.ShowPhoneCallUI("0213132131", "my name");
         }*/
    }




   public async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        return jsonString;
    }
}

I have these errors:

 Error  CS0116  A namespace cannot directly contain members such as fields or methods



 Error  CS0103  The name 'FetchAsync' does not exist in the current context Murakami    



  Error CS4033  The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.    

Where is my mistakes in code?

Thank's so much for help!

Upvotes: 2

Views: 1238

Answers (3)

Dev-Systematix
Dev-Systematix

Reputation: 449

You may use GetAsync

 var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsAsync<string>();
                }

Header namespace:

using System.Net.Http;
using System.Net.Http.Headers;

and read response in json string instead of StreamReader.

Upvotes: 0

Geoff James
Geoff James

Reputation: 3180

I've had a look at your code.

FIRSTLY

Where you've got:

/* private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
     {
         PhoneCallManager.ShowPhoneCallUI("0213132131", "my name");
     }*/
} // <-- This brace is closing off the class too early.

The last brace is closing off the class, and therefore the FetchAsync(url) method is trying to be declared as its own class.

Remove the offending } from after this code, and place one right at the bottom. Like this:

            /* private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
         {
             PhoneCallManager.ShowPhoneCallUI("0213132131", "my name");
         }*/


        public async Task<string> FetchAsync(string url)
        {
            string jsonString;

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                var stream = await httpClient.GetStreamAsync(url);
                StreamReader reader = new StreamReader(stream);
                jsonString = reader.ReadToEnd();
            }

            return jsonString;
        }
    } 
} // <-- Add this one, right here

This is causing your

Error CS0116 A namespace cannot directly contain members such as fields or methods

Error CS0103 The name 'FetchAsync' does not exist in the current context Murakami

And SECONDLY

Your await FetchAsync(url); call is inside the constructor of the class, which cannot be marked as async.

You need to create a new method, wrapping your

var json = await FetchAsync(url);
            using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
            {
                json.Save(fs);
            }

            Debug.WriteLine(json);

In its own async method, and then call that from your constructor instead.

Like this:

    private async void NewMethod(string url)
    {
        var json = await FetchAsync(url);
        using (FileStream fs = new FileStream("cache1.txt", FileMode.Create))
        {
            // Do stuff in here to write to your file...
        }

        Debug.WriteLine(json);
    }

Visit https://msdn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files to find out more on writing text to a file in UWP.

And call it from your ctor...

public MainPage() {
        string url = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=82";
        NewMethod(url); // Now call your newly-created method.

        ... // Do your other stuff as before.
}

This was what was causing your

Error CS4033 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

Hope this helps! Let me know if you need anything more.

Upvotes: 3

Alexej Sommer
Alexej Sommer

Reputation: 2679

Lets start from the beginning:

Error CS0116 A namespace cannot directly contain members such as fields or methods

You have miss somewhere { or } signs (or they are in wrong place. If you check your code once again for correct braces then first and second errors will disappear.

What's about

The 'await' operator can only be used within an async method...

You should have "async" predicate in method where "await" operation called. But as I remember you can't make coustructor async. So, I can recommend you place your code in Loading event and add async predicate to this event

Upvotes: 0

Related Questions