Пример #1
0
        /// <summary>
        /// Sends request with form data
        /// </summary>
        /// <typeparam name="R">Result type</typeparam>
        /// <param name="method">HTTP method</param>
        /// <param name="url">URL for request</param>
        /// <param name="pars">Request parameters</param>
        /// <returns>Async result object</returns>
        public async Task <R> SendForm <R>(HttpMethod method, string url, Dictionary <string, string> pars)
        {
            R result = default(R);
            await Retry.Do(
                RetryTimes,
                RetryDelay,
                async() =>
            {
                var client    = await GetHttpClient(url).ConfigureAwait(false);
                client.Method = method.ToString();
                using (var content = new FormUrlEncodedContent(pars))
                {
                    client.ContentType = content.Headers.ContentType.ToString();

                    using (var output = await client.GetRequestStreamAsync().ConfigureAwait(false))
                    {
                        await content.CopyToAsync(output).ConfigureAwait(false);
                    }
                }
                using (var response = (HttpWebResponse)await client.GetResponseAsync().ConfigureAwait(false))
                {
                    if (!response.IsSuccessStatusCode())
                    {
                        return(await LogBadResponse(response).ConfigureAwait(false));
                    }

                    result = await response.ReadAsAsync <R>().ConfigureAwait(false);
                }
                return(true);
            },
                GeneralExceptionProcessor).ConfigureAwait(false);

            return(result);
        }
        private void DoPostData()
        {
            if (_parameters.Count > 0)
            {
                _client.Method      = "POST";
                _client.ContentType = "application/x-www-form-urlencoded";

                using (var req = _client.GetRequestStream())
                    using (var content = new FormUrlEncodedContent(_parameters))
                    {
                        content.CopyToAsync(req);
                    }
            }
        }
        private byte[] generateFormData()
        {
            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("resource", "https://vault.azure.net"),
                new KeyValuePair <string, string>("client_id", ClientId),
                new KeyValuePair <string, string>("client_secret", ClientSecret),
                new KeyValuePair <string, string>("grant_type", "client_credentials")
            });

            var stream = new MemoryStream();

            formContent.CopyToAsync(stream).Wait();
            return(stream.ToArray());
        }
        public async Task <bool> SendFeedbackAsync(FeedbackTeacherModel model)
        {
            try
            {
                Dictionary <string, string> formData = new Dictionary <string, string>()
                {
                    ["__VIEWSTATE"]          = model.__ViewState,
                    ["__VIEWSTATEGENERATOR"] = model.__VIEWSTATEGENERATOR,
                    ["__EVENTVALIDATION"]    = model.__EVENTVALIDATION,
                    ["ctl00$ContentPlaceHolder1$reload$ctl00$chkList"] = model.FeedbackChoice[0].ToString(),
                    ["ctl00$ContentPlaceHolder1$reload$ctl01$chkList"] = model.FeedbackChoice[1].ToString(),
                    ["ctl00$ContentPlaceHolder1$reload$ctl02$chkList"] = model.FeedbackChoice[2].ToString(),
                    ["ctl00$ContentPlaceHolder1$reload$ctl03$chkList"] = model.FeedbackChoice[3].ToString(),
                    ["ctl00$ContentPlaceHolder1$reload$ctl04$chkList"] = model.FeedbackChoice[4].ToString(),
                    ["ctl00$ContentPlaceHolder1$reload$ctl05$chkList"] = model.FeedbackChoice[5].ToString(),
                    ["ctl00$ContentPlaceHolder1$txtComment"]           = model.Comment,
                    ["ctl00$ContentPlaceHolder1$btSendFeedback"]       = "Gửi ý kiến"
                };

                HttpWebRequest req = WebRequest.CreateHttp($"{FschoolDomain}{model.ID}");
                req.Method      = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                _acct.AddSessionIdCookie(req);

                using (var reqStream = await req.GetRequestStreamAsync())
                {
                    using (var urlEncoded = new FormUrlEncodedContent(formData))
                    {
                        await urlEncoded.CopyToAsync(reqStream);

                        var test = await urlEncoded.ReadAsStringAsync();
                    }

                    using (var resp = await req.GetResponseAsync())
                    {
                        using (var stream = resp.GetResponseStream())
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                string res = await reader.ReadToEndAsync();


                                if (await AccountModel.IsLoginPage(res))
                                {
                                    throw new InvalidSessionIDException($"{_acct.Email} session id: {_acct.SessionID} is invalid or expired, please request a new one and try again");
                                }

                                // Validate feedback
                                HtmlDocument doc = new HtmlDocument();
                                doc.LoadHtml(res);
                                return(doc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/section[2]/form/div/div/div/div[3]/div/div[1]/span/font") != null);
                            }
                        }
                    }
                }
            }
            catch (InvalidSessionIDException) // We don't wrap this exception
            {
                throw;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Failed to send feedback", e);
            }
        }