private async void ApiUpdate(ApiData apiData) { try { if (!_apiDataUpdates.ContainsKey(apiData.ApiKey)) { _apiDataUpdates.TryAdd(apiData.ApiKey, apiData); } if (!_apiUpdateBusy) { _apiUpdateBusy = true; while (_apiDataUpdates.Count > 0) { var apiUpdates = _apiDataUpdates.Values.ToList(); _apiDataUpdates.Clear(); var postData = new PostApiStatus() { SecurityToken = _sharedSettings.SecurityToken, ApiData = apiUpdates }; var start = new Stopwatch(); start.Start(); var result = await _sharedSettings.PostAsync <PostApiStatus, ReturnValue>("Remote/UpdateApi", postData, CancellationToken.None); start.Stop(); _logger.LogTrace("Send api results completed in {0}ms.", start.ElapsedMilliseconds); if (result.Success == false) { _logger.LogError(250, result.Exception, "Update api results failed. Return message was: {0}." + result.Message); } // wait a little while for more tasks results to arrive. await Task.Delay(500); } _apiUpdateBusy = false; } } catch (Exception ex) { _logger.LogError(250, ex, "Update api status failed with error. Error was: {0}." + ex.Message); _apiUpdateBusy = false; } }
public override async Task StartAsync(ManagedTaskProgress progress, CancellationToken cancellationToken = default) { progress.Report(50, 1, "Preparing files..."); var downloadStream = await _connectionFlatFile.DownloadFiles(_flatFile, _path, _files, _files.Length > 1, cancellationToken); var filename = _files.Length == 1 ? _files[0] : _flatFile.Name + "_files.zip"; progress.Report(100, 2, "Files ready for download..."); await _sharedSettings.StartDataStream(_messageId, downloadStream, _downloadUrl, "file", filename, false, cancellationToken); var url = $"{_sharedSettings.RemoteSettings.Network.ProxyUrl}/download/{_messageId}"; var downloadMessage = new DownloadReadyMessage() { InstanceId = _sharedSettings.InstanceId, SecurityToken = _sharedSettings.SecurityToken, ConnectionId = _connectionId, Reference = _reference, HubKey = _hubKey, Url = url }; var returnValue = await _sharedSettings.PostAsync <DownloadReadyMessage, ReturnValue>("Remote/DownloadReady", downloadMessage, cancellationToken); if (!returnValue.Success) { throw new RemoteOperationException($"The file download did not completed. {returnValue.Message}", returnValue.Exception); } }
public override async Task StartAsync(ManagedTaskProgress progress, CancellationToken cancellationToken = default) { progress.Report(50, 1, "Running data extract..."); var downloadStream = await _downloadData.GetStream(cancellationToken); var filename = downloadStream.FileName; var stream = downloadStream.Stream; progress.Report(100, 2, "Download ready..."); await _sharedSettings.StartDataStream(_reference, stream, _downloadUrl, "file", filename, false, cancellationToken); var url = $"{_downloadUrl.Url}/download/{_reference}"; var downloadMessage = new DownloadReadyMessage() { InstanceId = _sharedSettings.InstanceId, SecurityToken = _sharedSettings.SecurityToken, ConnectionId = _connectionId, Reference = _reference, HubKey = _hubKey, Url = url }; var returnValue = await _sharedSettings.PostAsync <DownloadReadyMessage, ReturnValue>("Remote/DownloadReady", downloadMessage, cancellationToken); if (!returnValue.Success) { throw new RemoteOperationException($"The data download did not completed. {returnValue.Message}", returnValue.Exception); } }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { _logger.LogInformation("Message Service is starting."); while (!cancellationToken.IsCancellationRequested) { try { await _messageQueue.WaitForMessage(cancellationToken); if (_messageQueue.Count > 0) { var messages = new List <ResponseMessage>(); while (_messageQueue.Count > 0) { _messageQueue.TryDeque(out var message); messages.Add(message); } var returnValue = await _sharedSettings.PostAsync <List <ResponseMessage>, ReturnValue>( "Remote/UpdateResponseMessage", messages, cancellationToken); if (!returnValue.Success) { _logger.LogError(1, returnValue.Exception, "A response message failed to send to server. Message" + returnValue.Message); } } await Task.Delay(500, cancellationToken); } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, $"The message service encountered the following error: {ex.Message}"); } } _logger.LogInformation("Message service has stopped."); }
private async Task RenewSslCertificate(string certificatePath, CancellationToken cancellationToken) { try { var details = new RenewSslCertificateModel() { Domain = _remoteSettings.Network.DynamicDomain, Password = _remoteSettings.Network.CertificatePassword }; _logger.LogInformation("Attempting to generate a new ssl certificate..."); var response = await _sharedSettings.PostAsync("Remote/GenerateCertificate", details, cancellationToken); if (response != null) { if (response.Content.Headers.ContentType.MediaType == "application/json") { var jsonContent = await response.Content.ReadAsStringAsync(); var message = JsonExtensions.Deserialize <ReturnValue>(jsonContent); _logger.LogError("Ssl request generated the following error: " + message.ExceptionDetails); throw new RemoteSecurityException(message.Message, message.Exception); } var certificate = await response.Content.ReadAsByteArrayAsync(); try { using (var cert = new X509Certificate2(certificate, _remoteSettings.Network.CertificatePassword)) { var effectiveDate = DateTime.Parse(cert.GetEffectiveDateString()); var expiresDate = DateTime.Parse(cert.GetExpirationDateString()); // if cert expires in next 14 days, then renew. if (DateTime.Now > effectiveDate && DateTime.Now < expiresDate) { await File.WriteAllBytesAsync(certificatePath, certificate, cancellationToken); _logger.LogInformation( $"A new Ssl certificate has been successfully created at {certificatePath}."); } else { var reason = $"A new Ssl certificate was download but has effective dates between {effectiveDate} and {expiresDate}. This certificate has not been saved."; _logger.LogCritical(reason); throw new RemoteSecurityException(reason); } } } catch (Exception ex) { var reason = $"There was an error with the downloaded SSL certificate. {ex.Message}"; _logger.LogCritical(reason, ex); throw new RemoteSecurityException(reason, ex); } } else { var reason = $"The ssl certificate renewal failed. {response.ReasonPhrase}."; _logger.LogCritical(reason); throw new RemoteSecurityException(reason); } } catch (Exception ex) { _logger.LogCritical("There was an issue generating a new SSL certificate. The existing certificate will be used, or if there is not a current certificate, then HTTP connections will not be available.", ex); } }