Получить JSON из URL, сохранить в файл и, наконец, CreateActivationService - PullRequest
0 голосов
/ 09 октября 2018

Используя расширение Template Studio для Visual Studio, я сгенерировал базу решения проекта и теперь пытаюсь прервать процесс загрузки приложения с помощью HTTP-запроса, прежде чем продолжить отображение страницы.

App.xaml.cs

using System;

using Braytech_3.Services;

using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.UI.Xaml;

namespace Braytech_3
{
    public sealed partial class App : Application
    {
        private Lazy<ActivationService> _activationService;

        private ActivationService ActivationService
        {
            get { return _activationService.Value; }
        }

        public App()
        {
            InitializeComponent();

            APIRequest();

            // Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class.
            _activationService = new Lazy<ActivationService>(CreateActivationService);
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!args.PrelaunchActivated)
            {
                await ActivationService.ActivateAsync(args);
            }
        }

        protected override async void OnActivated(IActivatedEventArgs args)
        {
            await ActivationService.ActivateAsync(args);
        }

        private async void APIRequest()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                APITempSave(httpResponseBody);

            }
            catch (Exception ex)
            {

            }
        }

        private async void APITempSave(string json)
        {
            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

            if (await tempFolder.TryGetItemAsync("APIData.json") != null)
            {
                StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }
            else
            {
                StorageFile APIData = await tempFolder.CreateFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }

        }

        private ActivationService CreateActivationService()
        {
            return new ActivationService(this, typeof(Views.VendorsPage), new Lazy<UIElement>(CreateShell));
        }

        private UIElement CreateShell()
        {
            return new Views.ShellPage();
        }
    }
}

Я думаю, что мне нужно сделать, это позвонить по номеру _activationService = new Lazy<ActivationService>(CreateActivationService); один раз APITempSave(), но я не уверен, как это сделать и каковы лучшие практики.

Любое руководство будет с благодарностью!

1 Ответ

0 голосов
/ 09 октября 2018

После дальнейшего изучения и ознакомления с созданным решением, а также дополнительного поиска в Google await, async и Tasks <> я смог реализовать запрос в качестве службы наряду с такими элементами, как ThemeSelector и ToastNotifications.

ThemeSelector - одна из первых вещей, которую нужно вызвать, чтобы определить режим светлой и темной темы для текущего пользователя, поэтому я смог смоделировать свой сервис вокруг него и одновременно вызвать его.

Это, очевидно, очень специфично для кода, который генерирует шаблонная студия, но некоторые концепции являются общими, и если кто-то еще будет искать подобные ответы в будущем, возможно, они найдут это.

APIRequest.cs(Служба)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace Braytech_3.Services
{
    public static class APIRequest
    {

        internal static async Task Request()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                await APITempSave(httpResponseBody);

            }
            catch (Exception ex)
            {

            }
        }

        internal static async Task APITempSave(string json)
        {
            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

            if (await tempFolder.TryGetItemAsync("APIData.json") != null)
            {
                StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }
            else
            {
                StorageFile APIData = await tempFolder.CreateFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }

        }
    }
}

ActiviationService.cs (первоначально вызывается App.xaml.cs)

private async Task InitializeAsync()
{
    await ThemeSelectorService.InitializeAsync();
    await APIRequest.Request();
}
...