/// <summary>
        /// Update Single Configuration.
        /// </summary>
        /// <param name="Id">
        /// GUID Key.
        /// </param>
        /// <param name="value">
        /// Value For Update.
        /// </param>
        /// <param name="accessToken">
        /// Access token used for authentication.
        /// </param>
        /// <param name="mediaType">
        /// MIME Type are you going to post/get. => application/json (mostly...)
        /// </param>
        /// <param name="urls">
        /// Target URL => https://www.darwin.com/
        /// </param>
        /// <returns>
        /// Http Response.
        /// </returns>
        public async Task <HttpResponseMessage> UpdateConfigurationAsync(string id, string value, string accessToken, string mediaType = "application/json")
        {
            httpClient = HttpClientHelper.CreateHttpClient();
            var response = await httpClient.UpdateConfigurationAsync(id, value, accessToken, mediaType);

            return(response);
        }
        /// <summary>
        /// Used For Get All URL Configuration.
        /// </summary>
        /// <param name="accessToken">
        /// Access token used for authentication.
        /// </param>
        /// <param name="mediaType">
        /// MIME Type are you going to post/get. => application/json (mostly...)
        /// </param>
        /// <param name="urls">
        /// Target URL => https://www.darwin.com/
        /// </param>
        /// <returns>
        /// Http Response.
        /// </returns>
        public async Task <IEnumerable <IntegratedApp> > GetAllURLConfigurationAsync(string accessToken, string mediaType = "application/json")
        {
            httpClient = HttpClientHelper.CreateHttpClient();
            var response = await httpClient.GetAllURLConfigurationAsync(accessToken, mediaType).Result.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <IEnumerable <IntegratedApp> >(response));
        }
        public async Task <IEnumerable <ErrorLog> > GetAllErrorLogByDateAsync(DateTime dateTime, string accessToken, string mediaType = "application/json")
        {
            httpClient = HttpClientHelper.CreateHttpClient();
            var response = await httpClient.GetListLoggingByDateAsync(dateTime, ControllerUrls.ErrorLog_URL, accessToken, mediaType).Result.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <IEnumerable <ErrorLog> >(response));
        }
        private ResponseMessage RecordPost(RequestMessage requestMessage)
        {
            HttpClient httpClientForProxy;
            IProxyAndRecordSettings settings;
            IRespondWithAProvider   respondProvider;
            IWireMockServerSettings wiremockSettings;

            wiremockSettings = new WireMockServerSettings();
            settings         = DeserializeObject <ProxyAndRecordSettings>(requestMessage);
            wiremockSettings.ProxyAndRecordSettings = settings;

            httpClientForProxy = HttpClientHelper.CreateHttpClient(settings);

            if (string.IsNullOrEmpty(settings.PrefixURL))
            {
                respondProvider = Given(Request.Create().WithPath("/*").UsingAnyMethod());
                respondProvider.WithTitle("RecordProxy_");
            }
            else
            {
                respondProvider = Given(Request.Create().WithPath(settings.PrefixURL + "/*").UsingAnyMethod());
                respondProvider.WithTitle("RecordProxy_" + settings.PrefixURL.Substring(1));
            }

            respondProvider.RespondWith(new ProxyAsyncResponseProvider(ProxyAndRecordAsyncWithHttpClient, wiremockSettings, httpClientForProxy));

            return(ResponseMessageBuilder.Create("Record started"));
        }
        public async Task <ErrorLog> GetErrorLogByIDAsync(string Id, string accessToken, string mediaType = "application/json")
        {
            httpClient = HttpClientHelper.CreateHttpClient();
            var response = await httpClient.GetLoggingByIdAsync(Id, ControllerUrls.ErrorLog_URL, accessToken, mediaType).Result.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ErrorLog>(response));
        }
예제 #6
0
        /// <summary>
        /// Retrieve an implementation of IMetricsService based on DI
        /// </summary>
        /// <param name="sp">Service Provider</param>
        /// <returns>MetricsService Object</returns>
        public static IMetricsService GetImplementation(IServiceProvider sp)
        {
            var config     = sp.GetRequiredService <IConfigurationRoot>();
            var httpClient = HttpClientHelper.CreateHttpClient(sp);

            return(new MetricsService(httpClient, config));
        }
예제 #7
0
        public async Task <Category> GetSubCategoryByIdAsync(Guid id, string accessToken, string mediaType = "application/json")
        {
            httpClient = HttpClientHelper.CreateHttpClient();
            var response = await httpClient.GetSubCategoryByIdAsync(id, accessToken, mediaType);

            return(JsonConvert.DeserializeObject <Category>(response.Content.ReadAsStringAsync().Result));
        }
예제 #8
0
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="navigationService"></param>
        public MainViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
            _navigator         = new Navigator(_navigationService);
            NavigateCommandToMainEmployeePage = new RelayCommand(NavigateCommandAction);

            client = HttpClientHelper.CreateHttpClient();
        }
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="navigationService"></param>
        public AddNewPackageViewModel(INavigationService navigationService)
        {
            _navigationService             = navigationService;
            NavigateCommandToManagerPage   = new RelayCommand(GoBackCommand);
            NavigateCommandToAddNewPackage = new RelayCommand(CommandToAddNewPackage);

            client = HttpClientHelper.CreateHttpClient();
        }
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="navigationService"></param>
        public MostAnnoyingCustomerViewModel(INavigationService navigationService)
        {
            _navigationService           = navigationService;
            NavigateCommandToManagerPage = new RelayCommand(GoBackCommand);

            client = HttpClientHelper.CreateHttpClient();

            GetClients();
        }
예제 #11
0
        /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
        public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
        {
            Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));

            ProxyUrl = proxyUrl;
            ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName;
            _httpClientForProxy = HttpClientHelper.CreateHttpClient(clientX509Certificate2ThumbprintOrSubjectName);
            return(this);
        }
예제 #12
0
        /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
        public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
        {
            Check.NotNull(settings, nameof(settings));

            ProxyUrl         = settings.Url;
            WebProxySettings = settings.WebProxySettings;

            _httpClientForProxy = HttpClientHelper.CreateHttpClient(settings);
            return(this);
        }
예제 #13
0
        /// <inheritdoc cref="Fluxup.Core.IUpdateEntry.FetchReleaseNote()"/>
        public async Task <string> FetchReleaseNote()
        {
            using var httpClient = HttpClientHelper.CreateHttpClient(GithubUpdateFetcher.ApplicationName);
            using var jsonClient = await httpClient.GetAsyncLogged(GithubUpdateFetcher.GithubApiRoot + $"/repos/{GithubUpdateFetcher.OwnerUsername}/{GithubUpdateFetcher.RepoName}/releases/{ReleaseId}");

            var json = await jsonClient.Content.ReadAsStringAsync();

            var release = JsonConvert.DeserializeObject <GithubRelease>(json);

            return(release.Body);
        }
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="navigationService"></param>
        public AddNewClientViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
            _navigator = new Navigator(_navigationService);
            NavigateCommandToMainEmployeePage = new RelayCommand(NavigationCommandActionToMainEmployeePage);
            CommandToAddNewUser = new RelayCommand(AddNewUserAction);

            client = HttpClientHelper.CreateHttpClient();

            GetAllClientTypes();
        }
예제 #15
0
 public HttpClient GetHttpClient(Kno2ConfigurationDTO configurationDTO)
 {
     return(HttpClientHelper.CreateHttpClient(baseUri: configurationDTO.BaseUri,
                                              defaultAccept: "application/json",
                                              clientId: configurationDTO.ClientId,
                                              clientSecret: configurationDTO.ClientSecret,
                                              appId: configurationDTO.AppId,
                                              authUri: configurationDTO.AuthUri,
                                              grantType: "client_credentials",
                                              emrSessionValue: configurationDTO.EmrSessionValue
                                              ));
 }
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="navigationService"></param>
        public FindClientViewModel(INavigationService navigationService)
        {
            _navigationService          = navigationService;
            _navigator                  = new Navigator(_navigationService);
            NavigateCommandToBack       = new RelayCommand(NavigateCommandActionToBack);
            CommandToGetUserByID        = new RelayCommand(CommandToGetUser);
            CommandToMoveToSelectedUser = new RelayCommand(CommandMoveToSelctedUser);

            MessengerInstance = new Messenger();

            client = HttpClientHelper.CreateHttpClient();
        }
예제 #17
0
        private void InitProxyAndRecord(IWireMockServerSettings settings)
        {
            _httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ProxyAndRecordSettings);

            var respondProvider = Given(Request.Create().WithPath("/*").UsingAnyMethod());

            if (settings.StartAdminInterface == true)
            {
                respondProvider.AtPriority(ProxyPriority);
            }

            respondProvider.RespondWith(new ProxyAsyncResponseProvider(ProxyAndRecordAsync, settings));
        }
        /// <summary>
        /// Gets the ACLs definied for the specified monitoring account
        /// </summary>
        /// <param name="accountName">Name of the account.</param>
        /// <param name="targetStampEndpoint">If not a production account, allows the target stamp to be overridden.  In most cases, allowing to default is appropriate.</param>
        /// <param name="includeReadOnly">True if the set should include those with read only access, otherwise false to return those with higher rights.</param>
        /// <returns>Acls for monitoring account.</returns>
        /// <exception cref="System.ArgumentNullException">accountName</exception>
        public static async Task <IMonitoringAccountAcls> GetAcls(string accountName, string targetStampEndpoint = "https://global.metrics.nsatc.net", bool includeReadOnly = true)
        {
            if (string.IsNullOrWhiteSpace(accountName))
            {
                throw new ArgumentNullException(nameof(accountName));
            }

            var client     = HttpClientHelper.CreateHttpClient(TimeSpan.FromMinutes(1));
            var requestUri = $"{targetStampEndpoint}/public/monitoringAccount/{accountName}/acls?includeReadOnly={includeReadOnly}";
            var result     = await HttpClientHelper.GetResponse(new Uri(requestUri), HttpMethod.Get, client, null, null).ConfigureAwait(false);

            return(JsonConvert.DeserializeObject <MonitoringAccountAcls>(result.Item1));
        }
예제 #19
0
        /// <summary>
        /// CTOR
        /// </summary>
        /// <param name="navigationService"></param>
        public ClientsInfoViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
            _navigator         = new Navigator(_navigationService);
            UpdateClient       = new RelayCommand(UpdateClientCommand);
            DeleteClient       = new RelayCommand(DeleteClientCommand);
            CommandToGoBack    = new RelayCommand(GoBackCommand);

            client = HttpClientHelper.CreateHttpClient();

            MessengerInstance = new Messenger();
            newClientFrom     = new Client();
            MessengerInstance.Register <Client>(this, "123456", (a) => { GetTheUser(a); });
        }
예제 #20
0
        /// <summary>
        /// Creates an instance of <see cref="StampLocator"/> asynchronously.
        /// </summary>
        /// <param name="folderToCacheRegionStampMap">The folder to cache region stamp map.</param>
        /// <param name="activityReporter">The activity reporter. The string argument contains the error detail when the activity results in an error; otherwise it is null.</param>
        /// <returns>An instance of <see cref="StampLocator"/>.</returns>
        public static Task <IStampLocator> CreateInstanceAsync(string folderToCacheRegionStampMap, ActivityReporter activityReporter)
        {
            if (string.IsNullOrWhiteSpace(folderToCacheRegionStampMap))
            {
                throw new ArgumentException("The argument is null or empty", nameof(folderToCacheRegionStampMap));
            }

            if (activityReporter == null)
            {
                throw new ArgumentNullException(nameof(activityReporter));
            }

            return(CreateInstanceAsync(
                       folderToCacheRegionStampMap,
                       HttpClientHelper.CreateHttpClient(ConnectionInfo.DefaultTimeout),
                       ThirdPartyRegionStampMapUrl,
                       activityReporter));
        }
예제 #21
0
 public async Task <HttpResponseMessage> DeleteAllCategoryAsync(string accessToken, string mediaType = "application/json")
 {
     httpClient = HttpClientHelper.CreateHttpClient();
     return(await httpClient.DeleteAllCategoryAsync(accessToken, mediaType));
 }
예제 #22
0
        /// <inheritdoc cref="Fluxup.Core.IUpdateFetcher{TUpdateInfo,TUpdateEntry}.CheckForUpdate(bool)"/>
        public async Task <GithubUpdateInfo> CheckForUpdate(bool useDeltaPatching = true)
        {
#if !DEBUG
            //TODO: Check if we are already checking for a update....
            if (!IsInstalledApp)
            {
                return(Logger.ErrorAndReturnDefault <GithubUpdateInfo>
                           ("This isn't a installed application, you need to install this application."));
            }
#endif
            IsCheckingForUpdate = true;

            //Get json from release api
            using var httpClient      = HttpClientHelper.CreateHttpClient(ApplicationName);
            using var responseMessage = await httpClient.GetAsyncLogged
                                            (GithubApiRoot + $"/repos/{OwnerUsername}/{RepoName}/releases/latest");

            var json = responseMessage != null ? await responseMessage.Content.ReadAsStringAsync() : "";

            //Check to see if we got anything we can use
            if (string.IsNullOrEmpty(json))
            {
                IsCheckingForUpdate = false;
                return(Logger.ErrorAndReturnDefault <GithubUpdateInfo>
                           ("\r\nWe are given no response from Github, can't continue..." +
                           responseMessage.ErrorResponseMessage()));
            }
            else if (!(responseMessage?.IsSuccessStatusCode).GetValueOrDefault())
            {
                var error = JsonConvert.DeserializeObject <GithubError>(json);
                IsCheckingForUpdate = false;
                return(Logger.ErrorAndReturnDefault <GithubUpdateInfo>
                           ("\r\nResponse reports as unsuccessful. It's likely that you haven't uploaded your first update yet or typed your Github username/repo incorrectly." +
                           responseMessage.ErrorResponseMessage() +
                           $"\r\n  Message: {error.Message}" +
                           $"\r\n  Documentation Url: {error.DocumentationUrl}"));
            }

            //Look for a RELEASES file from the release api
            var releases = JsonConvert.DeserializeObject <GithubRelease>(json);
            var release  = releases.Assets.Where(x => x.Name.StartsWith("RELEASES")).ToArray();
            releases.Assets = releases.Assets.Except(release).ToList();
            if (!release.Any())
            {
                IsCheckingForUpdate = false;
                return(Logger.ErrorAndReturnDefault <GithubUpdateInfo>
                           ("They is no RELEASES file, assumed to have no updates"));
            }
            else if (release.LongLength > 1)
            {
                //TODO: This is where we would use UpdateChannel, make it look at the filename to know what
                // file to use
                Logger.Warning("They is more then one RELEASES file, going to use the first RELEASES file");
            }

            //Grab RELEASES file and check if it's got any text
            //TODO: Check that RELEASES file is valid....
            using var releaseFileContent = await httpClient.GetAsyncLogged(release.First ().BrowserDownloadUrl);

            var releaseFile = await releaseFileContent.Content.ReadAsStringAsync();

            if (!releaseFileContent.IsSuccessStatusCode)
            {
                IsCheckingForUpdate = false;
                return(Logger.ErrorAndReturnDefault <GithubUpdateInfo>
                           ("\r\nSomething happened while getting the RELEASES file" +
                           responseMessage.ErrorResponseMessage()));
            }
            else if (string.IsNullOrEmpty(releaseFile))
            {
                IsCheckingForUpdate = false;
                return(Logger.ErrorAndReturnDefault <GithubUpdateInfo>
                           ("RELEASES file has no content"));
            }

            //Make RELEASES file contents into something we can use
            var releaseUpdates      = releaseFile.Split('\r');
            var githubUpdateEntries = new Dictionary <string, GithubUpdateEntry>();
            foreach (var update in releaseUpdates)
            {
                if (string.IsNullOrEmpty(update.Trim()))
                {
                    continue;
                }

                var fileSplit = update.Split(' ');
                githubUpdateEntries.Add(fileSplit[1], new GithubUpdateEntry(releases.Id, fileSplit[0], fileSplit[1], long.Parse(fileSplit[2]), fileSplit.Length >= 4 && bool.Parse(fileSplit[3]), ref @this));
            }

            //Get version and check if it is an delta package
            foreach (var asset in releases.Assets)
            {
                //Check that it's a file we can use
                if (!asset.Name.EndsWith(".nupkg") || !githubUpdateEntries.ContainsKey(asset.Name))
                {
                    continue;
                }
                githubUpdateEntries[asset.Name].DownloadUri = asset.BrowserDownloadUrl;

                //Add version and if it's a delta package from the filename if we can (and if it's a nuget file)
                if (githubUpdateEntries[asset.Name].AddVersionAndDeltaFromFileName(asset.Name))
                {
                    continue;
                }

                //Get nupkg file stream
                var fileStream = await httpClient.GetStreamAsyncLogged(asset.BrowserDownloadUrl);

                //get .nuspec file from nupkg
                using var packageReader = new PackageArchiveReader(fileStream);
                var nuspecReader = await packageReader.GetNuspecReaderAsync(default);
예제 #23
0
        static void Main(string[] args)
        {
            try
            {
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Needed for .Net Framework < 4.6.1
                // Enable TLS SecurityProtocol to default to TLS 1.2
                // UnComment the following line if you are  unable to upgrade to .Net 4.6.1 or greater
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Initialize the configuration data
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Initializing Configuration".AsOpeningBanner(ConsoleColor.DarkGray, false);
                ApiConfig apiConfig = new ApiConfig();
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Create a reusable HttpClient
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Creating Authenticated Http Client".AsInlineBanner(ConsoleColor.Gray);
                HttpClient httpClient = HttpClientHelper.CreateHttpClient(baseUri: apiConfig.BaseUri,
                                                                          defaultAccept: "application/json",
                                                                          clientId: apiConfig.ClientId,
                                                                          clientSecret: apiConfig.ClientSecret,
                                                                          appId: apiConfig.AppId,
                                                                          authUri: apiConfig.AuthUri,
                                                                          grantType: "client_credentials",
                                                                          emrSessionValue: apiConfig.EmrSessionValue
                                                                          );
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Request the unprocessed intake messages
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

                // This will wait forever for messages that meet the search criteria
                IEnumerable <MessageResource> intakeMessages = Enumerable.Empty <MessageResource>();
                while (true)
                {
                    "Requesting Available Unprocessed Intake Messages".AsOpeningBanner(light, false, true, false, false);
                    intakeMessages = ApiHelper.RequestUnprocessedIntakeMessages(httpClient: httpClient,
                                                                                documentsMessagesUri: apiConfig.MessageSearch());



                    // Message Download / Recieve


                    // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                    // Set the message output to be next the executable
                    // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                    string messageOutputPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? string.Empty;
                    // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --


                    foreach (var intakeMessage in intakeMessages)
                    {
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        // Request the message
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        "Getting Message".AsInlineBanner(dark);
                        string messageJson = ApiHelper.RequestMessage(httpClient: httpClient,
                                                                      messageUri: apiConfig.MessagesUri(intakeMessage.Id)
                                                                      );
                        string localMessageDirectory = Path.Combine(messageOutputPath, "MessageDownload", intakeMessage.Id);
                        if (!Directory.Exists(localMessageDirectory))
                        {
                            Directory.CreateDirectory(localMessageDirectory);
                        }

                        File.WriteAllText(Path.Combine(localMessageDirectory, "message.json"), messageJson);
                        var retrievedMessage = JsonConvert.DeserializeObject <MessageResource>(messageJson);
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        // Request the attachment meta data
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        foreach (var attachment in retrievedMessage.Attachments)
                        {
                            ("Requesting Attachment Metadata for attachment " + attachment.Id).AsInlineBanner(dark);
                            var metadata = ApiHelper.RequestAttachmentMetadata(httpClient: httpClient,
                                                                               attachmentsUri: apiConfig.AttachmentsUri(messageId: intakeMessage.Id, attachmentId: attachment.Id)
                                                                               );
                            string filedata = ApiHelper.Serialize(metadata, httpClient.DefaultMediaType());
                            string fileName = Path.Combine(messageOutputPath, localMessageDirectory, attachment.NativeFileName + ".metadata." + httpClient.DefaultMediaType());
                            (" √ saving metadata file as " + fileName).AsClosingBanner(light);
                            File.WriteAllText(fileName, filedata);
                        }
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        // Request the native attachment then save it to disk.
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        foreach (var attachment in intakeMessage.Attachments.OrderBy(a => a.IsPreviewAvailable))
                        {
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            // Request the native attachment
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            ("Requesting Native Attachment File Data " + attachment.NativeFileName).AsBanner(light, true, false);
                            byte[] fileBytes = ApiHelper.RequestAttachment(httpClient: httpClient,
                                                                           attachmentsUri: apiConfig.AttachmentsUri(messageId: retrievedMessage.Id, attachmentId: attachment.Id),
                                                                           mediaType: "application/octet-stream");
                            attachment.NativeFileBytes = fileBytes;
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            // Save the file bytes as per the nativeFileName metadata field
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            if (fileBytes.Length > 0)
                            {
                                string fileName = Path.Combine(messageOutputPath, localMessageDirectory, attachment.NativeFileName);
                                (" √ saving file as " + fileName).AsClosingBanner(light);
                                using (var stream = new FileStream(fileName, FileMode.Create))
                                    stream.Write(attachment.NativeFileBytes, 0, attachment.NativeFileBytes.Length);
                            }
                            else
                            {
                                (" There was a problem retrieving attachment").AsClosingBanner(light);
                            }
                        }
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        // Request the pdf converted attachment then save it to disk.
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        foreach (var attachment in intakeMessage.Attachments.OrderBy(a => a.Id))
                        {
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            // Request the native attachment
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            ("Requesting PDF Converted Attachment File Data " + attachment.PdfFileName).AsBanner(light, true, false);
                            byte[] fileBytes = ApiHelper.RequestAttachment(httpClient: httpClient,
                                                                           attachmentsUri: apiConfig.AttachmentsUri(messageId: retrievedMessage.Id, attachmentId: attachment.Id),
                                                                           mediaType: "application/pdf");
                            attachment.PdfFileBytes = fileBytes;
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            // Save the file bytes as per the nativeFileName metadata field
                            // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                            if (fileBytes.Length > 0)
                            {
                                string fileName = Path.Combine(messageOutputPath, localMessageDirectory, attachment.PdfFileName);
                                (" √ saving file as " + fileName).AsClosingBanner(light);
                                using (var stream = new FileStream(fileName, FileMode.Create))
                                    stream.Write(attachment.PdfFileBytes, 0, attachment.PdfFileBytes.Length);
                            }
                            else
                            {
                                (" X looks like the attachment id " + attachment.Id + " didn't convert to pdf")
                                .ToConsole(ConsoleColor.Red);
                                (" There was a problem retrieving converted attachment").AsClosingBanner(light);
                            }
                        }
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        // Send a message read event
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        "Sending Message Read Event".AsBanner(ConsoleColor.DarkGreen, true, false);
                        ApiHelper.RequesetMessageReadEvent(httpClient: httpClient,
                                                           messageReadEventUri: apiConfig.MessageReadEventUri(retrievedMessage.Id),
                                                           messageId: retrievedMessage.Id,
                                                           subject: intakeMessage.Subject
                                                           );
                        ConsoleHelper.HeaderLine(false);
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        // Send a attachmenet read event for each attachment
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        foreach (var attachment in intakeMessage.Attachments)
                        {
                            ("Sending Attachment Read Event for Attachment " + attachment.NativeFileName).AsBanner(ConsoleColor.DarkGreen, true, false);
                            ApiHelper.RequestAttachmentReadEvent(httpClient: httpClient,
                                                                 attachmentReadUri: apiConfig.AttachmentReadUri(messageId: retrievedMessage.Id, attachmentId: attachment.Id)
                                                                 );
                            ConsoleHelper.HeaderLine(false);
                        }
                        // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                    }

                    if (intakeMessages.Any())
                    {
                        ConsoleHelper.HeaderLine(true);
                    }
                    else
                    {
                        ConsoleHelper.HeaderLine(light);
                        "No messages found - waiting 10 seconds ... (ctrl+c to quit)".AsBanner(ConsoleColor.DarkYellow, true);
                        Console.WriteLine();
                        System.Threading.Thread.Sleep(10000);
                    }
                }
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
            }
            catch (AggregateException ex)
            {
                "Error".AsOpeningBanner(ConsoleColor.Red);
                foreach (var innerException in ex.InnerExceptions)
                {
                    innerException.Message.ToConsole(ConsoleColor.Red);
                    if (innerException.InnerException != null)
                    {
                        (" - " + innerException.InnerException.Message).ToConsole(ConsoleColor.Red);
                    }
                }
                string.Empty.AsClosingBanner(ConsoleColor.Red);
            }
            catch (Exception ex)
            {
                ex.Message.AsBanner(ConsoleColor.Red);
            }

            Console.ResetColor();
        }
 public async Task <HttpResponseMessage> DeleteDebugLogByIDAsync(string Id, string accessToken, string mediaType = "application/json")
 {
     httpClient = HttpClientHelper.CreateHttpClient();
     return(await httpClient.DeleteLoggingByIDAsync(Id, ControllerUrls.DebugLog_URL, accessToken, mediaType));
 }
예제 #25
0
        static void Main(string[] args)
        {
            try
            {
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Needed for .Net Framework < 4.6.1
                // Enable TLS SecurityProtocol to default to TLS 1.2
                // UnComment the following line if you are  unable to upgrade to .Net 4.6.1 or greater
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Initialize the configuration data
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Initializing Configuration".AsOpeningBanner(ConsoleColor.DarkGray, false);
                ApiConfig apiConfig = new ApiConfig();
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Create a reusable HttpClient
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Creating Authenticated Http Client".AsInlineBanner(ConsoleColor.Gray);
                HttpClient httpClient = HttpClientHelper.CreateHttpClient(baseUri: apiConfig.BaseUri,
                                                                          defaultAccept: "application/json",
                                                                          clientId: apiConfig.ClientId,
                                                                          clientSecret: apiConfig.ClientSecret,
                                                                          appId: apiConfig.AppId,
                                                                          authUri: apiConfig.AuthUri,
                                                                          grantType: "client_credentials",
                                                                          emrSessionValue: apiConfig.EmrSessionValue
                                                                          );
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --


                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Create a stock patient info
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Creating stock patient info".AsInlineBanner(ConsoleColor.Gray);
                var stockPatient = new Patient
                {
                    PatientId = "8675309",
                    FirstName = "John",
                    LastName  = "Smith (emr-client)",
                    Gender    = "M",
                    BirthDate = new DateTime(1980, 1, 1).ToShortDateString()
                };
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Validate the associated addresses
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                string toAddress   = "results@" + apiConfig.DirectMessageDomain;
                string fromAddress = "referral@" + apiConfig.DirectMessageDomain;
                "Validating Addresses".AsInlineBanner(dark);
                Dictionary <string, bool> addressValidationResults =
                    ApiHelper.ValidateAddresses(httpClient: httpClient,
                                                directoryValidateUri: apiConfig.DirectoryValidate(),
                                                addresses: new[] { toAddress, fromAddress });
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Request the available document types
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Requesting Available Document Types".AsInlineBanner(light);
                IEnumerable <string> documentTypes = ApiHelper.RequestDocumentTypes(httpClient: httpClient,
                                                                                    documentTypesUri: apiConfig.DocumentTypesUri());
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Request a message draft id
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Requesting Draft Id".AsInlineBanner(dark);
                var outboundMessage = ApiHelper.RequestMessageDraft(httpClient: httpClient,
                                                                    messageUri: apiConfig.MessagesUri()
                                                                    );
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Upload an attachment using the draft id
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                var attachmentIds = new List <string>();
                foreach (var fileType in Enum.GetValues(typeof(FileType)).Cast <FileType>())
                {
                    string fileName = FileHelpers.GenerateAttachmentName(fileType);
                    ("Uploading " + fileType + " Attachment " + fileName).AsInlineBanner(light);
                    var attachment = ApiHelper.UploadAttachment(httpClient: httpClient,
                                                                attachmentsUri: apiConfig.AttachmentsUri(outboundMessage.Id),
                                                                fileName: fileName,
                                                                attachment: new AttachmentResource
                    {
                        NativeFileName  = fileName,
                        NativeFileBytes = FileHelpers.GetSampleAttachmentBytes(fileType),
                        DocumentType    = documentTypes.First(),
                        AttachmentMeta  = new AttachmentMetaResource
                        {
                            DocumentTitle       = fileType.Description() + " Sample Document Title",
                            DocumentType        = documentTypes.First(),
                            DocumentDate        = DateTime.UtcNow,
                            DocumentDescription = fileType.Description() + " Sample Document Description",
                            Confidentiality     = Confidentiality.Normal
                        }
                    }
                                                                );
                    // The UploadAttachment helper method and the underlying API will give us the full attachment object
                    //  back but for the sake of the metadata requests we're only storing the Ids at this point
                    attachmentIds.Add(attachment.Id);
                }
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Request the attachment meta data
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                var attachments = new List <AttachmentResource>();
                foreach (var id in attachmentIds)
                {
                    ("Requesting Attachment Metadata for attachment " + id).AsInlineBanner(dark);
                    var metadata = ApiHelper.RequestAttachmentMetadata(httpClient: httpClient,
                                                                       attachmentsUri: apiConfig.AttachmentsUri(messageId: outboundMessage.Id, attachmentId: id)
                                                                       );
                    attachments.Add(metadata);
                }
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Send the message (draft)
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Sending the message (draft)".AsInlineBanner(light);

                outboundMessage.Attachments = attachments;
                outboundMessage.Subject     = "Referral";
                outboundMessage.ToAddress   = toAddress;
                outboundMessage.FromAddress = fromAddress;
                outboundMessage.Patient     = stockPatient;

                ApiHelper.SendDraft(httpClient: httpClient,
                                    messageUri: apiConfig.MessagesUri(outboundMessage.Id),
                                    messageResource: outboundMessage);
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Updating the message (draft)
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Updating the message (draft)".AsInlineBanner(light);

                outboundMessage.Patient.MiddleName = " (emr-client)";
                outboundMessage.Patient.LastName   = "Smith";

                ApiHelper.SendDraft(httpClient: httpClient,
                                    messageUri: apiConfig.MessagesUri(outboundMessage.Id),
                                    messageResource: outboundMessage);
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --



                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                // Send the message (release)
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                "Sending the message (release)".AsInlineBanner(dark);

                outboundMessage.Comments            = "Comments";
                outboundMessage.ReasonForDisclosure = "Additional disclosure reason ";
                outboundMessage.Body = "Referral from Caring Hands Village\n\n" +
                                       "Referral for: \nPatient ID: 8675309\n" +
                                       "Patient Name: John Smith\nDOB: 01/01/1980\n\n" +
                                       "Comments:\nComments";

                ApiHelper.SendRelease(httpClient: httpClient,
                                      messageSendUri: apiConfig.MessageSendUri(outboundMessage.Id),
                                      messageResource: outboundMessage
                                      );
                // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
            }
            catch (AggregateException ex)
            {
                "Error".AsOpeningBanner(ConsoleColor.Red);
                foreach (var innerException in ex.InnerExceptions)
                {
                    innerException.Message.ToConsole(ConsoleColor.Red);
                    if (innerException.InnerException != null)
                    {
                        (" - " + innerException.InnerException.Message).ToConsole(ConsoleColor.Red);
                    }
                }
                string.Empty.AsClosingBanner(ConsoleColor.Red);
            }
            catch (Exception ex)
            {
                ex.Message.AsBanner(ConsoleColor.Red);
            }

            Console.ResetColor();
        }
예제 #26
0
        private static async Task ActionAsync()
        {
            // Title
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("  _____ _                      ____        _   ");
            Console.WriteLine(" / ____| |                    |  _ \\      | |  ");
            Console.WriteLine("| (___ | |_ _ __ __ ___      _| |_) | ___ | |_ ");
            Console.WriteLine(" \\___ \\| __| '__/ _` \\ \\ /\\ / /  _ < / _ \\| __|");
            Console.WriteLine(" ____) | |_| | | (_| |\\ V  V /| |_) | (_) | |_ ");
            Console.WriteLine("|_____/ \\__|_|  \\__,_| \\_/\\_/ |____/ \\___/ \\__|   by Ethan Chrisp");

            // Get Poll ID
            Console.ResetColor();
            Console.WriteLine("\nEnter Strawpoll ID:");
            Console.ForegroundColor = ConsoleColor.White;
            string id = Console.ReadLine();

            Console.WriteLine("");

            var httpClient = HttpClientHelper.CreateHttpClient(WebProxy.GetDefaultProxy(), 10);
            var poll       = await StrawpollRequests.GetPollAsync(httpClient, id);

            if (!poll.Votes.Any())
            {
                Console.WriteLine("Error: Invalid Strawpoll ID specified.");
            }

            // Get Poll Choice
            Console.ForegroundColor = ConsoleColor.Cyan;
            for (int i = 0; i < poll.Votes.Count(); i++)
            {
                Console.WriteLine("Choice #" + i + ": " + poll.Votes.ElementAt(i).Name);
            }

            Console.ResetColor();
            Console.WriteLine("\nEnter Poll Choice:");
            Console.ForegroundColor = ConsoleColor.White;

            int voteId = 0;

            if (!int.TryParse(Console.ReadLine(), out voteId) && voteId >= poll.Votes.Count())
            {
                Console.WriteLine("\nError: Invalid Choice specified.");
            }

            // Get Proxy List
            Console.ResetColor();
            Console.WriteLine("\nEnter Proxy List Path:"); // ToDo: Get this automatically so this user doesn't have to specify a list each time
            Console.ForegroundColor = ConsoleColor.White;
            var proxyPath = Console.ReadLine();

            if (proxyPath == null)
            {
                throw new NullReferenceException("Error: Invalid Proxy List Path specified.");
            }

            if (!File.Exists(proxyPath))
            {
                throw new Exception("Error: Invalid Proxy List Path specified.");
            }

            // Get Desired Votes
            Console.ResetColor();
            Console.WriteLine("\nEnter Desired Votes: ");
            Console.ForegroundColor = ConsoleColor.White;

            int max = 0;

            if (!int.TryParse(Console.ReadLine(), out max))
            {
                throw new Exception("Error: Invalid Desired Votes specified, insufficient Proxies available.");
            }

            var lines   = File.ReadAllLines(proxyPath);
            int total   = lines.Length;
            int success = 0;
            int fail    = 0;
            int threads = 0;

            // Get Desired Threads
            Console.ResetColor();
            Console.WriteLine("\nThreads:");
            Console.ForegroundColor = ConsoleColor.White;
            if (!int.TryParse(Console.ReadLine(), out threads))
            {
                throw new Exception("Error: Invalid number of Threads specified.");
            }


            var options = new ParallelOptions
            {
                MaxDegreeOfParallelism = threads,
            };

            Parallel.ForEach(lines, options, address => {
                Task.Run(async() => {
                    if (success <= max)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write("\rSuccess: " + success + " ");
                        Console.Write("Fail: " + fail + " ");
                        Console.Write("Remaining: " + Math.Abs((success + fail) - total) + " ");
                        if (await ProxyHelpers.CheckProxyAsync(address))
                        {
                            try
                            {
                                var client = HttpClientHelper.CreateHttpClient(new WebProxy(address), 10);
                                var info   = await StrawpollRequests.GetPollAsync(client, id);
                                if (await StrawpollRequests.Vote(client, id, poll.Votes.ElementAt(voteId).ID, info.Token))
                                {
                                    success++;
                                }
                            }
                            catch (Exception)
                            {
                                fail++;
                            }
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Error: No response from Proxy " + address + ".");
                            fail++;
                        }
                    }
                }).Wait();
            });
        }
예제 #27
0
 public async Task <HttpResponseMessage> DeleteSubCategoryByIdAsync(Guid id, string accessToken, string mediaType = "application/json")
 {
     httpClient = HttpClientHelper.CreateHttpClient();
     return(await httpClient.DeleteSubCategoryByIDAsync(id, accessToken, mediaType));
 }
 public async Task <HttpResponseMessage> DeleteAllErrorLogAsync(string accessToken, string mediaType = "application/json")
 {
     httpClient = HttpClientHelper.CreateHttpClient();
     return(await httpClient.DeleteLoggingAllAsync(ControllerUrls.ErrorLog_URL, accessToken, mediaType));
 }
 private void InitProxyAndRecord(IProxyAndRecordSettings settings)
 {
     _httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ClientX509Certificate2ThumbprintOrSubjectName);
     Given(Request.Create().WithPath("/*").UsingAnyMethod()).RespondWith(new ProxyAsyncResponseProvider(ProxyAndRecordAsync, settings));
 }
예제 #30
0
 public async Task <HttpResponseMessage> PostSubCategoryAsync(Category category, string accessToken, string mediaType = "application/json")
 {
     httpClient = HttpClientHelper.CreateHttpClient();
     return(await httpClient.PostSubCategoryAsync(category, accessToken, mediaType));
 }