Esempio n. 1
0
		public void Ctor ()
		{
			var s = new List<KeyValuePair<string, string>> () {
				new KeyValuePair<string, string> ("key", "44"),
				new KeyValuePair<string, string> ("key 2", "&+/Ž@:=")
			};

			using (var m = new FormUrlEncodedContent (s)) {
				Assert.AreEqual ("application/x-www-form-urlencoded", m.Headers.ContentType.MediaType, "#1");
				Assert.AreEqual (37, m.Headers.ContentLength, "#2");
				Assert.AreEqual ("key=44&key+2=%26%2B%2F%C5%BD%40%3A%3D", m.ReadAsStringAsync ().Result, "#3");
			}

			s = new List<KeyValuePair<string, string>> ();
			using (var m = new FormUrlEncodedContent (s)) {
				Assert.AreEqual ("application/x-www-form-urlencoded", m.Headers.ContentType.MediaType, "#11");
				Assert.AreEqual (0, m.Headers.ContentLength, "#12");
				Assert.AreEqual ("", m.ReadAsStringAsync ().Result, "#13");
			}

			s = new List<KeyValuePair<string, string>> () {
				new KeyValuePair<string, string> ( "key", ""),
				new KeyValuePair<string, string> ( "key+ 2", null)
			};

			using (var m = new FormUrlEncodedContent (s)) {
				Assert.AreEqual ("application/x-www-form-urlencoded", m.Headers.ContentType.MediaType, "#21");
				Assert.AreEqual (14, m.Headers.ContentLength, "#22");
				Assert.AreEqual ("key=&key%2B+2=", m.ReadAsStringAsync ().Result, "#23");
			}
		}
Esempio n. 2
0
        public async Task<SendSmsResult> SendSms(string message)
        {
            var queryParameter = new[]
            {
                new KeyValuePair<string, string>("user", _user),
                new KeyValuePair<string, string>("pass", _pass),
                new KeyValuePair<string, string>("msg", message)
            };

            HttpContent content = new FormUrlEncodedContent(queryParameter);
            var query = await content.ReadAsStringAsync();

            var response = await _httpClient.GetAsync(new Uri(_smsapiUri, "/sendmsg?" + query));
            switch (response.StatusCode)
            {
                case HttpStatusCode.OK:
                    return SendSmsResult.Sent;
                case HttpStatusCode.BadRequest:
                    return SendSmsResult.MissingParameter;
                case HttpStatusCode.PaymentRequired:
                    return SendSmsResult.Throttled;
                case HttpStatusCode.Forbidden:
                    return SendSmsResult.ServiceNotActivated;
                case HttpStatusCode.InternalServerError:
                    return SendSmsResult.ServerError;
            }
            return SendSmsResult.ServerError;
        }
        public string GenerateSHA512Signature(FormUrlEncodedContent request)
        {
            HMAC digester = new HMACSHA512(this.PrivateKeyBytes);
            StringBuilder hex = new StringBuilder();
            byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(request.ReadAsStringAsync().Result);

            return BitConverter.ToString(digester.ComputeHash(requestBytes)).Replace("-", "").ToLower();
        }
 private async void DebugPrintAnalyticsOutput(Task<string> resultTask, Dictionary<string, string> hitData)
 {
     using (var form = new FormUrlEncodedContent(hitData))
     {
         var result = await resultTask.ConfigureAwait(false);
         var formData = await form.ReadAsStringAsync().ConfigureAwait(false);
         Debug.WriteLine($"Request: POST {_serverUrl} Data: {formData}");
         Debug.WriteLine($"Output of analytics: {result}");
     }
 }
        private string GetQueryString(ApiRequest request)
        {
            string xml = _xmlPipeline.Serialize(request);
            List<KeyValuePair<string, string>> values = GetQueryStringValues(xml);

            string query;
            using (var content = new FormUrlEncodedContent(values))
            {
                query = content.ReadAsStringAsync().Result;
            }

            return query;
        }
Esempio n. 6
0
        private async Task<GetLoginPageResult> GetLoginPage()
        {
            var result = new GetLoginPageResult();

            var queryParameter = new[]
            {
                new KeyValuePair<string, string>("locale", "en_US"),
                new KeyValuePair<string, string>("state", "bfh"),
                new KeyValuePair<string, string>("redirect_uri",
                    "https://battlelog.battlefield.com/sso/?tokentype=code"),
                new KeyValuePair<string, string>("response_type", "code"),
                new KeyValuePair<string, string>("client_id", "battlelog"),
                new KeyValuePair<string, string>("display", "web/login")
            };

            HttpContent content = new FormUrlEncodedContent(queryParameter);


            var query = await content.ReadAsStringAsync();

            var uri = new Uri("https://accounts.ea.com/connect/auth?" + query, UriKind.Absolute);


            var response = await _httpClient.GetAsync(uri);
            var source = await response.Content.ReadAsStringAsync();
            var parameters = response.RequestMessage.RequestUri.Query.Remove(0, 1).Split('&');

            foreach (var parameter in parameters)
            {
                var parameterSplitted = parameter.Split('=');
                var key = parameterSplitted[0];
                var value = WebUtility.UrlDecode(parameterSplitted[1]);

                if (key == "execution")
                {
                    result.Execution = value;
                }
                else if (key == "initref")
                {
                    result.Initref = value;
                }
            }

            // If HttpUtility is available in .Net 5
            //var queryDuringRedirect = response.RequestMessage.RequestUri.ParseQueryString();
            //result.Execution = queryDuringRedirect["execution"];
            //result.Initref = queryDuringRedirect["initref"];

            return result;
        }
 private void SetupRequestUrl()
 {
     using (var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]
     {
         new KeyValuePair<string, string>("client", ClientName),
         new KeyValuePair<string, string>("key", ApiKey),
         new KeyValuePair<string, string>("appver", ClientVersion),
         new KeyValuePair<string, string>("pver", ProtocolVersion)
     }
     ))
         {
         RequestUrl = HttpClient.BaseAddress.ToString() + content.ReadAsStringAsync().Result;
         }
 }
Esempio n. 8
0
        private Uri BuildGetTokenUri(string clientId, string clientSecret, string redirectUri, string code)
        {
            var query = new FormUrlEncodedContent(new[]
              {
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret),
                new KeyValuePair<string, string>("code", code),
                new KeyValuePair<string, string>("redirect_uri", redirectUri)
              });

              var uriBuilder = new UriBuilder(OAuthInfo.SlackOAuthUri);
              uriBuilder.Query = query.ReadAsStringAsync().Result;

              return uriBuilder.Uri;
        }
        public async Task HttpClient_PostAsync(string requestUrl, string responseContent)
        {
            var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(responseContent)};
            var mockPostContent = new FormUrlEncodedContent(PostContent.ToArray());
            var mockPostContentString = await mockPostContent.ReadAsStringAsync().ConfigureAwait(false);

            var httpClient = new HttpClient(new MockHttpMessageHandler(requestUrl, mockResponse));
            var httpResponse = await httpClient.PostAsync(requestUrl, mockPostContent).ConfigureAwait(false);
            var stringResponse = string.Empty;

            if (httpResponse.Content != null)
                stringResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            Assert.Equal(mockPostContentString, "Name=bob&Address=Ireland&Phone=12345");
            Assert.Equal(responseContent, stringResponse);
        }
Esempio n. 10
0
 /// <summary>
 /// submit this form, using a specified HttpClient.
 /// </summary>
 /// <remarks>
 /// the request will be set up from the form values.
 /// You can set up other options (like user-agent, timeout, cookies) before executing.
 /// </remarks>
 /// <returns>an async task.</returns>
 /// <exception cref="System.ArgumentException">
 /// if the form's absolute action URL cannot be determined.
 /// Make sure you pass the document's base URI when parsing.
 /// </exception>
 public Task<HttpResponseMessage> SubmitAsync(HttpClient client)
 {
     string action = HasAttr("action") ? AbsUrl("action") : BaseUri;
     Validate.NotEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.");
     var data = new FormUrlEncodedContent(this.FormData);
     if (string.Equals(Attr("method"), "POST", StringComparison.OrdinalIgnoreCase))
     {
         // POST
         return client.PostAsync(action, data);
     }
     else
     {
         // GET
         var actionUrl = new UriBuilder(action);
         actionUrl.Query = data.ReadAsStringAsync().Result;
         return client.GetAsync(actionUrl.Uri);
     }
 }
Esempio n. 11
0
        public async Task<IList<Torrent>> GetTorrents(Filter filter = Filter.All, string category = null)
        {
            await CheckAuthentification();

            var keyValuePairs = new KeyValuePair<string, string>[2];
            keyValuePairs.SetValue(new KeyValuePair<string, string>("filter", filter.ToString().ToLower()), 0);


            if (category != null)
            {
                keyValuePairs.SetValue(new KeyValuePair<string, string>("category", category), 1);
            }

            HttpContent content = new FormUrlEncodedContent(keyValuePairs);

            var uri = new Uri("/query/torrents?" + await content.ReadAsStringAsync(), UriKind.Relative);
            var response = await _httpClient.GetAsync(uri);
            var jsonStr = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<IList<Torrent>>(jsonStr);
        }
Esempio n. 12
0
        protected string FormatQueryString(string requestUri, IEnumerable<KeyValuePair<string, string>> parameters = null)
        {
            try
            {
                string query;

                using (var content = new FormUrlEncodedContent(parameters ?? new HashSet<KeyValuePair<string, string>>()))
                {
                    query = content.ReadAsStringAsync().Result;
                }

                //requestUri += requestUri.IndexOf('?') == -1 ? ("?" + query) : (String.IsNullOrEmpty(query) ? "" : "&" + query);
                requestUri += requestUri.IndexOf('?') == -1 ? (String.IsNullOrEmpty(query) ? "" : "?" + query) : (String.IsNullOrEmpty(query) ? "" : "&" + query);
                return requestUri;
            }
            catch (Exception)
            {

                throw;
            }
        }
Esempio n. 13
0
        public async System.Threading.Tasks.Task<IServiceResponse<PagedResult<MyObject>>> QueryMyObjects(IServiceRequest<PagedQuery> query)
        {
            query.MustNotBeNull("query");
            
            //this method of query strings from object content can be refactored.  However, it will have to be a more complex solution
            //that is completely generic and handles nested objects in the same way that the server libraries expect to see.
            //for now, this merely demonstrates the core principle.
            Dictionary<string, string> queryKeyValues = new Dictionary<string, string>();
            //some system that relies on a similar mechanism to Model Binding should be used to convert to strings.  That uses
            //the TypeDescriptor.GetConverter mechanism, so we couuld do the same.
            queryKeyValues["Page"] = Convert.ToString(query.Argument.Page);
            queryKeyValues["PageSize"] = Convert.ToString(query.Argument.PageSize);
            string queryString = null;
            using (var tempContent = new FormUrlEncodedContent(queryKeyValues))
            {
                //why use this?  It handles the url encoding - and doesn't require System.Web (another popular
                //solution uses HttpUtility.ParseQueryString - but client code has no business referencing System.Web).
                queryString = await tempContent.ReadAsStringAsync();
            }

            return await _requestManager.Get<ApiServiceResponse<PagedResult<MyObject>>>(string.Concat("api/MyObjects?", queryString), query);
        }
 static Task<string> MakeQuery(Dictionary<string, string> data)
 {
     using (var content = new FormUrlEncodedContent(data))
         return content.ReadAsStringAsync();
 }
        // Get the access token via straight http post request doing client credential flow
        private async Task<String> GetAppOnlyAccessTokenWithHttpRequest(string resource, string tenantId)
        {
            /**
             * use the tenant specific endpoint for requesting the app-only access token
             */
            string tokenIssueEndpoint = appConfig.TokenIssueingUri.Replace("common", tenantId);

            /**
             * sign the assertion with the private key
             */
            string certfile = Server.MapPath(appConfig.ClientCertificatePfx);
            X509Certificate2 cert = new X509Certificate2(
                certfile,
                appConfig.ClientCertificatePfxPassword,
                X509KeyStorageFlags.MachineKeySet);

            /**
             * Example building assertion using Json Tokenhandler. 
             * Sort of cheating, but just if someone wonders ... there are always more ways to do something :-)
             */
            Dictionary<string, string> claims = new Dictionary<string, string>()
            {
                { "sub", appConfig.ClientId },
                { "jti", Guid.NewGuid().ToString() },
            };

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            X509SigningCredentials signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);

            JwtSecurityToken selfSignedToken = new JwtSecurityToken(
                appConfig.ClientId,
                tokenIssueEndpoint,
                claims.Select(c => new Claim(c.Key, c.Value)),
                DateTime.UtcNow, 
                DateTime.UtcNow.Add(TimeSpan.FromMinutes(15)),
                signingCredentials);

            string signedAssertion = tokenHandler.WriteToken(selfSignedToken);

            //---- End example with Json Tokenhandler... now to the fun part doing it all ourselves ...

            /**
              * Example building assertion from scratch with Crypto APIs
            */
            JObject clientAssertion = new JObject();
            clientAssertion.Add("aud", tokenIssueEndpoint);
            clientAssertion.Add("iss", appConfig.ClientId);
            clientAssertion.Add("sub", appConfig.ClientId);
            clientAssertion.Add("jti", Guid.NewGuid().ToString());
            clientAssertion.Add("nbf", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(-5)));
            clientAssertion.Add("exp", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(15)));

            string assertionPayload = clientAssertion.ToString(Newtonsoft.Json.Formatting.None);

            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(cert);
            RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;
            RSACryptoServiceProvider newRsa = GetCryptoProviderForSha256(rsa);
            SHA256Cng sha = new SHA256Cng();

            JObject header = new JObject(new JProperty("alg", "RS256"));
            string thumbprint = WebConvert.Base64UrlEncoded(WebConvert.HexStringToBytes(cert.Thumbprint));
            header.Add(new JProperty("x5t", thumbprint));

            string encodedHeader = WebConvert.Base64UrlEncoded(header.ToString());
            string encodedPayload = WebConvert.Base64UrlEncoded(assertionPayload);

            string signingInput = String.Concat(encodedHeader, ".", encodedPayload);

            byte[] signature = newRsa.SignData(Encoding.UTF8.GetBytes(signingInput), sha);
  
            signedAssertion = string.Format("{0}.{1}.{2}",
                encodedHeader,
                encodedPayload,
                WebConvert.Base64UrlEncoded(signature));

            /**
             * build the request payload
             */
            FormUrlEncodedContent tokenRequestForm;
            tokenRequestForm = new FormUrlEncodedContent(
                new[] { 
                new KeyValuePair<string,string>("resource", appConfig.ExchangeResourceUri),
                new KeyValuePair<string,string>("client_id", appConfig.ClientId),
                new KeyValuePair<string,string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
                new KeyValuePair<string,string>("client_assertion", signedAssertion),
                new KeyValuePair<string,string>("grant_type","client_credentials"),
                }
                );

            /*
             * Do the web request
             */
            HttpClient client = new HttpClient();

            Task<string> requestString = tokenRequestForm.ReadAsStringAsync();
            StringContent requestContent = new StringContent(requestString.Result);
            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            requestContent.Headers.Add("client-request-id", System.Guid.NewGuid().ToString());
            requestContent.Headers.Add("return-client-request-id", "true");
            requestContent.Headers.Add("UserAgent", "MatthiasLeibmannsAppOnlyAppSampleBeta/0.1");

            HttpResponseMessage response = client.PostAsync(tokenIssueEndpoint, requestContent).Result;
            JObject jsonResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            JsonSerializer jsonSerializer = new JsonSerializer();

            if(response.IsSuccessStatusCode == true)
            { 
                AADClientCredentialSuccessResponse s = (AADClientCredentialSuccessResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialSuccessResponse));
                return s.access_token;
            }

            AADClientCredentialErrorResponse e = (AADClientCredentialErrorResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialErrorResponse));
            throw new Exception(e.error_description);
        }
Esempio n. 16
0
        //マイリストを移動
        public void MoveMylist(IEnumerable<MylistListEntryViewModel> source, MylistListViewModel dest)
        {
            string token = GetMylistToken(source.First().Owner.Group);

            Dictionary<string, string> pair = new Dictionary<string, string>();
            pair["group_id"] = source.First().Owner.Group.Id;
            pair["target_group_id"] = dest.Group.Id;
            pair["token"] = token;

            //id_list以外のペアを指定
            var encodedContent = new FormUrlEncodedContent(pair);

            //エンコードされたデータを取得
            var text = encodedContent.ReadAsStringAsync().Result;

            //id_listを付け足す
            text += MakeIdList(source);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistMoveAPI);

            //ソースがとりあえずマイリストだったら
            if(source.First().Owner.Group.Id == "0") {

                request.RequestUri = new Uri(DefListMoveAPI);
            }

            //データw指定
            request.Content = new StringContent(text);

            //コンテンツタイプを設定
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            //移動先がとりあえずマイリストだったら
            if(dest.Group.Id == "0") {

                foreach(MylistListEntryViewModel vm in source) {

                    AddDefMylist(vm.Entry.Id, token);
                }
            } else {

                var ret = NicoNicoWrapperMain.Session.GetAsync(request).Result;
            }
        }
Esempio n. 17
0
        //マイリストを削除
        public void DeleteMylist(IEnumerable<MylistListEntryViewModel> source)
        {
            string token = GetMylistToken(source.First().Owner.Group);

            Dictionary<string, string> pair = new Dictionary<string, string>();
            pair["group_id"] = source.First().Owner.Group.Id;
            pair["token"] = token;

            var encodedContent = new FormUrlEncodedContent(pair);

            var text = encodedContent.ReadAsStringAsync().Result;

            text += MakeIdList(source);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistDeleteAPI);

            if(source.First().Owner.Group.Id == "0") {

                request.RequestUri = new Uri(DefListDeleteAPI);
            }

            request.Content = new StringContent(text);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var ret = NicoNicoWrapperMain.Session.GetAsync(request).Result;
        }
Esempio n. 18
0
        //マイリストをコピー
        public void CopyMylist(IEnumerable<MylistListEntryViewModel> source, MylistListViewModel dest)
        {
            string token = GetMylistToken(source.First().Owner.Group);

            Dictionary<string, string> pair = new Dictionary<string, string>();
            pair["group_id"] = source.First().Owner.Group.Id;
            pair["target_group_id"] = dest.Group.Id;
            pair["token"] = token;

            //フォームエンコード済み文字列を取得
            var encodedContent = new FormUrlEncodedContent(pair);
            var text = encodedContent.ReadAsStringAsync().Result;

            //IDリスト作成
            text += MakeIdList(source);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistCopyAPI);

            if(source.First().Owner.Group.Id == "0") {

                request.RequestUri = new Uri(DefListCopyAPI);
            }

            request.Content = new StringContent(text);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            if(dest.Group.Id == "0") {

                foreach(MylistListEntryViewModel vm in source) {

                    AddDefMylist(vm.Entry.Id, token);
                }
            } else {

                var ret = NicoNicoWrapperMain.Session.GetAsync(request).Result;
            }
        }
      private async Task<AADCodeFlowSuccessResponse> GetAccessTokenByAuthorisationCode(string code, string tenantId)
      {
         string tokenIssueEndpoint = appConfig.TokenIssueingUri.Replace("common", tenantId);

         /**
          * build the request payload
          */
         FormUrlEncodedContent tokenRequestForm;
         tokenRequestForm = new FormUrlEncodedContent(
             new[] {
                    new KeyValuePair<string,string>("grant_type","authorization_code"),
                    new KeyValuePair<string,string>("code",code),
                    new KeyValuePair<string,string>("client_id", appConfig.ClientId),
                    new KeyValuePair<string,string>("client_secret", appConfig.ClientSecret),
                    new KeyValuePair<string,string>("redirect_uri", appConfig.RedirectUri)
             }
         );

         /*
          * Do the web request
          */
         HttpClient client = new HttpClient();

         Task<string> requestString = tokenRequestForm.ReadAsStringAsync();
         StringContent requestContent = new StringContent(requestString.Result);
         requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
         requestContent.Headers.Add("client-request-id", System.Guid.NewGuid().ToString());
         requestContent.Headers.Add("return-client-request-id", "true");
         requestContent.Headers.Add("UserAgent", "MatthiasLeibmannsWebAppCodeFlow/0.1");

         HttpResponseMessage response = client.PostAsync(tokenIssueEndpoint, requestContent).Result;
         JObject jsonResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
         JsonSerializer jsonSerializer = new JsonSerializer();

         if (response.IsSuccessStatusCode == true)
         {
            AADCodeFlowSuccessResponse s = (AADCodeFlowSuccessResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADCodeFlowSuccessResponse));
            return s;
         }

         AADErrorResponse e = (AADErrorResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADErrorResponse));
         throw new Exception(e.error_description);
      }
Esempio n. 20
0
 private Task<string> BuildParametersString(Dictionary<string, string> parameters)
 {
     var content = new FormUrlEncodedContent(parameters);
     return content.ReadAsStringAsync();
 }
Esempio n. 21
0
        public async Task<ServiceResponse<SearchResults>> Search(
            string query,
            string projectTypeFilter = null,
            bool includePrerelease = false,
            string curatedFeed = null,
            SortOrder sortBy = SortOrder.Relevance,
            int skip = 0,
            int take = 10,
            bool isLuceneQuery = false,
            bool countOnly = false,
            bool explain = false,
            bool getAllVersions = false,
            string supportedFramework = null)
        {
            IDictionary<string, string> nameValue = new Dictionary<string, string>();
            nameValue.Add("q", query);
            nameValue.Add("skip", skip.ToString());
            nameValue.Add("take", take.ToString());
            nameValue.Add("sortBy", SortNames[sortBy]);

            if (!String.IsNullOrEmpty(supportedFramework))
            {
                nameValue.Add("supportedFramework", supportedFramework);
            }

            if (!String.IsNullOrEmpty(projectTypeFilter))
            {
                nameValue.Add("projectType", projectTypeFilter);
            }

            if (includePrerelease)
            {
                nameValue.Add("prerelease", "true");
            }

            if (!String.IsNullOrEmpty(curatedFeed))
            {
                nameValue.Add("feed", curatedFeed);
            }

            if (!isLuceneQuery)
            {
                nameValue.Add("luceneQuery", "false");
            }

            if (explain)
            {
                nameValue.Add("explanation", "true");
            }

            if (getAllVersions)
            {
                nameValue.Add("ignoreFilter", "true");
            }

            if (countOnly)
            {
                nameValue.Add("countOnly", "true");
            }

            var qs = new FormUrlEncodedContent(nameValue);
            var queryString = await qs.ReadAsStringAsync().ConfigureAwait(false);

            var endpoints = await _discoveryClient.GetEndpointsForResourceType(_resourceType).ConfigureAwait(false);
            var requestEndpoints = endpoints.Select(e => AppendPathToUri(e, "search/query", queryString));

            var httpResponseMessage = await _retryingHttpClientWrapper.GetAsync(requestEndpoints).ConfigureAwait(false);
            return new ServiceResponse<SearchResults>(httpResponseMessage);
        }
Esempio n. 22
0
        public static async Task<ForumAccessToken> AuthenticateAsync(string username, string password)
        {
            var handler = CreateHttpClientHandler(null);
            var loginClient = CreateHttpClient(handler);

            HttpContent content = new FormUrlEncodedContent(
                new KeyValuePair<string,string>[]{
                    new KeyValuePair<string, string>("action", "login"),
                    new KeyValuePair<string, string>("username", username),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("next", "/")
                });

            string postData = await content.ReadAsStringAsync();
            postData = postData.Replace("!", "%21");

            content = new StringContent(postData);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.Add("Origin", "http://forums.somethingawful.com");
         
            var response = await loginClient.PostAsync("/account.php", content);
            response.EnsureSuccessStatusCode();
           
            ForumAccessToken user = new ForumAccessToken();
            user.Username = username;

            // extract cookies
            var cookieUri = new Uri(COOKIE_DOMAIN_URL, UriKind.Absolute);
            var cookieCollection = handler.CookieContainer.GetCookies(cookieUri);
            user.Cookies = new List<Cookie>(cookieCollection.Count);

            // fix domain issue -> .forums.somethingawful.com to forums.somethingawful.com
            foreach (Cookie cookie in cookieCollection)
            {
                var fixedCookie = new Cookie(
                    cookie.Name,
                    cookie.Value,
                    "/",
                    DOMAIN_FIX);

                user.Cookies.Add(fixedCookie);
                handler.CookieContainer.Add(new Uri(BASE_URL), fixedCookie);
            }

            AwfulWebClient awc = new AwfulWebClient(user, loginClient);
            return user;
        }
Esempio n. 23
0
        public async Task<string> GetItinerary(GeoLocation start, GeoLocation end, DateTimeOffset? leaveTime,
            DateTimeOffset? arrivalTime, List<Network> prefNetworks, JourneyPreference? preference,
            bool withTrafficEvents, bool withText, bool withDetails)
        {
            var queryStringParametters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("startPointLon", start.Longitude.ToString()),
                new KeyValuePair<string, string>("startPointLat", start.Latitude.ToString()),
                new KeyValuePair<string, string>("keyapp", "FvChCBnSetVgTKk324rO"),
                new KeyValuePair<string, string>("engine", "ratp"),
                new KeyValuePair<string, string>("endPointLon", end.Longitude.ToString()),
                new KeyValuePair<string, string>("endPointLat", end.Latitude.ToString()),
                new KeyValuePair<string, string>("cmd", "getItinerary")
            };

            if (withTrafficEvents)
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("withTrafficEvents", "true"));
            }

            if (withText)
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("withText", "true"));
            }

            if (withDetails)
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("withDetails", "true"));
            }

            if (leaveTime == null && arrivalTime == null)
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("leaveTime", ToApix(DateTimeOffset.Now)));
            }
            else if (leaveTime != null && arrivalTime != null)
            {
                throw new ArgumentException("Can't set both leaveTime and arrivalTime");
            }
            else if (leaveTime != null)
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("leaveTime", ToApix(leaveTime.Value)));
            }
            else
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("arrivalTime", ToApix(arrivalTime.Value)));
            }

            if (preference != null)
            {
                queryStringParametters.Add(new KeyValuePair<string, string>("prefJourney",
                    preference.ToString().PascalCaseToCamelCase()));
            }

            if (prefNetworks != null && prefNetworks.Any())
            {
                var prefNetworksStr = string.Join(",", prefNetworks.Select(s => s.ToString().ToLower()));

                queryStringParametters.Add(new KeyValuePair<string, string>("prefNetworks", prefNetworksStr));
            }

            HttpContent queryString = new FormUrlEncodedContent(queryStringParametters);
            var response =
                await _httpClient.GetAsync(new Uri("/APIX?" + await queryString.ReadAsStringAsync(), UriKind.Relative));

            return await response.Content.ReadAsStringAsync();
        }
Esempio n. 24
0
        public async Task<BackendResponse> Login(string username, string password)
        {
            PasswordVault vault = new PasswordVault();
            vault.Add(new PasswordCredential("creds", username, password));
            
            HttpWebRequest request = PopulateRequest(new Uri("/Token", UriKind.Relative), POST, "application/x-www-form-urlencoded");
            Task<Stream> outStream = request.GetRequestStreamAsync();
            FormUrlEncodedContent encodedContent = new FormUrlEncodedContent(new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>("username", username),
                new KeyValuePair<string, string>("password", password),
                new KeyValuePair<string, string>("grant_type", "password")
            });

            Task<string> serializedContentTask = encodedContent.ReadAsStringAsync();
            using (StreamWriter writer = new StreamWriter(await outStream))
            {
                await writer.WriteAsync(await serializedContentTask);
            }

            try
            {
                using (StreamReader response = new StreamReader((await request.GetResponseAsync()).GetResponseStream()))
                {
                    string responseString = response.ReadToEnd();
                    JObject responseObject = JObject.Parse(responseString);
                    if (responseObject["access_token"] != null)
                    {
                        _authenticationToken = responseObject["access_token"].ToString();
                        _authenticationTokenType = responseObject["token_type"].ToString();
                        Username = responseObject["userName"].ToString();
                        return BackendResponse.Ok;
                    }
                    else
                    {
                        return BackendResponse.Unauthorized;
                    }
                }
            }
            catch (Exception)
            {
                return BackendResponse.Unauthorized;
            }
        }
Esempio n. 25
0
 public virtual async Task<HttpResponseMessage> SendRequestAsync(HttpClient client)
 {
     /// For some reason formurlencodedcontent won't encode
     /// exclamation points, it's annoying as hell.
     HttpContent content = new FormUrlEncodedContent(pairs);
     string value = await content.ReadAsStringAsync();
     return await client.PostAsync(endpoint, content);
 }
Esempio n. 26
0
        public string getResponse(string serviceURL, IDictionary<string, string> parms, bool useMarketPlaceId, bool retry)
        {
            AMZNHelper amznHelper = new AMZNHelper();

            parms["SellerId"] = SecureLocalStore.getItem("SellerId");
            if (useMarketPlaceId)
            {
                parms["MarketplaceId"] = SecureLocalStore.getItem("MarketplaceId");
            }

            amznHelper.AddRequiredParameters(parms, serviceURL);

            //var content2 = HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8);
            var content2 = new FormUrlEncodedContent(parms);
            var requestUrl = serviceURL + "?" + content2.ReadAsStringAsync().Result;

            this.url_called = requestUrl;
            this.logtimestamp = DateTime.Now;

            var start = DateTime.Now;

            WebRequest request = HttpWebRequest.Create(requestUrl);

            HttpWebResponse webResponse = null;

            try
            {
                webResponse = (HttpWebResponse)request.GetResponse();
                this.StatusCode = (int)webResponse.StatusCode;
                this.ContentLength = webResponse.ContentLength;

            }
            catch (WebException e)
            {

                // wait a bit, retry
                Util.ServiceLog.Warn("first error running " + requestUrl, e);
                if (retry)
                {
                    Util.ServiceLog.Info("waiting 2 mins...");
                    System.Threading.Thread.Sleep(120000);

                    try
                    {
                        start = DateTime.Now;
                        request = HttpWebRequest.Create(requestUrl);
                        webResponse = (HttpWebResponse)request.GetResponse();
                        this.StatusCode = (int)webResponse.StatusCode;
                        this.ContentLength = webResponse.ContentLength;
                    }
                    catch (WebException e2)
                    {
                        Util.ServiceLog.Error("Second try error running " + requestUrl, e2);
                        if (e2.Status == WebExceptionStatus.ProtocolError)
                        {
                            var exResponse = (HttpWebResponse)e2.Response;
                            if (exResponse != null)
                            {
                                this.StatusCode = (int)exResponse.StatusCode;
                                this.response = new StreamReader(exResponse.GetResponseStream()).ReadToEnd();
                            }
                        }

                    }
                }
                else
                {

                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        var exResponse = (HttpWebResponse)e.Response;
                        if (exResponse != null)
                        {
                            this.StatusCode = (int)exResponse.StatusCode;
                            this.response = new StreamReader(exResponse.GetResponseStream()).ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Util.ServiceLog.Error("Exception running " + requestUrl, e);
                return "";
            }

            this.durationms = (int)(DateTime.Now - start).TotalMilliseconds;

            if (webResponse == null)
                return "";

            MemoryStream ms = new MemoryStream();

            webResponse.GetResponseStream().CopyTo(ms);
            ms.Seek(0, 0);
            string rv = Encoding.UTF8.GetString(ms.ToArray());

            if (this.StatusCode == (int)HttpStatusCode.OK)
            {
                this.response = Util.Compress(rv);
            }

            return rv;
        }
Esempio n. 27
0
        private async Task<bool> Login(GetLoginPageResult getLoginPageResult, string email, string password)
        {
            var queryList = new[]
            {
                new KeyValuePair<string, string>("execution", getLoginPageResult.Execution),
                new KeyValuePair<string, string>("initref", getLoginPageResult.Initref)
            };

            var bodyList = new[]
            {
                new KeyValuePair<string, string>("email", email),
                new KeyValuePair<string, string>("password", password),
                new KeyValuePair<string, string>("_rememberMe",
                    "on"),
                new KeyValuePair<string, string>("rememberMe", "on"),
                new KeyValuePair<string, string>("_eventId", "submit"),
                new KeyValuePair<string, string>("gCaptchaResponse", "")
            };

            HttpContent queryStringContent = new FormUrlEncodedContent(queryList);
            HttpContent bodyContent = new FormUrlEncodedContent(bodyList);

            var queryString = await queryStringContent.ReadAsStringAsync();

            var uri = new Uri("https://signin.ea.com/p/web/login?" + queryString, UriKind.Absolute);

            var response = await _httpClient.PostAsync(uri, bodyContent);
            var source = await response.Content.ReadAsStringAsync();

            if (response.RequestMessage.RequestUri == uri)
            {
                return false;
            }

            return true;
        }
 //Encode the data to be sent as a url
 public async Task<string> GetUrlEncodedLinkAsString()
 {
     Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
     keyValuePairs.Add("Location", _location);
     keyValuePairs.Add("StreetAddress", _streetAddress);
     keyValuePairs.Add("PhoneNumber", _phoneNumber);
     keyValuePairs.Add("Name", _name);
     keyValuePairs.Add("TradeName", _tradeName);
     FormUrlEncodedContent content = new FormUrlEncodedContent(keyValuePairs);
     return await content.ReadAsStringAsync();
 }