示例#1
0
        public async Task <ActionResult> Login(string username, string password)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.BaseAddress = new Uri("http://" + this.Request.Host.Value);
            List <KeyValuePair <string, string> > values = new List <KeyValuePair <string, string> >();

            values.Add(new KeyValuePair <string, string>("username", username));
            values.Add(new KeyValuePair <string, string>("password", password));

            System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(values);
            var response = await client.PostAsync("/token", content);

            string result = response.Content.ReadAsStringAsync().Result;

            object dataObject = result;

            try
            {
                dataObject = Newtonsoft.Json.Linq.JObject.Parse(result);
            }
            catch
            {
            }

            return(StatusCode((int)response.StatusCode, dataObject));
        }
示例#2
0
        /// <summary>
        /// Will download mod json data
        /// </summary>
        private static async Task <string> DownloadData()
        {
            await Program.Log(new LogMessage(LogSeverity.Info, "ModsManager", $"Requesting DownloadData. tMod version: {tMLVersion}"));

            using (var client = new System.Net.Http.HttpClient())
            {
                //var version = await GetTMLVersion();

                var values = new Dictionary <string, string>
                {
                    { "modloaderversion", $"tModLoader {tMLVersion}" },
                    { "platform", "w" }
                };
                var content = new System.Net.Http.FormUrlEncodedContent(values);

                await Program.Log(new LogMessage(LogSeverity.Info, "ModsManager", "Sending post request"));

                var response = await client.PostAsync(XmlUrl, content);

                await Program.Log(new LogMessage(LogSeverity.Info, "ModsManager", "Reading post request"));

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

                await Program.Log(new LogMessage(LogSeverity.Info, "ModsManager", "Done downloading data"));

                return(postResponse);
            }
        }
示例#3
0
        async void GetData()
        {
            if (position == null)
            {
                position = await CrossGeolocator.Current.GetPositionAsync(timeout : TimeSpan.FromSeconds(10));
            }
            var param = new Dictionary <string, string>();

            param.Add("latitude", position.Latitude.ToString());
            param.Add("longitude", position.Longitude.ToString());

            var content = new System.Net.Http.FormUrlEncodedContent(param);
            var client  = new System.Net.Http.HttpClient();

            client.BaseAddress = App.BaseAddress;

            portListView.IsRefreshing = true;

            var response = await client.PostAsync("api/GetPortNearest", content);

            portListView.IsRefreshing = false;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var json = await response.Content.ReadAsStringAsync();

                var coordinates = JArray.Parse(json).ToObject <List <Coordinate> >();
                foreach (var item in coordinates)
                {
                    item.GetDistacneInfo(position.Latitude, position.Longitude);
                }
                portListView.ItemsSource = coordinates;
            }
        }
示例#4
0
        public static ReCaptchaResponse VerifyCaptcha(string secret, string response)
        {
            //    if (request != null)
            //    {
            ReCaptchaResponse responses;

            using (System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient())
            {
                var values = new Dictionary <string,
                                             string> {
                    {
                        "secret",
                        secret
                    },
                    {
                        "response",
                        response
                    }
                };
                var content        = new System.Net.Http.FormUrlEncodedContent(values);
                var Response       = hc.PostAsync("https: //www.google.com/recaptcha/api/siteverify", content).Result;
                var responseString = Response.Content.ReadAsStringAsync().Result;
                if (!string.IsNullOrWhiteSpace(responseString))
                {
                    responses = JsonConvert.DeserializeObject <ReCaptchaResponse>(responseString);
                    return(responses);
                }

                //Throw error as required
            }
            return(null);
        }
示例#5
0
        private static void do_reportGotShip(GetBattleResultResponse battleResult, int battle_fleetid, string level, string nodeflag)
        {
            if (battleResult == null || battleResult.newShipVO == null || battleResult.newShipVO.Length == 0)
            {
                return;
            }
            var      dic      = new Dictionary <string, string>();
            string   desc     = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[battle_fleetid - 1].ships[0]);

            foreach (UserShip us in battleResult.newShipVO)
            {
                desc += level + "|" + nodeflag + "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                        + "|" + ServerTimer.GetNowServerTime()
                        + "|" + z.instance.getServerName()
                        + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                        + "|" + (WarResultLevel)battleResult.warResult.resultLevel
                        + "|" + battleResult.bossHpLeft
                        + "|" + GameData.instance.UserInfo.detailInfo.collection
                        + "|" + GameData.instance.UserInfo.level
                        + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportdrop", c).Result;
            }
            catch (Exception)
            {
            }
        }
示例#6
0
        private async void btnAttach_Click(object sender, RoutedEventArgs e)
        {
            var sim = new InputSimulator();

            sim.Keyboard
            .ModifiedKeyStroke(VirtualKeyCode.MENU, VirtualKeyCode.TAB)
            .Sleep(500);

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                // Normal press-release key action, optionally repeated several times:
                //     [modifiers -] keyname [/ innerpause] [: repeat] [/ outerpause]
                // Press-and-hold a key, or release a held-down key:
                //     [modifiers -] keyname : direction [/ outerpause]

                var values = new Dictionary <string, string>()
                {
                    { "spec", "t,e,s, t, s-left/50:4/100, c-c/50, c-v/100, c-v" },
                    { "prop1", "hello" },
                    { "prop2", "world" }
                };
                var content  = new System.Net.Http.FormUrlEncodedContent(values);
                var response = await client.PostAsync("http://localhost:2083/" + txtHandle.Text, content);

                string responseString = await response.Content.ReadAsStringAsync();

                appendLog(responseString);
            }
        }
示例#7
0
        private static async void SendExceptionLog()
        {
            try
            {
                var appFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                var file      = await appFolder.GetFileAsync(ErrorLogFilename);

                string errorLogContent = await Windows.Storage.FileIO.ReadTextAsync(file);

                if (errorLogContent == null)
                {
                    return;
                }

                List <KeyValuePair <string, string> > postData = new List <KeyValuePair <string, string> >();
                postData.Add(new KeyValuePair <string, string>("log", errorLogContent));


                using (var httpClient = new System.Net.Http.HttpClient())
                    using (var httpContent = new System.Net.Http.FormUrlEncodedContent(postData))
                        using (var response = await httpClient.PostAsync(ErrorReportPostURL, httpContent))
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                await file.DeleteAsync();
                            }
                        }
            }
            catch { }
        }
示例#8
0
        private System.Net.Http.FormUrlEncodedContent BuildRoomSearchQuerry(string keyword, string authToken)
        {
            //authenticity_token = IZlOXRusFSIipRhoZM6pE1a96Cuk644m6fMF0mHSRkfQgqLL4Ep1RKjvHf % 2BuSCByDfs2XgM94NhrNBQZHgUgtA % 3D % 3D
            //& search % 5Blocations % 5D % 5B % 5D = cherrybrook - 2126
            //& search % 5Bmode % 5D = rooms
            //& search % 5Bmin_budget % 5D =
            //&search % 5Bmax_budget % 5D =
            //&search % 5Bsort % 5D = photos

            var querry = new System.Net.Http.FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("authenticity_token", authToken),
                new KeyValuePair <string, string>("search[locations][]", keyword),
                new KeyValuePair <string, string>("search[mode]", "rooms"),
                new KeyValuePair <string, string>("search[min_budget]", ""),
                new KeyValuePair <string, string>("search[max_budget]", ""),
                new KeyValuePair <string, string>("search[sort]", "photos")
            });

            //var keys = new KeyValuePair<string, string>();
            //keys.ad

            //var token = HtmlEntity.Entitize(authToken);
            //string postString = "authenticity_token=" + token;
            //postString += "&search%5Blocations%5D%5B%5D=" + keyword;
            //postString += "&search%5Bmode%5D=rooms&search%5Bmin_budget%5D=&search%5Bmax_budget%5D=&search%5Bsort%5D=photos";
            //return postString;

            return(querry);
        }
示例#9
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var postData = new System.Net.Http.FormUrlEncodedContent(Request.Form.ToDictionary());
            int seq      = 1;

            if (!string.IsNullOrEmpty(Request.QueryString["seq"]))
            {
                seq = int.Parse(Request.QueryString["seq"].ToString()) + 1;
            }

            if (seq < 5)
            {
                WebFormsActions.Redirect(new BladeSettings(new BladeContent()
                {
                    url         = "/Ajax/BladeWithForm.aspx?seq=" + seq.ToString(),
                    type        = "Post",
                    contentType = "application/x-www-form-urlencoded; charset=UTF-8",
                    data        = postData.ReadAsStringAsync().Result
                })
                {
                    title           = string.Format("Blade with form: #{0}", seq),
                    propertiesBlade = true
                });
            }
        }
示例#10
0
        doPost_NativeResponse (string uri, IEnumerable<KeyValuePair<string, string>> pairs = null)
        {
            System.Net.Http.HttpContent content = null;
            if (pairs != null)
            {
                content = new System.Net.Http.FormUrlEncodedContent(pairs);
            }

            return _httpClient.PostAsync(uri, content);
        }
示例#11
0
        doPost_NativeResponse(string uri, IEnumerable <KeyValuePair <string, string> > pairs = null)
        {
            System.Net.Http.HttpContent content = null;
            if (pairs != null)
            {
                content = new System.Net.Http.FormUrlEncodedContent(pairs);
            }

            return(_httpClient.PostAsync(uri, content));
        }
示例#12
0
        async private Task <string> watchingReservation(string token, string id, string mode)
        {
            util.debugWriteLine("watching reservation post " + token + " " + mode);
            try {
                var handler = new System.Net.Http.HttpClientHandler();
                handler.UseCookies      = true;
                handler.CookieContainer = cc;
                var http = new System.Net.Http.HttpClient(handler);
                handler.UseProxy = true;
                handler.Proxy    = util.httpProxy;


                //var contentStr = "mode=auto_register&vid=" + id + "&token=" + token + "&_=";
                //util.debugWriteLine("reservation " + contentStr);

                var _content = new List <KeyValuePair <string, string> >();
                if (mode == "watching_reservation_regist")
                {
                    _content.Add(new KeyValuePair <string, string>("mode", "auto_register"));
                    _content.Add(new KeyValuePair <string, string>("vid", id));
                    _content.Add(new KeyValuePair <string, string>("token", token));
                    _content.Add(new KeyValuePair <string, string>("_", ""));
                }
                else if (mode == "regist_finished")
                {
                    _content.Add(new KeyValuePair <string, string>("accept", "true"));
                    _content.Add(new KeyValuePair <string, string>("mode", "use"));
                    _content.Add(new KeyValuePair <string, string>("vid", id));
                    _content.Add(new KeyValuePair <string, string>("token", token));
                    _content.Add(new KeyValuePair <string, string>("", ""));
                }
                //var content = new System.Net.Http.StringContent(contentStr);
                var content = new System.Net.Http.FormUrlEncodedContent(_content);
                //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                http.Timeout = TimeSpan.FromSeconds(3);
                var url = "https://live.nicovideo.jp/api/watchingreservation";
                var _t  = http.PostAsync(url, content);
                _t.Wait();
                var _res = _t.Result;
                var res  = await _res.Content.ReadAsStringAsync();

                //			var a = _res.Headers;

                //			if (res.IndexOf("login_status = 'login'") < 0) return null;

//				cc = handler.CookieContainer;

                return(res);
//				return cc;
            } catch (Exception e) {
                util.debugWriteLine("get watching exception " + e.Message + e.StackTrace);
                return(null);
            }
        }
示例#13
0
        private Models.OAuthResponse fetchToken(string path, IEnumerable <KeyValuePair <string, string> > formParams, string basicAuthorization, Models.TokenType tokenType)
        {
            using (var request_ = new System.Net.Http.FormUrlEncodedContent(formParams))
            {
                request_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", basicAuthorization);

                var response = _httpClient.PostAsync(path, request_).Result;

                return(HandleApiResponse(response, tokenType));
            }
        }
示例#14
0
        public async Task <IActionResult> RefreshToken(int userId, RefreshToken refreshToken)
        {
            var userEnt = await _userService.GetOrdUserAsync(userId);

            if (userEnt == null)
            {
                return(NotFound(new { Error = $"A user with an Id of '{userId}' could not be found." }));
            }

            var values = new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >
            {
                new System.Collections.Generic.KeyValuePair <string, string>("client_id", "orderbuddy_password"),
                new System.Collections.Generic.KeyValuePair <string, string>("client_secret", "7baeb4e4"),
                new System.Collections.Generic.KeyValuePair <string, string>("grant_type", "refresh_token"),
                new System.Collections.Generic.KeyValuePair <string, string>("refresh_token", refreshToken.Token)
            };

            var formEnCoded = new System.Net.Http.FormUrlEncodedContent(values);

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

                var response = await httpClient.PostAsync("https://accounts.orderbuddy.co.za/connect/token", formEnCoded); // URL will change to accounts.orderbuddy.co.za

                if (response != null)
                {
                    var httpStringContent = await response.Content.ReadAsStringAsync();

                    var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(httpStringContent);

                    if (responseObject != null)
                    {
                        if (responseObject.error != null)
                        {
                            return(BadRequest(new { Error = "Invalid token." }));
                        }

                        var token = new
                        {
                            AccessToken  = responseObject.access_token,
                            RefreshToken = responseObject.refresh_token,
                            ExpiresIn    = responseObject.expires_in
                        };

                        return(Ok(token));
                    }
                }
            }

            return(BadRequest(new { Error = "Could not refresh token." }));
        }
示例#15
0
        static string Post(string path, Dictionary <string, string> dict)
        {
            var httpClient = new System.Net.Http.HttpClient();

            httpClient.BaseAddress = new Uri(BaseURL);
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var body = new System.Net.Http.FormUrlEncodedContent(dict);

            // response
            var response = httpClient.PostAsync(path, body).Result;
            var data     = response.Content.ReadAsStringAsync().Result;

            return(data);
        }
示例#16
0
        /// <summary>
        /// Retrieves a token value used for authentication of API calls.
        /// </summary>
        /// <param name="ct">Cancellation token instance. Use CancellationToken.None if not needed.</param>
        /// <returns></returns>
        private async Task <TokenResponse> GetTokenAsync(CancellationToken ct = default(CancellationToken))
        {
            if (this.Token == null)
            {
                var dic = new Dictionary <string, string>();
                dic.Add("grant_type", "client_credentials");
                dic.Add("client_id", this.AppID);
                dic.Add("client_secret", this.AppSecret);
                var contents = new System.Net.Http.FormUrlEncodedContent(dic.ToKeyValuePairList());

                this.Token = await this.PostAsync <TokenResponse>("/oauth2/token", ct, contents);
            }

            return(this.Token);
        }
示例#17
0
        /// <summary>
        /// 通过 POST 提交某些内容到服务器,并读取响应结果; 默认下将使用 utf8 编解码;
        /// 注意,content-type 为 application/x-www-form-urlencoded;
        /// 即将 请求参数编码为 client_id=testclient&client_secret=testclientsecret 的形式并 Post
        /// </summary>
        /// <param name="url">提交的url</param>
        /// <param name="postContent">需要提交的内容</param>
        /// <returns></returns>
        public static async Task <T> FormUrlEncodedPostGetResult <T>(string url, IEnumerable <KeyValuePair <string, string> > postContent)
        {
            System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(postContent);
            content.Headers.Add("conent-type", "application/x-www-form-urlencoded");
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var asyncResult = await client.PostAsync(url, content);

            var result = await asyncResult.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(result))
            {
                return(default(T));
            }
            return(JsonConvert.DeserializeObject <T>(result));
        }
示例#18
0
        // https://stackoverflow.com/questions/15176538/net-httpclient-how-to-post-string-value
        public async Task <bool> GetAccessToken(string pincode)
        {
            AuthorizationError = false;

            string api = Global.Instance.AuthorizationEndpoint;

            var content = new System.Net.Http.FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("client_id", Global.Instance.ProductID),
                new KeyValuePair <string, string>("client_secret", Global.Instance.ProductSecret),
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("code", pincode)
            });

            using (System.Net.Http.HttpClient client = HttpApiClient())
            {
                try
                {
                    System.Net.Http.HttpResponseMessage response = await client.PostAsync(api, content);

                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (responseContent.Contains("error"))
                    {
                        ErrorMessage = Parse.ErrorMessage(responseContent);
                        return(false);
                    }

                    string token = Parse.AccessToken(responseContent);

                    if (!string.IsNullOrEmpty(token))
                    {
                        AuthToken = token;

                        Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                        localSettings.Values["NestAccessToken"] = token;
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    ErrorMessage = ex.Message;
                }

                return(false);
            }
        }
示例#19
0
        public static Boolean RequestAccessTokenRefresh(String _strClientId, String _strClientSecret)
        {
            Boolean bRet = false;

            try
            {
                // Make the call to get an access token using a refresh token

                //Create HttpClient
                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();

                Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                if ((localSettings.Values["refreshToken"] == null))
                {
                    return(false);
                }
                String strRefreshToken = Convert.ToString(localSettings.Values["refreshToken"]);
                var    values          = new Dictionary <string, string>
                {
                    { "grant_type", "refresh_token" },
                    { "refresh_token", strRefreshToken },
                    { "client_id", _strClientId },
                    { "client_secret", _strClientSecret }
                };

                var content = new System.Net.Http.FormUrlEncodedContent(values);

                var response = httpClient.PostAsync(" https://api.amazon.com/auth/o2/token", content).Result;

                var    responseString = response.Content.ReadAsStringAsync().Result;
                var    arrResp        = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <String, String> >(responseString);
                String strAccessToken = arrResp["access_token"];
                strRefreshToken = arrResp["refresh_token"];
                localSettings.Values["accessToken"]        = strAccessToken;
                localSettings.Values["accessTokenExpires"] = DateTime.Now.AddHours(1).ToString("MM/dd/yy HH:mm:ss");
                localSettings.Values["refreshToken"]       = strRefreshToken;
                bRet = true;
            }
            catch (Exception)
            {
                //results.Equals(ex.ToString());
                //textBox.Text = ex.ToString();
            }
            return(bRet);
        }
示例#20
0
        public static void Reset()
        {
            // Clear trace messages
            DecisionServiceTrace.Clear();

            // Reset DecisionService objects
            if (Service != null)
            {
                Service.Flush();
                Service.Dispose();
            }

            Explorer             = null;
            Configuration        = null;
            Service              = null;
            LastBlobModifiedDate = new DateTimeOffset();

            // Reset all settings via the command center (storage, metadata, etc...)
            using (var client = new System.Net.Http.HttpClient())
            {
                var values = new Dictionary <string, string>
                {
                    { "token", appToken }
                };
                var content = new System.Net.Http.FormUrlEncodedContent(values);

                var responseTask = client.PostAsync(
                    // TODO: use https
                    commandCenterAddress + "/Application/Reset",
                    content
                    );
                responseTask.Wait();

                var response = responseTask.Result;
                if (!response.IsSuccessStatusCode)
                {
                    var t2 = response.Content.ReadAsStringAsync();
                    t2.Wait();
                    System.Diagnostics.Trace.TraceError("Failed to reset application. Result : {0}, Reason: {1}, Details: {2}",
                                                        t2.Result, response.ReasonPhrase, response.Headers.ToString());
                }
            }
        }
        public void FindWithLanguage_WhenIsNull_ReturnDefaultLanguage()
        {
            var ss = new System.Net.Http.FormUrlEncodedContent(new Dictionary <string, string>
            {
                ["grant_type"]    = "client_credentials",
                ["client_id"]     = "console",
                ["client_secret"] = "388D45FA-B36B-4988-BA59-B187D329C207"
            });

            //Arrange
            string languageCode = null;

            //Act
            var result = _templates.FindWithLanguage(languageCode);

            //Assert
            Assert.NotNull(result);
            Assert.Null(result.LanguageCode);
        }
        /// <summary>
        /// Posts a message back to the browser, via App Engine.
        /// </summary>
        /// <param name="postStatusUrl">Where to post the status to?</param>
        /// <param name="postStatusToken">An additional value to post.</param>
        /// <param name="status">The status to report to the browser.</param>
        /// <param name="result">The result or error message to report to the browser.</param>
        private void PublishStatus(string postStatusUrl, string postStatusToken,
                                   string status, string result = null)
        {
            var content = new System.Net.Http.FormUrlEncodedContent(
                new Dictionary <string, string>()
            {
                { "status", status },
                { "token", postStatusToken },
                { "result", result },
                { "host", System.Environment.MachineName }
            });
            var task = init.HttpClient.PostAsync(postStatusUrl, content);

            task.Wait();
            if (task.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new FatalException(task.Result.ToString());
            }
        }
示例#23
0
        public async Task Create_one()
        {
            // Arrange.
            var requestUrl  = "/api/echos";
            var requestBody = new System.Net.Http.FormUrlEncodedContent(new System.Collections.Generic.Dictionary <string, string> {
                { "message", "Hello World" }
            });

            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

            // Act.
            var response = await _client.PostAsync(requestUrl, requestBody);

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

            // Assert.
            Assert.IsTrue(response.IsSuccessStatusCode);
        }
示例#24
0
        public static Boolean RequestAccessToken(String _strAuthCode, String _strClientId, String _strClientSecret, String _strOAuthReidrectURL)
        {
            Boolean bRet = false;

            try
            {
                // Make the call to get an access token.

                //Create HttpClient
                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();

                // grant_type=authorization_code&code=ANBzsjhYZmNCTeAszagk&client_id=1234&client_secret=1234&redirect_uri=https%3A%2F%2Flocalhost
                var values = new Dictionary <string, string>
                {
                    { "grant_type", "authorization_code" },
                    { "code", _strAuthCode },
                    { "client_id", _strClientId },
                    { "client_secret", _strClientSecret },
                    { "redirect_uri", _strOAuthReidrectURL }
                };

                var content = new System.Net.Http.FormUrlEncodedContent(values);

                var response = httpClient.PostAsync(" https://api.amazon.com/auth/o2/token", content).Result;

                var    responseString  = response.Content.ReadAsStringAsync().Result;
                var    arrResp         = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <String, String> >(responseString);
                String strAccessToken  = arrResp["access_token"];
                String strRefreshToken = arrResp["refresh_token"];
                Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                localSettings.Values["accessToken"]        = strAccessToken;
                localSettings.Values["accessTokenExpires"] = DateTime.Now.AddHours(1).ToString("MM/dd/yy HH:mm:ss");
                localSettings.Values["refreshToken"]       = strRefreshToken;
                return(true);
            }
            catch (Exception)
            {
                //results.Equals(ex.ToString());
                //textBox.Text = ex.ToString();
            }
            return(bRet);
        }
示例#25
0
        public Task <bool> PutData(string url, List <KeyValuePair <string, string> > data)
        {
            TaskCompletionSource <bool> TCS = new TaskCompletionSource <bool>();

            var uri = new Uri(url);

            System.Net.Http.HttpClient  httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpContent content    = new System.Net.Http.FormUrlEncodedContent(data);

            string text = string.Empty;


            Task <System.Net.Http.HttpResponseMessage> response = httpClient.PutAsync(uri, content);

            response.ContinueWith(r =>
            {
                TCS.SetResult(r.Result.IsSuccessStatusCode);
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            return(TCS.Task);
        }
示例#26
0
        private static void do_reportBuildShip(int dockid, BSLOG bSLOG, GetShipData getShipData)
        {
            if (getShipData == null || getShipData.shipVO == null)
            {
                return;
            }
            var      dic      = new Dictionary <string, string>();
            string   desc     = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[0].ships[0]);
            UserShip us       = getShipData.shipVO;

            {
                desc += bSLOG.oil.ToString() + "|" +
                        bSLOG.ammo.ToString() + "|" +
                        bSLOG.steel.ToString() + "|" +
                        bSLOG.al.ToString() + "|" +
                        bSLOG.timetick.ToString() + "|" +
                        bSLOG.buildreturntype.ToString() +

                        "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                        + "|" + ServerTimer.GetNowServerTime()
                        + "|" + z.instance.getServerName()
                        + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                        + "|" + GameData.instance.UserInfo.detailInfo.collection
                        + "|" + GameData.instance.UserInfo.level
                        + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportbuild", c).Result;
            }
            catch (Exception)
            {
            }
        }
        public static string GetMSGraphToken()
        {
            string jsonResponse     = null;
            string oauth2_token_url = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], ConfigurationManager.AppSettings["ida:Tenant"], "/oauth2/token?api-version=1.0");

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri("~/Home/Welcome.cshtml");
                var content = new System.Net.Http.FormUrlEncodedContent(new KeyValuePair <string, string>[]
                {
                    new KeyValuePair <string, string>("grant_type", "client_credentials"),
                    new KeyValuePair <string, string>("resource", "https://graph.microsoft.com"),
                    new KeyValuePair <string, string>("client_id", ConfigurationManager.AppSettings["ida:ClientId"]),
                    new KeyValuePair <string, string>("client_secret", ConfigurationManager.AppSettings["ida:ClientSecret"])
                });

                var responseData = client.PostAsync(oauth2_token_url, content).Result;
                jsonResponse = responseData.Content.ReadAsStringAsync().Result;
            }

            return(jsonResponse);
        }
示例#28
0
        private static void do_reportBuildShip(int dockid, BSLOG bSLOG, GetShipData getShipData)
        {
            if (getShipData == null || getShipData.shipVO == null )
            {
                return;
            }
            var dic = new Dictionary<string, string>();
            string desc = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[0].ships[0]);
            UserShip us = getShipData.shipVO;
            {
                desc += bSLOG.oil.ToString() + "|" +
                    bSLOG.ammo.ToString() + "|" +
                    bSLOG.steel.ToString() + "|" +
                    bSLOG.al.ToString() + "|" +
                    bSLOG.timetick.ToString() + "|" +
                    bSLOG.buildreturntype.ToString()  +

                    "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                    + "|" + ServerTimer.GetNowServerTime()
                    + "|" + z.instance.getServerName()
                    + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                    + "|" + GameData.instance.UserInfo.detailInfo.collection
                    + "|" + GameData.instance.UserInfo.level
                    + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportbuild", c).Result;
            }
            catch (Exception)
            {

            }
        }
示例#29
0
        internal async void AddItemToCategory()
        {
            //Remove the item from ItemList, Add item to CategoryItems and add Item to Category.Item on the backend
            if (SelectedItem != null)
            {
                var item = SelectedItem;

                var values = new Dictionary <string, string>
                {
                    { "CategorylId", Category.Id.ToString() },
                    { "ItemId", item.Id.ToString() }
                };
                var content = new System.Net.Http.FormUrlEncodedContent(values);
                var result  = await Client.HttpClient.PutAsync("http://localhost:65177/api/Category/Item", content);

                if (result.StatusCode == HttpStatusCode.OK)
                {
                    CategoryItems.Add(item);
                    ItemList.Remove(item);
                }
            }
        }
示例#30
0
        internal async void AddTaskToCategory()
        {
            //Add task to CategoryTasks, Remove the task from TaskList and add Task to Category.Task on the backend

            if (SelectedTask != null)
            {
                var task   = SelectedTask;
                var values = new Dictionary <string, string>
                {
                    { "CategorylId", Category.Id.ToString() },
                    { "TaskId", task.Id.ToString() }
                };
                var content = new System.Net.Http.FormUrlEncodedContent(values);
                var result  = await Client.HttpClient.PutAsync("http://localhost:65177/api/Category/Task", content);

                if (result.StatusCode == HttpStatusCode.OK)
                {
                    CategoryTasks.Add(task);
                    TaskList.Remove(task);
                }
            }
        }
        public static async Task <string> GetAuthorizeToken()
        {
            // Initialization.
            string result = string.Empty;

            // Posting.
            using (var client = new System.Net.Http.HttpClient())
            {
                // Setting Base address.
                client.BaseAddress = new Uri("https://localhost:44340/");

                // Setting content type.
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                // Initialization.
                var response      = new System.Net.Http.HttpResponseMessage();
                var allIputParams = new List <KeyValuePair <string, string> >();

                // Convert Request Params to Key Value Pair.
                allIputParams.Add(new KeyValuePair <string, string>("grant_type", "password"));
                allIputParams.Add(new KeyValuePair <string, string>("username", "admin"));
                allIputParams.Add(new KeyValuePair <string, string>("password", "adminPass"));

                // URL Request parameters.
                var requestParams = new System.Net.Http.FormUrlEncodedContent(allIputParams);

                // HTTP POST
                response = await client.PostAsync("Token", requestParams).ConfigureAwait(false);

                // Verification
                if (response.IsSuccessStatusCode)
                {
                    // Reading Response.
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }

            return(result);
        }
示例#32
0
        /// <summary>
        /// Gets and caches a valid token so the bot can send messages.
        /// </summary>
        /// <returns>The token</returns>
        private async Task <string> GetBotApiToken()
        {
            // Check to see if we already have a valid token
            string token = memoryCache.Get("token")?.ToString();

            if (string.IsNullOrEmpty(token))
            {
                // we need to get a token.
                using (
                    var client = new System.Net.Http.HttpClient())
                {
                    // Create the encoded content needed to get a token
                    var parameters = new Dictionary <string, string>
                    {
                        { "client_id", this.botCredentials.ClientId },
                        { "client_secret", this.botCredentials.ClientSecret },
                        { "scope", "https://graph.microsoft.com/.default" },
                        { "grant_type", "client_credentials" }
                    };
                    var content = new System.Net.Http.FormUrlEncodedContent(parameters);

                    // Post
                    var response = await client.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", content);

                    // Get the token response
                    var tokenResponse = await response.Content.ReadAsJsonAsync <Entities.TokenResponse>();

                    token = tokenResponse.access_token;

                    // Cache the token fo 15 minutes.
                    memoryCache.Set(
                        "token",
                        token,
                        new DateTimeOffset(DateTime.Now.AddMinutes(15)));
                }
            }

            return(token);
        }
示例#33
0
        public Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Net.Http.HttpClient client)
        {
            List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>();
            foreach (var key in SettingsTable.Keys)
                parameters.Add(new KeyValuePair<string, string>(key, BoolToResponse(SettingsTable[key])));

            parameters.Add(new KeyValuePair<string, string>("submit", SUBMIT));
            var postData = new System.Net.Http.FormUrlEncodedContent(parameters);

            return client.PostAsync("member.php", postData);
        }
示例#34
0
        private static void do_reportGotShip(GetBattleResultResponse battleResult, int battle_fleetid, string level, string nodeflag)
        {
            if(battleResult == null || battleResult.newShipVO == null || battleResult.newShipVO.Length ==0)
            {
                return;
            }
            var dic = new Dictionary<string, string>();
            string desc = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[battle_fleetid -1].ships[0]);
            foreach(UserShip us in battleResult.newShipVO)
            {
                desc += level + "|" + nodeflag + "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                    + "|" + ServerTimer.GetNowServerTime()
                    + "|" + z.instance.getServerName()
                    + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                    + "|" + (WarResultLevel)battleResult.warResult.resultLevel
                    + "|" + battleResult.bossHpLeft
                    + "|" + GameData.instance.UserInfo.detailInfo.collection
                    + "|" + GameData.instance.UserInfo.level
                    + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportdrop", c).Result;
            }
            catch (Exception)
            {

            }
        }
        public IActionResult Authorized(string code)
        {
            OauthInfo oai = OauthRepository.Get();

            if (code == null)
                return View(oai);

            oai.authCode = code;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            var url = "https://graph.api.smartthings.com/oauth/token";

            List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
            parms.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
            parms.Add(new KeyValuePair<string, string>("code", oai.authCode));
            parms.Add(new KeyValuePair<string, string>("client_id", oai.clientKey));
            parms.Add(new KeyValuePair<string, string>("client_secret", oai.secretKey));
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");
            parms.Add(new KeyValuePair<string, string>("redirect_uri", authorizedUrl));

            var content = new System.Net.Http.FormUrlEncodedContent(parms);
            var response = client.PostAsync(url, content);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get Auth Code Error: " + response.Result.StatusCode.ToString());
                return View(oai);
            }

            // Save the interim result
            var val = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Result.Content.ReadAsStringAsync().Result);
            oai.accessToken = val["access_token"];
            oai.expiresInSeconds = Convert.ToInt32(val["expires_in"]);
            oai.tokenType = val["token_type"];
            OauthRepository.Save(oai);

            // Get the endpoint info
            client = new System.Net.Http.HttpClient();
            url = "https://graph.api.smartthings.com/api/smartapps/endpoints";

            System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            msg.Headers.Add("Authorization", $"Bearer {oai.accessToken}");

            response = client.SendAsync(msg);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get EndPoints Error: " + response.Result.StatusCode.ToString());
                return View(oai);
            }

            string jsonString = response.Result.Content.ReadAsStringAsync().Result;
            oai.endpoints = JsonConvert.DeserializeObject<List<OauthEndpoint>>(jsonString);

            OauthRepository.Save(oai);

            // Install the Zones
            SmartThingsRepository.InstallDevices(this.Request.Host.Value);
            return View(oai);

        }
 /// <summary>
 /// Posts a message back to the browser, via App Engine.
 /// </summary>
 /// <param name="postStatusUrl">Where to post the status to?</param>
 /// <param name="postStatusToken">An additional value to post.</param>
 /// <param name="status">The status to report to the browser.</param>
 /// <param name="result">The result or error message to report to the browser.</param>
 private void PublishStatus(string postStatusUrl, string postStatusToken,
     string status, string result = null)
 {
     var content = new System.Net.Http.FormUrlEncodedContent(
         new Dictionary<string, string>() {
         {"status", status},
         {"token", postStatusToken},
         {"result", result},
         {"host", System.Environment.MachineName}});
     var task = init.HttpClient.PostAsync(postStatusUrl, content);
     task.Wait();
     if (task.Result.StatusCode != System.Net.HttpStatusCode.OK)
     {
         throw new FatalException(task.Result.ToString());
     }
 }