private async Task Cache(AuthorizedBridgeModel bridgeModel) { using (var writer = new StreamWriter(_bridgeAddressCacheFile, append: false)) { string serializedBrigeModel = JsonConvert.SerializeObject(bridgeModel); await writer.WriteAsync(serializedBrigeModel); } }
public async Task EstablishConnection() { var httpClient = _httpClientFactory.CreateClient(); _bridgeModel = await TryReadFromCache(); if (_bridgeModel == null) { Console.WriteLine("Lets try to find your Bridge..."); HttpResponseMessage response = await httpClient.GetAsync(_bridgeDiscoveryEndpoint); response.EnsureSuccessStatusCode(); string responseContent = await response.Content.ReadAsStringAsync(); IEnumerable <FoundBridgeModel> bridges = JsonConvert.DeserializeObject <IEnumerable <FoundBridgeModel> >(responseContent); AuthorizedBridgeModel authorizedBridgeModel = null; foreach (FoundBridgeModel bridge in bridges) { if (bridge == null) { continue; } string bridgeEndpoint = $"http://{bridge.IpAddress}/api"; try { SuccesfulBridgeConnectionModel succesfulBridgeConnectionModel = await TryConnect(bridgeEndpoint, _tempUserName); authorizedBridgeModel = new AuthorizedBridgeModel { Id = bridge.Id, IpAddress = bridge.IpAddress, UserName = succesfulBridgeConnectionModel.Success.UserName }; break; } catch (Exception) { // ignored } } if (authorizedBridgeModel == null) { throw new Exception("Could not find the Bridge. Try again."); } _bridgeModel = authorizedBridgeModel; await Cache(_bridgeModel); } }