Esempio n. 1
0
 /// <summary>
 /// Retrieves the genre list from the Shoutcast server
 /// </summary>
 /// <returns>A List of ShoutcastGenre objects</returns>
 public List<ShoutcastGenre> GetGenres()
 {
     WebRequestHandler wrh = new WebRequestHandler();
     string response = wrh.MakeWebRequest(m_GenresUrl + "?rss=1");
     m_Genres = ParseGenres(response);
     return m_Genres;
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="authentication"></param>
        /// <param name="contentType"></param>
        /// <param name="method"></param>
        /// <param name="jsonBody"></param>
        /// <returns></returns>
        protected string SendWebRequest(string url, Dictionary <string, string> data, AuthenticationHeaderValue authentication = null, string contentType = "application/x-www-form-urlencoded", string method = "POST", string jsonBody = "")
        {
            string responseString         = null;
            FormUrlEncodedContent content = null;

            System.Net.Http.HttpResponseMessage response = null;
            string certpath = (HttpContext.Current == null) ? connectionConfiguration.sslCertPath : HttpContext.Current.Server.MapPath(connectionConfiguration.sslCertPath);

            var encodedCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", connectionConfiguration.clientID, connectionConfiguration.clientSecret)));

            WebRequestHandler handler     = new WebRequestHandler();
            X509Certificate2  certificate = LoadCertificateFile(certpath, connectionConfiguration.sslKeyPath, connectionConfiguration.sslKeyPass);

            handler.ClientCertificates.Add(certificate);

            using (var client = new HttpClient(handler))
            {
                // iat needs to support Basic Authentication
                // uncomment this when it does.

                if (authentication != null)
                {
                    client.DefaultRequestHeaders.Authorization = authentication;
                }

                client.DefaultRequestHeaders.Add("User-Agent", "adp-connection-net/1.0.1");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));

                if (method.ToUpper().Equals("POST"))
                {
                    if (jsonBody != String.Empty)
                    {
                        var jsonContent = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                        response = client.PostAsync(url, jsonContent).Result;
                    }
                    else if (data != null)
                    {
                        content  = new FormUrlEncodedContent(data);
                        response = client.PostAsync(url, content).Result;
                    }
                }
                else
                {
                    response = client.GetAsync(url).Result;
                }

                if (response.IsSuccessStatusCode)
                {
                    // by calling .Result you are performing a synchronous call
                    var responseContent = response.Content;

                    // by calling .Result you are synchronously reading the result
                    responseString = responseContent.ReadAsStringAsync().Result;
                }
                else
                {
                    // by calling .Result you are performing a synchronous call
                    var responseContent = response.Content;

                    // by calling .Result you are synchronously reading the result
                    responseString = responseContent.ReadAsStringAsync().Result;
                    throw new ADPConnectionException(String.Format("Connection Exception: {0}: {1}", response.StatusCode, responseString), new JavaScriptSerializer().Serialize(response));
                }
            }

            return(responseString);
        }
Esempio n. 3
0
        async Task CheckForUpdates()
        {
            try
            {
                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                        var uninstaller = new Uninstaller();
                        uninstaller.Uninstall(uninstallInfo);
                        Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                    telemetryClient?.TrackException(ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync();

                var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);

                var latestVersion = new Version(result.Version);

                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion       = latestVersion;
                    Update.IsUpdateRequired       = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes        = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable)
                {
                    return;
                }

                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                                          "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }

                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string)key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                Update.IsUpdating = false;
                                return;
                            }

                            var    length          = response.Content.Headers.ContentLength;
                            double lengthInMb      = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                            double bytesDownloaded = 0;

                            using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    var buffer = new byte[65535 * 4];

                                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);

                                    while (bytesRead != 0)
                                    {
                                        await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);

                                        bytesDownloaded += bytesRead;

                                        if (length.HasValue)
                                        {
                                            double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                            var    percent        = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                            var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                            Update.IsUpdating         = true;
                                            Update.DownloadPercentage = percent;
                                            progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                        }

                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                            Update.IsUpdating = false;
                                            return;
                                        }

                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                                    }
                                }
                        }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;

                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));

                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo        startupInfo        = new StartupInfo();
                SecurityAttributes processSecurity    = new SecurityAttributes();
                SecurityAttributes threadSecurity     = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength  = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                                                  threadSecurity, false, NormalPriorityClass,
                                                  IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                    telemetryClient?.TrackException(ex);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
                telemetryClient?.TrackException(ex);
                telemetryClient?.Flush();
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
Esempio n. 4
0
 internal CouchbaseHttpClient(WebRequestHandler handler)
Esempio n. 5
0
        public Polymath(VaultClientSettings vaultClientSettings)
        {
            VaultClientSettings = vaultClientSettings;

#if NET45
            var handler = new WebRequestHandler();

            // if auth method is kerberos, then set the credentials in the handler.
            if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Kerberos)
            {
                var kerberosAuthMethodInfo = vaultClientSettings.AuthMethodInfo as KerberosAuthMethodInfo;
                handler.PreAuthenticate = kerberosAuthMethodInfo.PreAuthenticate;
                handler.Credentials     = kerberosAuthMethodInfo.Credentials;
            }
#elif NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48
            var handler = new WinHttpHandler();

            // if auth method is kerberos, then set the credentials in the handler.
            if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Kerberos)
            {
                var kerberosAuthMethodInfo = vaultClientSettings.AuthMethodInfo as KerberosAuthMethodInfo;
                handler.PreAuthenticate   = kerberosAuthMethodInfo.PreAuthenticate;
                handler.ServerCredentials = kerberosAuthMethodInfo.Credentials;
            }
#else
            var handler = new HttpClientHandler();

            // if auth method is kerberos, then set the credentials in the handler.
            if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Kerberos)
            {
                var kerberosAuthMethodInfo = vaultClientSettings.AuthMethodInfo as KerberosAuthMethodInfo;
                handler.PreAuthenticate = kerberosAuthMethodInfo.PreAuthenticate;
                handler.Credentials     = kerberosAuthMethodInfo.Credentials;
            }
#endif

            // not the best place, but a very convenient place to add cert of certauthmethod.
            if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Cert)
            {
                var certAuthMethodInfo = vaultClientSettings.AuthMethodInfo as CertAuthMethodInfo;

                if (certAuthMethodInfo.ClientCertificate != null)
                {
                    handler.ClientCertificates.Add(certAuthMethodInfo.ClientCertificate);
                }
                else
                {
                    if (certAuthMethodInfo.ClientCertificateCollection != null)
                    {
                        handler.ClientCertificates.AddRange(certAuthMethodInfo.ClientCertificateCollection);
                    }
                }
            }

            vaultClientSettings.PostProcessHttpClientHandlerAction?.Invoke(handler);

            _httpClient = VaultClientSettings.MyHttpClientProviderFunc == null ? new HttpClient(handler) : VaultClientSettings.MyHttpClientProviderFunc(handler);

            _httpClient.BaseAddress = new Uri(VaultClientSettings.VaultServerUriWithPort);

            if (VaultClientSettings.VaultServiceTimeout != null)
            {
                _httpClient.Timeout = VaultClientSettings.VaultServiceTimeout.Value;
            }

            if (VaultClientSettings.AuthMethodInfo != null)
            {
                _authMethodLoginProvider = AuthProviderFactory.CreateAuthenticationProvider(VaultClientSettings.AuthMethodInfo, this);

                SetVaultTokenDelegate();
            }
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            try
            {
                var    certificatePath = args[0];
                var    password        = args[1];
                var    uriStr          = args[2];
                var    agentId         = args[3];
                var    command         = args[4];
                var    tablePath       = args[5];
                string requestId       = "";
                if (args.Length > 6)
                {
                    requestId = args[6];
                }
                var xmlSerializer = new GenericXmlSerializer();
                var pemPacker     = new PemPacker();


                var certificate = new X509Certificate2(certificatePath, password);
                var pkcs7Coder  = new PKCS7Coder(certificate);

                var uri     = new Uri(uriStr);
                var handler = new WebRequestHandler();
                handler.ClientCertificates.Add(certificate);

                using (var client = new YandexMoneyClient(xmlSerializer, pkcs7Coder, pemPacker, uri, handler))
                {
                    //var response = client.TestDepositionRequest(new TestDepositionRequest()
                    //{
                    //    AgentId = 203598,
                    //    DstAccount = "410019806982007",
                    //    Amount = "10.00",
                    //    ClientOrderId = Guid.NewGuid().ToString(),
                    //    DepositionPointId = "29",
                    //    Currency = "643",
                    //    Contract = "Зачисление на кошелек",
                    //    RequestDT = DateTime.Now
                    //});
                    //Console.WriteLine(response.Error);
                    //Console.WriteLine(response.Identification);
                    //Console.WriteLine(response.Status);
                    //Console.WriteLine(response.TechMessage);
                    //Console.ReadLine();

                    if (command == "check")
                    {
                        var checkDepositionPointRequest = new CheckDepositionPointsRequest()
                        {
                            AgentId   = long.Parse(agentId),
                            RequestId = requestId
                        };
                        var result = client.CheckDepositionPointsRequest(checkDepositionPointRequest);
                        Console.WriteLine(result.Status);
                        Console.WriteLine(result.RequestId);
                        if (result.Error != null)
                        {
                            Console.WriteLine(result.Error.Code);
                            Console.WriteLine(result.Error.PointId);
                        }
                        Console.WriteLine();
                        foreach (var item in result.Items)
                        {
                            Console.WriteLine($"{item.Id} {item.Reason} {item.Status}");
                        }
                    }
                    else if (command == "add")
                    {
                        var parser = new AddressParser();
                        var wb     = new XSSFWorkbook(tablePath);
                        var sheet  = wb.GetSheetAt(0);

                        var addDepositionPointRequest = new AddDepositionPointsRequest()
                        {
                            AgentId   = long.Parse(agentId),
                            RequestId = Guid.NewGuid().ToString(),
                            Points    = new DepositionPoint[134]
                        };

                        for (int i = 0; i != 134; i++)
                        {
                            var row = sheet.GetRow(i + 1);
                            if (row != null)
                            {
                                var depositionPoint = new DepositionPoint()
                                {
                                    Id       = (int)row.GetCell(1).NumericCellValue,
                                    Type     = "atm",
                                    Address  = parser.Parse(row.GetCell(6).StringCellValue),
                                    Subagent = false
                                };
                                addDepositionPointRequest.Points[i] = depositionPoint;
                            }
                        }

                        File.WriteAllText(@"C:\Users\it014\Desktop\request.txt", UTF8Encoding.UTF8.GetString(xmlSerializer.Serialize <AddDepositionPointsRequest>(addDepositionPointRequest)));
                        Console.ReadLine();
                        var result = client.AddDepositionPointsRequest(addDepositionPointRequest);
                        File.AppendAllText("log.txt", result.RequestId + "\r\n");
                        Console.WriteLine(result.RequestId);
                        Console.WriteLine(result.Status);
                        if (result.Error != null)
                        {
                            Console.WriteLine(result.Error.Code);
                            Console.WriteLine(result.Error.PointId);
                        }
                    }
                    else if (command == "balance")
                    {
                        var balnceRequest = new BalanceRequest()
                        {
                            AgentId       = long.Parse(agentId),
                            ClientOrderId = Guid.NewGuid().ToString(),
                            RequestDT     = DateTime.Now
                        };
                        var result = client.BalanceRequest(balnceRequest);
                        Console.WriteLine(result.Balance);
                        Console.WriteLine(result.ClientOrderId);
                        Console.WriteLine(result.ProcessedDt);
                        Console.WriteLine(result.Status);
                        Console.WriteLine(result.Error);
                    }
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.GetType().FullName);
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.HResult);
                Console.ReadLine();
            }
        }
Esempio n. 7
0
        internal HttpJsonRequest(
            CreateHttpJsonRequestParams requestParams,
            HttpJsonRequestFactory factory)
        {
            _credentials        = requestParams.DisableAuthentication == false ? requestParams.Credentials : null;
            disabledAuthRetries = requestParams.DisableAuthentication;

            Url    = requestParams.Url;
            Method = requestParams.Method;

            if (requestParams.Timeout.HasValue)
            {
                Timeout = requestParams.Timeout.Value;
            }
            else
            {
                Timeout = TimeSpan.FromSeconds(100); // default HttpClient timeout
#if DEBUG
                if (Debugger.IsAttached)
                {
                    Timeout = TimeSpan.FromMinutes(5);
                }
#endif
            }

            this.factory      = factory;
            owner             = requestParams.Owner;
            conventions       = requestParams.Convention;
            requestTimeMetric = requestParams.RequestTimeMetric;

            recreateHandler = factory.httpMessageHandler ?? (
                () =>
            {
                var useDefaultCredentials = _credentials != null && _credentials.HasCredentials() == false;
                ICredentials credentialsToUse = null;
                if (_credentials != null)
                {
                    var networkCredentials = _credentials.Credentials as NetworkCredential;
                    if (networkCredentials != null && factory.authenticationScheme != null)
                    {
                        var credentialCache = new CredentialCache();
                        var uri = new Uri(requestParams.Url);
                        credentialCache.Add(new Uri(string.Format("{0}://{1}:{2}/", uri.Scheme, uri.Host, uri.Port)), factory.authenticationScheme, networkCredentials);

                        credentialsToUse = credentialCache;
                    }
                    else
                    {
                        credentialsToUse = _credentials.Credentials;
                    }
                }
#if !DNXCORE50
                var handler = new WebRequestHandler
                {
                    AllowAutoRedirect = false,
                    UseDefaultCredentials = useDefaultCredentials,
                    Credentials = credentialsToUse
                };
#else
                var handler = new HttpClientHandler
                {
                    AllowAutoRedirect = false,
                    UseDefaultCredentials = useDefaultCredentials,
                    Credentials = credentialsToUse
                };
#endif
                return(handler);
            }
                );

            httpClient = factory.httpClientCache.GetClient(Timeout, _credentials, recreateHandler);

            if (factory.DisableRequestCompression == false && requestParams.DisableRequestCompression == false)
            {
                if (Method == HttpMethods.Post || Method == HttpMethods.Put || Method == HttpMethods.Patch || Method == HttpMethods.Eval)
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Encoding", "gzip");
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
                }

                if (factory.acceptGzipContent)
                {
                    httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                }
            }

            headers.Add("Raven-Client-Version", ClientVersion);
            WriteMetadata(requestParams.Metadata);
            requestParams.UpdateHeaders(headers);
        }
Esempio n. 8
0
        public async Task <Action <HttpClient> > DoOAuthRequestAsync(string baseUrl, string oauthSource, string apiKey)
        {
            if (oauthSource == null)
            {
                throw new ArgumentNullException("oauthSource");
            }

            string serverRSAExponent = null;
            string serverRSAModulus  = null;
            string challenge         = null;

            // Note that at two tries will be needed in the normal case.
            // The first try will get back a challenge,
            // the second try will try authentication. If something goes wrong server-side though
            // (e.g. the server was just rebooted or the challenge timed out for some reason), we
            // might get a new challenge back, so we try a third time just in case.
            int tries = 0;

            while (true)
            {
                tries++;
#if !DNXCORE50
                var handler = new WebRequestHandler();
#else
                var handler = new WinHttpHandler();
#endif

                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("grant_type", "client_credentials");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")
                    {
                        CharSet = "UTF-8"
                    });

                    string data = null;
                    if (!string.IsNullOrEmpty(serverRSAExponent) && !string.IsNullOrEmpty(serverRSAModulus) && !string.IsNullOrEmpty(challenge))
                    {
                        var exponent = OAuthHelper.ParseBytes(serverRSAExponent);
                        var modulus  = OAuthHelper.ParseBytes(serverRSAModulus);

                        var apiKeyParts = apiKey.Split(new[] { '/' }, StringSplitOptions.None);
                        if (apiKeyParts.Length > 2)
                        {
                            apiKeyParts[1] = string.Join("/", apiKeyParts.Skip(1));
                        }
                        if (apiKeyParts.Length < 2)
                        {
                            throw new InvalidOperationException("Invalid API key");
                        }

                        var apiKeyName = apiKeyParts[0].Trim();
                        var apiSecret  = apiKeyParts[1].Trim();

                        data = OAuthHelper.DictionaryToString(new Dictionary <string, string> {
                            { OAuthHelper.Keys.RSAExponent, serverRSAExponent }, { OAuthHelper.Keys.RSAModulus, serverRSAModulus }, { OAuthHelper.Keys.EncryptedData, OAuthHelper.EncryptAsymmetric(exponent, modulus, OAuthHelper.DictionaryToString(new Dictionary <string, string> {
                                    { OAuthHelper.Keys.APIKeyName, apiKeyName }, { OAuthHelper.Keys.Challenge, challenge }, { OAuthHelper.Keys.Response, OAuthHelper.Hash(string.Format(OAuthHelper.Keys.ResponseFormat, challenge, apiSecret)) }
                                })) }
                        });
                    }

                    var requestUri = oauthSource;

                    var response = await httpClient.PostAsync(requestUri, data != null?(HttpContent) new CompressedStringContent(data, true) : new StringContent("")).AddUrlIfFaulting(new Uri(requestUri)).ConvertSecurityExceptionToServerNotFound();

                    if (response.IsSuccessStatusCode == false)
                    {
                        // We've already tried three times and failed
                        if (tries >= 3)
                        {
                            throw ErrorResponseException.FromResponseMessage(response);
                        }

                        if (response.StatusCode != HttpStatusCode.PreconditionFailed)
                        {
                            throw ErrorResponseException.FromResponseMessage(response);
                        }

                        var header = response.Headers.GetFirstValue("WWW-Authenticate");
                        if (header == null || header.StartsWith(OAuthHelper.Keys.WWWAuthenticateHeaderKey) == false)
                        {
                            throw new ErrorResponseException(response, "Got invalid WWW-Authenticate value");
                        }

                        var challengeDictionary = OAuthHelper.ParseDictionary(header.Substring(OAuthHelper.Keys.WWWAuthenticateHeaderKey.Length).Trim());
                        serverRSAExponent = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAExponent);
                        serverRSAModulus  = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAModulus);
                        challenge         = challengeDictionary.GetOrDefault(OAuthHelper.Keys.Challenge);

                        if (string.IsNullOrEmpty(serverRSAExponent) || string.IsNullOrEmpty(serverRSAModulus) || string.IsNullOrEmpty(challenge))
                        {
                            throw new InvalidOperationException("Invalid response from server, could not parse raven authentication information: " + header);
                        }

                        continue;
                    }

                    using (var stream = await response.GetResponseStreamWithHttpDecompression())
                        using (var reader = new StreamReader(stream))
                        {
                            var currentOauthToken = reader.ReadToEnd();
                            CurrentOauthToken           = currentOauthToken;
                            CurrentOauthTokenWithBearer = "Bearer " + currentOauthToken;

                            ScheduleTokenRefresh(oauthSource, apiKey);

                            return((Action <HttpClient>)(SetAuthorization));
                        }
                }
            }
        }
Esempio n. 9
0
 /// <inheritdoc />
 public int UnexceptionWebRequest(UmbracoUrl url) => WebRequestHandler.Unexception(this, url);
Esempio n. 10
0
 void ApplyConfig(ConsulClientConfiguration config, WebRequestHandler handler, HttpClient client)
        public async Task <string> GenerateTokenAsync(LoginViewModel context)
        {
            var jsonString = "";

            try
            {
                var handler = new WebRequestHandler()
                {
                    ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
                };

                using (var client = new HttpClient(handler))
                {
                    //client.BaseAddress = new Uri(Request.RequestUri.GetLeftPart(UriPartial.Authority).ToString());
                    client.BaseAddress = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority));
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    // HTTP POST
                    //if (context.Password == null)
                    //{
                    //    context.Password = "******";
                    //}
                    var body = new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("username", context.Username),


                        new KeyValuePair <string, string>("password", context.Password)
                    };
                    //prashant

                    //


                    var content = new FormUrlEncodedContent(body);
                    // var response1 = await client.PostAsJsonAsync("", body);
                    HttpResponseMessage response = await client.PostAsync("token", content);

                    if (response.IsSuccessStatusCode)
                    {
                        jsonString = await response.Content.ReadAsStringAsync();

                        jsonString = jsonString.Split(',')[0].ToString().Split(':')[1].ToString();

                        return(jsonString.Replace("\"", ""));
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
                    {
                        return(string.Empty);
                    }
                    else
                    {
                        return(string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write(ex.ToString());;
            }
            return(jsonString);
        }
        /// <summary>
        /// OAuth2-identity-provider based authorization via an HTTP Basic Auth String.
        /// The used server-certificate validation is tolerant. Creates an authorized HttpClient instance,
        /// following the OAuth2-identity-provider authorization strategy.
        /// Just use the returned HttpClient instance for future calls against the platform.
        /// </summary>
        /// <param name="apiDomain">address to get "auth"</param>
        /// <param name="httpBasicAuthString">HTTP Basic Auth String</param>
        /// <returns>An authorized HttpClient instance, or null if something went wrong, esp. authorization went wrong.</returns>
        public static HttpClient Authorize(string apiDomain, string httpBasicAuthString)
        {
            WebRequestHandler webRequesthandler = DefaultWebRequestHandler(false);

            HttpClient httpClient = new HttpClient(webRequesthandler);

            httpClient.Timeout     = DefaultRequestTimeout;
            httpClient.BaseAddress = new UriBuilder("https", apiDomain).Uri;

            /// Authorization procedure:
            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

            // Get identity providers:
            string  rawAuthResult        = httpClient.GetStringAsync($"https://{apiDomain}/auth").Result;
            dynamic authResult           = JObject.Parse(rawAuthResult);
            string  urlIdentityProviders = authResult.SelectToken("$._links.auth:identity-providers[0].href");

            // Select OAuth2 identity provider and retrieve login URL:
            string  rawIdentityProvidersResult = httpClient.GetStringAsync(urlIdentityProviders).Result;
            dynamic identityProvidersResult    = JObject.Parse(rawIdentityProvidersResult);
            dynamic oAuthLoginHrefObject       = identityProvidersResult.SelectToken("$._embedded.auth:identity-provider[?(@.kind == 'oauth')]._links.auth:ropc-default[0].href");

            if (null == oAuthLoginHrefObject)
            {
                // OAuth2 authentication not supported
                return(null);
            }

            string OAuth2EndPoint = oAuthLoginHrefObject.ToString();

            // Do the login:
            IDictionary <string, string> loginArguments = new Dictionary <string, string>(3)
            {
                { "grant_type", "client_credentials" },
                { "scope", "openid" }
            };

            using (HttpContent content = new FormUrlEncodedContent(loginArguments))
            {
                using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, OAuth2EndPoint)
                {
                    Content = content
                })
                {
                    request.Headers.Add("Accept", "application/json");
                    request.Headers.Add("Authorization", "Basic " + httpBasicAuthString);

                    using (HttpResponseMessage result = httpClient.SendAsync(request).Result)
                    {
                        if (HttpStatusCode.RedirectMethod == result.StatusCode || result.IsSuccessStatusCode)
                        {
                            string  rawAuthorizationData = result.Content.ReadAsStringAsync().Result;
                            dynamic authorizationData    = JObject.Parse(rawAuthorizationData);
                            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", $"avidAccessToken={authorizationData.access_token}");

                            HttpClient httpKeepAliveClient = new HttpClient(DefaultWebRequestHandler(false));
                            httpKeepAliveClient.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", $"avidAccessToken={authorizationData.access_token}");
                            httpKeepAliveClient.BaseAddress = new Uri($"http://{apiDomain}");
                            httpKeepAliveClient.DefaultRequestHeaders.Add("Accept", "application/json");
                            tokenSource = new CancellationTokenSource();
                            Task sessionRefresher
                                = Task.Factory.StartNew(
                                      async ignored =>
                            {
                                while (!tokenSource.Token.IsCancellationRequested)
                                {
                                    await Task.Delay(120000, tokenSource.Token).ConfigureAwait(false);
                                    tokenSource.Token.ThrowIfCancellationRequested();

                                    try
                                    {
                                        SessionKeepAlive(httpKeepAliveClient);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine($"Platform session refresher error. - {e.Message}");
                                    }
                                }
                            }
                                      , null
                                      , tokenSource.Token
                                      , TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning
                                      , TaskScheduler.Default);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }
            }

            return(httpClient);
        }
Esempio n. 13
0
        public HttpClientHelper(
            Uri baseAddress,
            IAuthorizationProvider authenticationHeaderProvider,
            IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > defaultErrorMapping,
            TimeSpan timeout,
            Action <HttpClient> preRequestActionForAllRequests,
            X509Certificate2 clientCert,
            HttpClientHandler httpClientHandler,
            ProductInfo productInfo,
            IWebProxy proxy
            )
        {
            this.baseAddress = baseAddress;
            this.authenticationHeaderProvider = authenticationHeaderProvider;
            this.defaultErrorMapping          =
                new ReadOnlyDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > >(defaultErrorMapping);

#if NET451
            WebRequestHandler handler = httpClientHandler as WebRequestHandler;
            if (clientCert != null)
            {
                if (handler == null)
                {
                    handler = new WebRequestHandler();
                }

                handler.ClientCertificates.Add(clientCert);
                this.usingX509ClientCert = true;
            }

            if (proxy != DefaultWebProxySettings.Instance)
            {
                if (handler == null)
                {
                    handler = new WebRequestHandler();
                }

                handler.UseProxy = (proxy != null);
                handler.Proxy    = proxy;
            }

            this.httpClientObj = handler != null ? new HttpClient(handler) : new HttpClient();
#else
            if (clientCert != null)
            {
                if (httpClientHandler == null)
                {
                    httpClientHandler = new HttpClientHandler();
                }

                httpClientHandler.ClientCertificates.Add(clientCert);
                this.usingX509ClientCert = true;
            }

            if (proxy != DefaultWebProxySettings.Instance)
            {
                if (httpClientHandler == null)
                {
                    httpClientHandler = new HttpClientHandler();
                }

                httpClientHandler.UseProxy = (proxy != null);
                httpClientHandler.Proxy    = proxy;
            }

            this.httpClientObj = httpClientHandler != null ? new HttpClient(httpClientHandler) : new HttpClient();
#endif

            this.httpClientObj.BaseAddress = this.baseAddress;
            this.httpClientObj.Timeout     = timeout;
            this.httpClientObj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(CommonConstants.MediaTypeForDeviceManagementApis));
            this.httpClientObj.DefaultRequestHeaders.ExpectContinue = false;
            if (preRequestActionForAllRequests != null)
            {
                preRequestActionForAllRequests(this.httpClientObj);
            }
            this.productInfo = productInfo;
        }
 public ConsoleLoggerMessageHandler(WebRequestHandler clientRequest) : base(clientRequest)
 {
 }
Esempio n. 15
0
 /// <inheritdoc />
 public int UnexceptionWebRequest() => WebRequestHandler.Unexception(this);
Esempio n. 16
0
        public async Task HttpsHelloWorldCerts(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl, ApplicationType applicationType, bool sendClientCert)
        {
            var logger = new LoggerFactory()
                         .AddConsole()
                         .CreateLogger($"HttpsHelloWorldCerts:{serverType}:{runtimeFlavor}:{architecture}");

            using (logger.BeginScope("HttpsHelloWorldTest"))
            {
                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint      = applicationBaseUrl,
                    EnvironmentName             = "HttpsHelloWorld", // Will pick the Start class named 'StartupHttpsHelloWorld',
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Https.config") : null,
                    SiteName        = "HttpsTestSite",               // This is configured in the Https.config
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType = applicationType
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var handler          = new WebRequestHandler();
                    handler.ServerCertificateValidationCallback = (a, b, c, d) => true;
                    handler.ClientCertificateOptions            = ClientCertificateOption.Manual;
                    if (sendClientCert)
                    {
                        X509Certificate2 clientCert = FindClientCert();
                        Assert.NotNull(clientCert);
                        handler.ClientCertificates.Add(clientCert);
                    }
                    var httpClient = new HttpClient(handler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri)
                    };

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(() =>
                    {
                        return(httpClient.GetAsync("checkclientcert"));
                    }, logger, deploymentResult.HostShutdownToken);

                    var responseText = await response.Content.ReadAsStringAsync();

                    try
                    {
                        if (sendClientCert)
                        {
                            Assert.Equal("Scheme:https; Original:http; has cert? True", responseText);
                        }
                        else
                        {
                            Assert.Equal("Scheme:https; Original:http; has cert? False", responseText);
                        }
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
Esempio n. 17
0
 /// <inheritdoc />
 public int WatchWebRequests(PipeLineStages stage, Regex regex,
                             int priority, Func <int, HttpApplication, WatchResponse> request) =>
 WebRequestHandler.Watch(this, stage, regex, priority, request);
Esempio n. 18
0
        public static async Task <RetornoSiscomex> EnviarSemServico(string xml, string due, string cpfCertificado)
        {
            try
            {
                try
                {
                    HttpResponseMessage response = new HttpResponseMessage();

                    var token = new Token();

                    token = Autenticar(cpfCertificado);

                    if (token != null)
                    {
                        var headers = ObterHeaders(token);

                        var url = string.Format("/due/api/ext/due/{0}", due);



                        using (var handler = new WebRequestHandler())
                        {
                            handler.UseProxy = false;
                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                            handler.ClientCertificates.Add(ObterCertificado(cpfCertificado));
                            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;

                            using (var client = new HttpClient(handler))
                            {
                                // client.Timeout = new TimeSpan(0, 15, 00);
                                client.Timeout = new TimeSpan(25, 0, 0);

                                client.DefaultRequestHeaders.Accept.Clear();
                                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

                                foreach (var header in headers)
                                {
                                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                                }

                                client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                                client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate");
                                client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");

                                using (var stringContent = new StringContent(xml, Encoding.UTF8, "application/xml"))
                                {
                                    HttpResponseMessage retorno = await client
                                                                  .PutAsync(new Uri(string.Concat(UrlSiscomex, url)), stringContent)
                                                                  .ConfigureAwait(false);

                                    response = retorno;
                                }
                            }
                        }
                    }

                    var retornoSiscomex = new ServicoSiscomex.RetornoSiscomex();

                    var retornoResponse = response.Content.ReadAsStringAsync().Result;

                    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(Regex.Unescape(retornoResponse))))
                    {
                        var reader = new StreamReader(memoryStream, Encoding.UTF8);

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            try
                            {
                                var xmlSerializer = new XmlSerializer(typeof(RetornoCriticas));
                                var criticas      = (ServicoSiscomex.RetornoCriticas)xmlSerializer.Deserialize(reader);

                                retornoSiscomex.Sucesso    = false;
                                retornoSiscomex.Warnings   = false;
                                retornoSiscomex.Message    = criticas.message;
                                retornoSiscomex.Criticas   = criticas.detail;
                                retornoSiscomex.XmlRetorno = retornoResponse;
                            }
                            catch (Exception ex)
                            {
                                retornoSiscomex.Sucesso    = false;
                                retornoSiscomex.Message    = "Erro: " + retornoResponse;
                                retornoSiscomex.XmlRetorno = retornoResponse;
                            }
                        }
                        else
                        {
                            if (retornoResponse.Contains("warnings"))
                            {
                                var xmlSerializer = new XmlSerializer(typeof(PucomexReturn));
                                var warnings      = (PucomexReturn)xmlSerializer.Deserialize(reader);

                                retornoSiscomex.Sucesso  = true;
                                retornoSiscomex.Warnings = true;
                                retornoSiscomex.Message  = string.Join("<br />", warnings.Warnings.Warning);
                            }
                            else
                            {
                                var xmlSerializer = new XmlSerializer(typeof(RetornoSucesso));
                                var sucesso       = (RetornoSucesso)xmlSerializer.Deserialize(reader);

                                retornoSiscomex.Sucesso  = true;
                                retornoSiscomex.Warnings = false;
                                retornoSiscomex.Message  = sucesso.Message;
                                retornoSiscomex.DUE      = sucesso.Due;
                                retornoSiscomex.RUC      = sucesso.Ruc;
                            }
                        }
                    }

                    return(retornoSiscomex);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                return(new RetornoSiscomex
                {
                    Sucesso = false,
                    Message = ex.Message
                });
            }
        }
Esempio n. 19
0
 /// <inheritdoc />
 public int UnwatchWebRequests(PipeLineStages stage, Regex regex) =>
 WebRequestHandler.Unwatch(this, stage, regex);
Esempio n. 20
0
 public RequestRoute(string path, HttpMethods httpMethod, WebRequestHandler requestHandler)
 {
     Path = path;
     HttpMethod = httpMethod;
     RequestHandler = requestHandler;
 }
Esempio n. 21
0
 /// <inheritdoc />
 public int UnwatchWebRequests(PipeLineStages stage) =>
 WebRequestHandler.Unwatch(this, stage);
Esempio n. 22
0
        static void Main(string[] args)
        {
            Task.Run(() =>
            {
                var handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = (a, b, c, d) =>
                {
                    return(true);
                };

                using (var client = new TcpClient())
                {
                    client.Connect(MachineName, LldbProxyPort);

                    Console.WriteLine("Connection made to debug proxy server.");

                    bool bRunning = true;

                    ManualResetEvent e = new ManualResetEvent(false);

                    ThreadPool.QueueUserWorkItem((o) =>
                    {
                        using (var reader = new StreamReader(client.GetStream()))
                        {
                            while (bRunning)
                            {
                                try
                                {
                                    string line = reader.ReadLine();
                                    if (line != null)
                                    {
                                        Console.WriteLine(line);
                                    }
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }

                        e.Set();
                    });

                    using (var writer = new StreamWriter(client.GetStream()))
                    {
                        while (bRunning)
                        {
                            string line = Console.ReadLine();
                            writer.WriteLine(line);
                            writer.Flush();

                            if (string.Compare(line, "quit", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                bRunning = false;
                            }
                        }
                    }

                    e.WaitOne();
                }
            }).Wait();
        }
Esempio n. 23
0
 /// <inheritdoc />
 public int UnwatchWebRequests() =>
 WebRequestHandler.Unwatch(Environment.Id, App.Id);
        private static HttpMessageHandler ResolveHttpMessageHandler(SamlAuthenticationOptions options)
        {
            HttpMessageHandler handler = new WebRequestHandler();

            return(handler);
        }
Esempio n. 25
0
 /// <inheritdoc />
 public int UnwatchWebRequests(IApp app) =>
 WebRequestHandler.Unwatch(app.Id);
Esempio n. 26
0
 public YandexMoneyClient(GenericXmlSerializer xmlSerializer, PKCS7Coder pkcs7coder, PemPacker pemPacker, Uri baseUri, WebRequestHandler handler) : base(handler)
 {
     this.xmlSerializer = xmlSerializer;
     this.pkcs7coder    = pkcs7coder;
     this.pemPacker     = pemPacker;
     this.baseUri       = baseUri;
 }
Esempio n. 27
0
 /// <inheritdoc />
 public int ExceptionWebRequest(UmbracoUrl url) => WebRequestHandler.Exception(this, null, url);
        public AsyncRequesterBase(CommandLineOptions options)
        {
#if NET452
            var requestHandler = new WebRequestHandler()
            {
                UseCookies            = false,
                UseDefaultCredentials = true,
                ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true
            };
#else
            var requestHandler = new HttpClientHandler()
            {
                UseCookies            = false,
                UseDefaultCredentials = true
            };
#endif

            if (options.UseProxy)
            {
                requestHandler.UseProxy = true;
                requestHandler.Proxy    = WebRequest.GetSystemWebProxy();
            }
            _client  = new HttpClient(requestHandler);
            _options = options;
            _url     = new TokenisedString(options.Url);
            if (!string.IsNullOrEmpty(options.Template))
            {
                _templateParser      = new TemplateParser(File.ReadAllText(options.Template));
                _randomValueProvider = new RandomValueProvider(
                    new[] { _url }.Concat(_templateParser.Headers.Select(x => x.Value)).ToArray());
            }
            else
            {
                _randomValueProvider = new RandomValueProvider(_url);
            }
            _valueProvider = new NoValueProvider();

            if (!string.IsNullOrEmpty(_options.Plugin)) // plugin
            {
                var assembly          = Assembly.LoadFile(_options.Plugin);
                var valueProviderType = assembly.GetExportedTypes().FirstOrDefault(t => typeof(IValueProvider)
                                                                                   .IsAssignableFrom(t));
                if (valueProviderType != null)
                {
                    _valueProvider = (IValueProvider)Activator.CreateInstance(valueProviderType);
                    Console.WriteLine($"Loaded {valueProviderType.FullName} from the plugin as IValueProvider.");
                }

                var responseOverride = assembly.GetExportedTypes().FirstOrDefault(t => typeof(IResponseStatusOverride)
                                                                                  .IsAssignableFrom(t));

                if (responseOverride != null)
                {
                    _responseStatusOverride = (IResponseStatusOverride)Activator.CreateInstance(responseOverride);
                    Console.WriteLine($"Loaded {responseOverride.FullName} from the plugin as IResponseStatusOverride.");
                }
            }
            else if (!string.IsNullOrEmpty(options.ValuesFile)) // csv values file
            {
                _valueProvider = new SeparatedFileValueProvider(options.ValuesFile,
                                                                options.IsTsv ? '\t' : ',', options.Shuffle);
            }
        }
Esempio n. 29
0
 /// <inheritdoc />
 public int UnexceptionWebRequest(Regex regex) => WebRequestHandler.Unexception(this, regex);
Esempio n. 30
0
        // =================================================================================================================
        /// <summary>
        ///     Install the package
        /// </summary>
        /// <param name="_uri">URI to send to</param>
        /// <param name="_parameters">parameters to be added to the uri</param>
        /// <param name="_files">list of filenames to send</param>
        /// <returns>response string</returns>
        private static string InstallPackage(string _uri, Dictionary <string, string> _parameters, List <string> _files)
        {
            string        originalUri = _uri;
            StringBuilder postData    = new StringBuilder();

            if (_parameters != null)
            {
                int count = 0;
                foreach (KeyValuePair <string, string> kvp in _parameters)
                {
                    if (count > 0)
                    {
                        postData.Append("&");
                    } // en dif
                    postData.AppendFormat("{0}={1}", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value));
                    ++count;
                } // end foreach
            }     // end if
            _uri = _uri + "?" + postData.ToString();
            string responseString = "";

            try
            {
                using (var handler = new WebRequestHandler()
                {
                    CookieContainer = CookieContainer,
                })
                {
                    handler.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return(true); };
                    using (var client = new HttpClient(handler))
                    {
                        client.DefaultRequestHeaders.ExpectContinue = false;
                        client.DefaultRequestHeaders.Authorization  = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Username, Password))));
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
                        if (!string.IsNullOrEmpty(CSRF))
                        {
                            client.DefaultRequestHeaders.Add("X-CSRF-Token", CSRF);
                        }
                        if (Credentials == null)
                        {
                            if (!string.IsNullOrEmpty(WMID))
                            {
                                client.DefaultRequestHeaders.Add("WMID", WMID);
                            }
                        } // end if
                        using (var content = new MultipartFormDataContent())
                        {
                            foreach (string f in _files)
                            {
                                var      streamContent = new StreamContent(new StreamReader(f).BaseStream, 1024);
                                FileInfo fI            = new FileInfo(f);
                                streamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                                {
                                    Name     = "\"" + fI.Name + "\"",
                                    FileName = "\"" + fI.Name + "\""
                                };
                                streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                                content.Add(streamContent);
                            } // end foreach

                            // this is the magic bit of code to fix sending the multipart form data properly...
                            var boundaryValue = content.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");
                            boundaryValue.Value = boundaryValue.Value.Replace("\"", String.Empty);

                            Task <HttpResponseMessage> tmessage = client.PostAsync(_uri, content);
                            tmessage.Wait();
                            HttpResponseMessage message = tmessage.Result;
                            message.EnsureSuccessStatusCode();
                            var input = message.Content.ReadAsStringAsync();
                            responseString = input.Result;
                        } // end using
                    }     // end using
                }
            }             // end try
            catch (Exception _ex)
            {
                responseString = _ex.ToString();
            }

            return(responseString);
        } // end InstallPackage
        public void update()
        {
            String bdCustomerApiKey = "73ad7b80-7c4e-11e4-a2d3-b8ca3a6b879d"; //This key is generated by Bluedot Point Access UI when your account is created
            String bdApplicationId  = "564ecdc0-7e86-11e4-95ff-a0481cdba490"; //This ID is retrieved through the GET Applications call
            String bdRestUrl        = "https://api.bluedotinnovation.com/1/applications";

            String application =
                "{" +
                "\"security\": {" +

                /*
                 * customerApiKey is generated when customer registers first time. It is also available
                 * on the PointAccess interface in the Edit Profile section.
                 */
                "\"customerApiKey\":" + "\"" + bdCustomerApiKey + "\"" +
                "}," +
                "\"content\": { " +
                "\"application\" : {" +

                /*This is the id of the application as opposed to the api key.
                 * This is returned when the application/getAll is called*/
                "\"applicationId\":" + "\"" + bdApplicationId + "\"," +
                /* Time in Hour:Minute format.*/
                "\"nextRuleUpdateIntervalFormatted\": \"00:10\"," +
                "\"webhook\": {" +
                /*The URL of the server where the webhooks will be received.*/
                "\"url\": \"https://api.testapplication.com/webhook/checkinreceiver\"," +
                "\"enabled\" : true," +
                /*The Security Token Key is the name of the field to be sent in the POST request header.*/
                "\"securityTokenKey\" : \"authToken\"," +
                /*The Security Token Value field is value of the Security Token Key field sent in the POST request header.*/
                "\"securityTokenValue\" : \"f2f7a58c-f0d5-498c-9bad-acbc89923dc5\"" +
                "}" +
                "}" +
                "}" +
                "}";

            WebRequestHandler handler     = new WebRequestHandler();
            X509Certificate2  certificate = new X509Certificate2();

            handler.ClientCertificates.Add(certificate);
            HttpClient httpRestClient = new HttpClient(handler);

            //specify to use TLS 1.2 as default connection
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            httpRestClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpContent jsonApplicationContent = new StringContent(@application);

            jsonApplicationContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage serverResponse = httpRestClient.PostAsync(new Uri(bdRestUrl), jsonApplicationContent).Result;

            if (serverResponse.IsSuccessStatusCode)
            {
                var result = serverResponse.Content.ReadAsStringAsync().Result;
                Console.WriteLine("{0}", result);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)serverResponse.StatusCode, serverResponse.Content.ReadAsStringAsync().Result);
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Retrieves a list of all Shoutcast stations tagged with
 /// the given genre name
 /// </summary>
 /// <param name="genre">The name of the genre to search for</param>
 /// <returns>A List of ShoutcastStation objects</returns>
 public List<ShoutcastStation> GetStationsByGenre(string genreName)
 {
     WebRequestHandler wrh = new WebRequestHandler();
     string response = wrh.MakeWebRequest(m_StationsByGenreUrl + genreName);
     return ParseStations(response);
 }
Esempio n. 33
0
        private static Tuple <HttpStatusCode, string> MakeQrsRequest(string path, HttpMethod method, HTTPContentType contentType = HTTPContentType.json, byte[] body = null)
        {
            // Fix Path
            if (!path.StartsWith("/"))
            {
                path = '/' + path;
            }
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            int indexOfSlash = path.LastIndexOf('/');
            int indexOfQuery = path.LastIndexOf('?');

            if (indexOfQuery <= indexOfSlash)
            {
                path += "?";
            }
            else
            {
                path += "&";
            }

            string         responseString = "";
            HttpStatusCode responseCode   = 0;
            string         xrfkey         = "0123456789abcdef";

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

            HttpRequestMessage req = new HttpRequestMessage();

            req.RequestUri = new Uri(@"https://" + HOSTNAME.Value + ":4242/qrs" + path + "xrfkey=" + xrfkey);
            req.Method     = method;
            req.Headers.Add("X-Qlik-xrfkey", xrfkey);
            req.Headers.Add("X-Qlik-User", @"UserDirectory=internal;UserId=sa_api");

            WebRequestHandler handler = new WebRequestHandler();

            handler.ClientCertificates.Add(SENSE_CERT.Value);

            if (method == HttpMethod.Post || method == HttpMethod.Put)
            {
                req.Content = new ByteArrayContent(body);

                // Set Headers
                if (contentType == HTTPContentType.json)
                {
                    req.Content.Headers.Remove("Content-Type");
                    req.Content.Headers.Add("Content-Type", "application/json");
                }
                else if (contentType == HTTPContentType.app)
                {
                    req.Content.Headers.Remove("Content-Type");
                    req.Content.Headers.Add("Content-Type", "application/vnd.qlik.sense.app");
                }
                else
                {
                    throw new ArgumentException("Content type '" + contentType.ToString() + "' is not supported.");
                }
            }

            using (HttpClient client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    Task <HttpResponseMessage> responseTask = client.SendAsync(req);
                    responseTask.Wait();
                    responseTask.Result.EnsureSuccessStatusCode();
                    responseCode = responseTask.Result.StatusCode;
                    Task <string> responseBodyTask = responseTask.Result.Content.ReadAsStringAsync();
                    responseBodyTask.Wait();
                    responseString = responseBodyTask.Result;
                }
                catch (Exception e)
                {
                    if (responseCode != 0)
                    {
                        return(new Tuple <HttpStatusCode, string>(responseCode, e.Message));
                    }
                    else
                    {
                        return(new Tuple <HttpStatusCode, string>(HttpStatusCode.InternalServerError, e.Message));
                    }
                }
            }

            return(new Tuple <HttpStatusCode, string>(responseCode, responseString));
        }