コード例 #1
0
        public async Task SetCredentials(MQTTCredential mqttCredential)
        {
            var folder          = Windows.Storage.ApplicationData.Current.LocalFolder;
            var storeCredential = await folder.CreateFileAsync(CREDENTIAL_FILE, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            await Windows.Storage.FileIO.WriteTextAsync(storeCredential, JsonConvert.SerializeObject(mqttCredential));
        }
コード例 #2
0
ファイル: MainPage.xaml.cs プロジェクト: NgToann/DemoIoT
        //public static async Task<MQTTCredential> GetMQTTCredentials(DeviceModel device)
        public static async Task <MQTTCredential> GetMQTTCredentials()
        {
            // 1 Check credential local is available or not.
            var storageFolder  = Windows.Storage.ApplicationData.Current.LocalFolder;
            var checkFileExist = await storageFolder.TryGetItemAsync(CREDENTIAL_FILENAME);

            if (checkFileExist != null)
            {
                var credentialLocalFile = await storageFolder.GetFileAsync(CREDENTIAL_FILENAME);

                var contentFromFile = await Windows.Storage.FileIO.ReadTextAsync(credentialLocalFile);

                if (!string.IsNullOrEmpty(contentFromFile))
                {
                    mQTTCredential = JsonConvert.DeserializeObject <MQTTCredential>(contentFromFile);
                    return(mQTTCredential);
                }
            }

            // 2 if not availale. get from server, save data to storage
            var         body     = JsonConvert.SerializeObject(deviceDefault);
            HttpContent content  = new StringContent(body, Encoding.UTF8, "application/json");
            var         response = await client.PutAsync("api/devices/credentials", content);

            if (response.IsSuccessStatusCode)
            {
                //var result = await response.Content.ReadAsAsync<MQTTCredential>();
                //return result;
                var resultString = await response.Content.ReadAsStringAsync();

                mQTTCredential = JsonConvert.DeserializeObject <MQTTCredential>(resultString);

                // Create credentialJson file; replace if exists
                //Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                //var x = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
                //var t = await storageFolder.GetFileAsync("credentiallocal.json");

                var storeCredential = await storageFolder.CreateFileAsync(CREDENTIAL_FILENAME, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                await Windows.Storage.FileIO.WriteTextAsync(storeCredential, JsonConvert.SerializeObject(mQTTCredential));

                return(mQTTCredential);
            }
            return(null);
        }