private static XmlDocument SimpleRequest(string method, ref Uri uri, HttpRequestFilter filter, out WebHeaderCollection responseHeaders, params string[] parameters)
        {
            string absUri = UrlHelper.SafeToAbsoluteUri(uri);

            if (parameters.Length > 0)
            {
                FormData formData = new FormData(true, parameters);

                if (absUri.IndexOf('?') == -1)
                    absUri += "?" + formData.ToString();
                else
                    absUri += "&" + formData.ToString();
            }

            RedirectHelper.SimpleRequest simpleRequest = new RedirectHelper.SimpleRequest(method, filter);
            HttpWebResponse response = RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(simpleRequest.Create));
            try
            {
                uri = response.ResponseUri;
                responseHeaders = response.Headers;
                return ParseXmlResponse(response);
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
        }
 /// <summary>
 ///     提交表单
 /// </summary>
 /// <param name="request">请求对象</param>
 /// <param name="formData">表单数据</param>
 /// <returns>响应文本</returns>
 public static string Post(this HttpWebRequest request, FormData formData)
 {
     return request
         .Method(HttpWebRequestMethod.POST)
         .SetContentType("application/x-www-form-urlencoded;charset=utf-8")
         .Write(formData)
         .GetResponseString();
 }
        public void GetQueryStringForSimpleResponseReturnsEncodedResponse()
        {
            var message = "test message";
            var data = new FormData() { Response = message };
            var expectedMessage = WebUtility.UrlEncode(message);

            var result = data.ToString();

            Assert.Contains(expectedMessage, result);
            Assert.Equal($"response={expectedMessage}", result);
        }
 /// <summary>
 ///     提交表单和文件
 /// </summary>
 /// <param name="request">请求对象</param>
 /// <param name="formData">表单数据</param>
 /// <param name="files">文件</param>
 /// <returns>响应文本</returns>
 public static string Post(this HttpWebRequest request, FormData formData,
                           IDictionary<string, FileItem> files)
 {
     // 随机分隔线
     var boundary = DateTime.Now.Ticks.ToString("X");
     return request
         .Method(HttpWebRequestMethod.POST)
         .SetContentType("multipart/form-data; boundary=" + boundary)
         .Write(formData, files, boundary)
         .GetResponseString();
 }
        public void GetQueryStringForFullResponseReturnsEncodedResponse()
        {
            var message = "test message";
            var status = HttpStatusCode.Created;
            var delay = 100;
            var data = new FormData { Response = message, Status = status, Delay = delay };
            var expectedMessage = WebUtility.UrlEncode(message);
            var expected = $"response={expectedMessage}&status={(int)HttpStatusCode.Created}&delay={delay}";

            var result = data.ToString();

            Assert.Contains(expectedMessage, result);
            Assert.Equal(expected, result);
        }
        public async Task PostRequestWithFormDataReturnsEchoMessage()
        {
            var request = $"{CONST_ServerUrl}/api/echo/";
            var data = new FormData() {Delay = 10, Status = HttpStatusCode.OK, Response = CONST_Message };

            var result = await this.SendPostAsync(request, data.ToString());
            var response = await result.Content.ReadAsStringAsync();
            var status = result.StatusCode;
            var isSuccess = result.IsSuccessStatusCode;

            Assert.True(isSuccess);
            Assert.Equal(HttpStatusCode.OK, status);
            Assert.Equal(CONST_Message, response);
        }
        /// <summary>
        ///     写入提交数据
        /// </summary>
        private static HttpWebRequest Write(this HttpWebRequest request, FormData formData)
        {
            if (formData.Count > 0)
            {
                //var formDataString = formData.GetFormDataString();
                request.Write(Encoding.UTF8.GetBytes(formData.ToString()));
#if DEBUG
                request.ShowDebugInfo();
                Debug.WriteLine("Form Data:");
                var i = 0;
                foreach (var data in formData)
                {
                    Debug.WriteLine("[{0,-2}] {1,-15} : {2}", ++i, data.Key, data.Value);
                }
#endif
            }
            return request;
        }
Example #8
0
        /// <summary>
        /// 上传媒体。
        /// 注意:如果上传失败,会抛出WxMenuException异常
        /// </summary>
        /// <param name="media"></param>
        /// <returns></returns>
        public RemoteMedia Upload(LocalMedia media)
        {
            var checkRet = MediaChecker(media);
            if (!checkRet.IsSuccess)
                throw new WxException(-9999, checkRet.ErrMsg);//todo:考虑是否设计新的Exception类,以区分异常是由微信抛出还是本地抛出

            var param = new FormData()
            {
                {"access_token", AccessToken},
                {"type", media.MediaType}
            };
            var rs = new HttpHelper(UploadUrl).Upload(param, media.MediaPath);
            var ret = JsonConvert.DeserializeObject<RemoteMedia>(rs);
            if (string.IsNullOrEmpty(ret.MediaID))
            {
                var ex = JsonConvert.DeserializeObject<BasicResult>(rs);
                throw new WxException(ex);
            }
            return ret;
        }
 public void GetQueryStringForEmptyDataReturnsEmpty()
 {
     var data = new FormData();
     Assert.Empty(data.ToString());
 }
        public ApplicationContent(
            IApp page = null,
            IApplicationWebServiceX service = null)
        {
            // need absolute path when docked..
            page.style1.href = page.style1.href;

            // first order of business.
            // enable drop zone.
            var dz = new DropZone();


            dz.Container.AttachToDocument();
            dz.Container.Hide();

            var StayAlertTimer = default(Timer);
            var DoRefresh = default(Action);

            #region StayAlert
            Action<string> StayAlert =
                transaction_id =>
                {
                    StayAlertTimer = new Timer(
                        delegate
                        {
                            service.GetTransactionKeyAsync(
                                id =>
                                {
                                    if (id == transaction_id)
                                        return;

                                    // shot down during flight?
                                    if (!StayAlertTimer.IsAlive)
                                        return;

                                    Console.WriteLine("StayAlert " + new { id, transaction_id });

                                    DoRefresh();
                                }
                            );
                        }
                    );

                    StayAlertTimer.StartInterval(5000);
                };
            #endregion


            DoRefresh =
                delegate
                {
                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();

                    page.output.Clear();

                    new FileLoading().Container.AttachTo(page.output);

                    service.EnumerateFilesAsync(
                        y:
                        (
                            long ContentKey,
                            string ContentValue,
                            string ContentType,
                            long ContentBytesLength
                        ) =>
                        {
                            var e = new FileEntry();

                            #region ContentValue
                            e.ContentValue.value = ContentValue.TakeUntilLastIfAny(".");
                            e.ContentValue.onchange +=
                                delegate
                                {
                                    var ext = ContentValue.SkipUntilLastOrEmpty(".");

                                    if (ext != "")
                                        ext = "." + ext;

                                    ContentValue = e.ContentValue.value + ext;


                                    Console.WriteLine("before update!");

                                    service.UpdateAsync(
                                        ContentKey,
                                        ContentValue,
                                        // null does not really work?
                                        delegate
                                        {
                                            Console.WriteLine("update done!");
                                        }
                                    );

                                    e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                                };
                            e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                            e.open.target = Target;

                            #endregion

                            e.ContentType.innerText = ContentBytesLength + " bytes " + ContentType;


                            #region Delete
                            e.Delete.WhenClicked(
                                delegate
                                {
                                    //e.ContentValue.style.textDecoration = ""

                                    if (StayAlertTimer != null)
                                        StayAlertTimer.Stop();

                                    e.Container.style.backgroundColor = "red";

                                    service.DeleteAsync(
                                        ContentKey,
                                        delegate
                                        {

                                            DoRefresh();
                                        }
                                    );
                                }
                            );
                            #endregion


                            e.Container.AttachTo(page.output);



                            Console.WriteLine(
                                new { ContentKey, ContentValue, ContentType, ContentBytesLength }
                            );

                        },

                        done: transaction_id =>
                        {
                            Console.WriteLine(new { transaction_id });
                            new FileLoadingDone().Container.AttachTo(page.output);

                            StayAlert(transaction_id);
                        }
                    );
                };

            #region ondrop

            var TimerHide = new Timer(
                delegate
                {
                    dz.Container.Hide();
                }
            );

            Action<DragEvent> ondragover =
                evt =>
                {
                    //Console.WriteLine("ondragover");


                    evt.stopPropagation();
                    evt.preventDefault();

                    // ondragover { type = Files }

                    //foreach (var type in evt.dataTransfer.types)
                    //{
                    //    Console.WriteLine("ondragover " + new { type });
                    //}


                    if (evt.dataTransfer.types.Contains("Files"))
                    {


                        evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.

                        dz.Container.Show();
                        TimerHide.Stop();
                    }

                    //}

                    //Console.WriteLine(" Native.Document.body.ondragover");
                };

            Native.Document.body.ondragover += ondragover;
            dz.Container.ondragover += ondragover;

            //dz.Container.ondragstart +=
            //    evt =>
            //    {
            //        Console.WriteLine("ondragstart");


            //        evt.stopPropagation();
            //        evt.preventDefault();
            //    };

            dz.Container.ondragleave +=
                 evt =>
                 {
                     //Console.WriteLine("ondragleave");

                     //Console.WriteLine(" dz.Container.ondragleave");

                     evt.stopPropagation();
                     evt.preventDefault();

                     TimerHide.StartTimeout(90);
                 };

            dz.Container.ondrop +=
                evt =>
                {
                    //Console.WriteLine("ondrop");

                    TimerHide.StartTimeout(90);

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();

                    // can we use a webClient yet?
                    var xhr = new IXMLHttpRequest();

                    // does not work for chrome?
                    //xhr.setRequestHeader("WebServiceMethod", "FileStorageUpload");

                    // which server?
                    xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/FileStorageUpload");

                    // http://stackoverflow.com/questions/13870853/how-to-upload-files-in-web-workers-when-formdata-is-not-defined

                    //var c = new WebClient();

                    ////c.UploadData(
                    //c.UploadProgressChanged +=
                    //    (sender, args) =>
                    //    {

                    //    };

                    //c.UploadFileAsync(



                    #region send
                    var d = new FormData();

                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            d.append("file" + index, f, f.name);
                        }
                    );

                    xhr.InvokeOnComplete(
                        delegate
                        {
                            Console.WriteLine("upload complete!");

                            DoRefresh();
                        }
                    );

                    var upload = new Uploading();

                    upload.Container.AttachTo(page.output);
                    // http://www.matlus.com/html5-file-upload-with-progress/
                    xhr.upload.onprogress +=
                        e =>
                        {
                            var p = (int)(e.loaded * 100 / e.total) + "%";

                            upload.status = p;

                            Console.WriteLine("upload.onprogress " + new { e.total, e.loaded });
                        };

                    xhr.send(d);
                    #endregion


                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();



                };
            #endregion




            DoRefresh();
        }
Example #11
0
            public HttpWebRequest Create(string uri)
            {
                FormData formData = new FormData(false,
                    "Email", _username,
                    "Passwd", _password,
                    "service", _service,
                    "source", _source);

                if (_captchaToken != null && _captchaValue != null)
                {
                    formData.Add("logintoken", _captchaToken);
                    formData.Add("logincaptcha", _captchaValue);
                }

                HttpWebRequest request = HttpRequestHelper.CreateHttpWebRequest(uri, true);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                using (Stream inStream = formData.ToStream())
                using (Stream outStream = request.GetRequestStream())
                    StreamHelper.Transfer(inStream, outStream);

                return request;
            }
        public async Task GetRequestWithFormDataReturnsEchoMessage()
        {
            var query = new FormData() {Delay = 20, Status = HttpStatusCode.NotFound, Response = CONST_Message };
            var data = WebUtility.UrlEncode(query.Response);
            var request = $"{CONST_ServerUrl}/api/echo/{data}/?{query}";

            this.output.WriteLine("GET Request ->{0}", request);

            var result = await this.SendGetAsync(request);
            var response = await result.Content.ReadAsStringAsync();
            var status = result.StatusCode;
            var isSuccess = result.IsSuccessStatusCode;

            Assert.False(isSuccess);
            Assert.Equal(HttpStatusCode.NotFound, status);
            Assert.Equal(CONST_Message, WebUtility.UrlDecode(response));
        }
 public void Send(FormData data)
 {
 }
Example #14
0
 public void Send(FormData data)
 {
 }
Example #15
0
        /// <summary>
        /// 下载媒体文件。
        /// 如果下载成功,返回值的ErrMsg属性携带保存的文件全路径
        /// </summary>
        /// <param name="mediaId"></param>
        /// <param name="filePath">
        ///     保存下载的文件的本地文件名或目录(以\结尾)。
        ///     如果为目录,则文件名为微信响应的文件名。
        ///     如果文件已经存在,则会覆盖原文件。
        /// </param>
        /// <returns>如果成功,ErrMsg属性携带保存的文件全路径</returns>
        public BasicResult Download(string mediaId, string filePath)
        {
            var param = new FormData
            {
                {"access_token", AccessToken},
                {"media_id", mediaId}
            };

            var url = string.Format("{0}?{1}", DownLoadUrl, param.Format());
            var request = HttpHelper.CreateRequest(url);
            var response = request.GetResponse();
            using (var stream = response.GetResponseStream())
            {
                var disposition = response.Headers["Content-disposition"];
                if (string.IsNullOrEmpty(disposition))
                {
                    var s = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
                    return JsonConvert.DeserializeObject<BasicResult>(s);
                }

                filePath = filePath.EndsWith(@"\")
                    ? string.Format("{0}{1}", filePath, Regex.Match(disposition, "(?<=filename\\s*=\\s*\\\"?)[^\\\"]+", RegexOptions.IgnoreCase))
                    : filePath;
                var fs = new FileStream(filePath, FileMode.OpenOrCreate);
                try
                {
                    var buffer = new byte[128 * 1024]; //128K
                    int i;
                    while ((i = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, i);
                    }

                    return BasicResult.GetSuccess(filePath);
                }
                finally
                {
                    fs.Close();
                }
            }
        }
Example #16
0
 public Url(string urlString)
 {
     _urlString = urlString;
     _data = new FormData();
 }