Esempio n. 1
0
        /// <summary>
        /// <paramref name="address"/>에 <paramref name="data"/> 문자열을 전송합니다. (HTTP나 FTP나 같습니다)
        /// </summary>
        /// <param name="webClient"><see cref="WebClient"/> 인스턴스</param>
        /// <param name="address">전송할 주소</param>
        /// <param name="method">전송 방법 (HTTP는 POST, FTP는 STOR)</param>
        /// <param name="data">전송할 문자열</param>
        /// <returns></returns>
        public static Task <string> UploadStringTask(this WebClient webClient, Uri address, string method, string data)
        {
            webClient.ShouldNotBeNull("webClient");
            address.ShouldNotBeNull("address");
            // data.ShouldNotBeEmpty("data");

            if (IsDebugEnabled)
            {
                log.Debug("지정된 주소에 문자열을 비동기 Upload합니다... address=[{0}], method=[{1}], data=[{2}]",
                          address.AbsoluteUri, method, data.EllipsisChar(255));
            }

            var tcs = new TaskCompletionSource <string>(address);

            UploadStringCompletedEventHandler handler = null;

            handler =
                (s, e) => EventAsyncPattern.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadStringCompleted -= handler);
            webClient.UploadStringCompleted += handler;

            try {
                webClient.UploadStringAsync(address, method, data, tcs);
            }
            catch (Exception ex) {
                if (log.IsWarnEnabled)
                {
                    log.Warn("WebClient를 이용하여 문자열을 비동기 Upload 하는데 실패했습니다. address=[{0}]", address.AbsoluteUri);
                    log.Warn(ex);
                }

                webClient.UploadStringCompleted -= handler;
                tcs.TrySetException(ex);
            }
            return(tcs.Task);
        }
        public void CreateMessage(string body, UploadStringCompletedEventHandler handler, string sentiment = null, string in_reply_to_msg_id = null, string chartUri = null)
        {
            StringBuilder postData = new StringBuilder("body=");

            postData.Append(Uri.EscapeDataString(body));

            if (in_reply_to_msg_id != null)
            {
                postData.Append("&in_reply_to_message_id=");
                postData.Append(in_reply_to_msg_id);
            }

            if (chartUri != null)
            {
                postData.Append("&chart=");
                postData.Append(chartUri);
            }

            if (sentiment != null)
            {
                postData.Append("&sentiment=");
                postData.Append(sentiment);
            }

            string queryUri = API_BASE_URL_SECURE + "messages/create.json?access_token=" + AccessToken;

            System.Diagnostics.Debug.WriteLine("StockTwits API: posting to " + queryUri);
            WebClient client = new WebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            client.Headers[HttpRequestHeader.UserAgent]   = API_USER_AGENT;
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(handler);
            client.UploadStringAsync(new Uri(queryUri), "POST", postData.ToString());
        }
Esempio n. 3
0
        public WebClient ServicePost <T>(string api, UploadStringCompletedEventHandler eventHandler, T postObject)
        {
            string postData = "";

            if (postObject != null)
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream())
                {
                    xs.Serialize(ms, postObject);
                    ms.Seek(0, SeekOrigin.Begin);
                    byte[] b = new byte[ms.Length];
                    ms.Read(b, 0, (int)ms.Length);
                    postData = System.Text.Encoding.UTF8.GetString(b, 0, (int)ms.Length);
                }
            }

            WebClient wc  = new WebClient();
            Uri       uri = new Uri(string.Format("{0}/{1}", PartyServiceUrl, api));

            wc.UseDefaultCredentials  = false;
            wc.Credentials            = this.Credentials;
            wc.UploadStringCompleted += eventHandler;
            wc.Headers[HttpRequestHeader.ContentType] = "application/xml";
            wc.UploadStringAsync(uri, postData);

            return(wc);
        }
        public void PostMessageOnWall(string message, UploadStringCompletedEventHandler handler)
        {
            WebClient client = new WebClient();

            client.UploadStringCompleted += handler;
            client.UploadStringAsync(new Uri("https://graph.facebook.com/me/feed"), "POST", "message=" + HttpUtility.UrlEncode(message) + "&access_token=" + Global.GAccessToken);
        }
Esempio n. 5
0
        public static void getRequest(string request, UploadStringCompletedEventHandler callback)
        {
            WebClient wc = new WebClient();

            wc.UploadStringCompleted += callback;
            wc.UploadStringAsync(new Uri(address), "POST", "text=" + request);
        }
Esempio n. 6
0
        public static void XmlRpcExecMethod(string methodName, UploadStringCompletedEventHandler completed)
        {
            try
            {
                WebClient req = new WebClient();

                string genParams = GetParams();

                //MessageBox.Show(genParams);

                string command = @"<?xml version=""1.0""?><methodCall><methodName>" + methodName + @"</methodName><params>" + genParams + @"</params></methodCall>";
                byte[] bytes = Encoding.Unicode.GetBytes(command);

                req.Headers[HttpRequestHeader.ContentLength] = bytes.Length.ToString();
                req.Headers[HttpRequestHeader.ContentType] = "text/xml";
                req.Headers[HttpRequestHeader.AcceptEncoding] = "text";
                req.Headers[HttpRequestHeader.Accept] = "*/*";
                req.Headers[HttpRequestHeader.Connection] = "keep-alive";

                if (App.Session_LoadSession("xf_session").Replace(" ", "") != "")  //hdp.
                    req.Headers[HttpRequestHeader.Cookie] = "xf_session=" + App.Session_LoadSession("xf_session");  //hdp.

                req.UploadStringAsync(new Uri(Oauth.sApiAddress, UriKind.Absolute), "POST", command);
                req.UploadStringCompleted += completed;
            }
            catch (Exception ex)
            {
                //BugSenseHandler.Instance.SendExceptionAsync(ex);

                MessageBox.Show("Hata oluştu : exec-method");
            }
        }
Esempio n. 7
0
        public static void XmlRpcExecMethod(string methodName, UploadStringCompletedEventHandler completed)
        {
            try
            {
                WebClient req = new WebClient();

                string genParams = GetParams();

                //MessageBox.Show(genParams);

                string command = @"<?xml version=""1.0""?><methodCall><methodName>" + methodName + @"</methodName><params>" + genParams + @"</params></methodCall>";
                byte[] bytes   = Encoding.Unicode.GetBytes(command);

                req.Headers[HttpRequestHeader.ContentLength]  = bytes.Length.ToString();
                req.Headers[HttpRequestHeader.ContentType]    = "text/xml";
                req.Headers[HttpRequestHeader.AcceptEncoding] = "text";
                req.Headers[HttpRequestHeader.Accept]         = "*/*";
                req.Headers[HttpRequestHeader.Connection]     = "keep-alive";

                if (App.Session_LoadSession("xf_session").Replace(" ", "") != "")                                  //hdp.
                {
                    req.Headers[HttpRequestHeader.Cookie] = "xf_session=" + App.Session_LoadSession("xf_session"); //hdp.
                }
                req.UploadStringAsync(new Uri(Oauth.sApiAddress, UriKind.Absolute), "POST", command);
                req.UploadStringCompleted += completed;
            }
            catch (Exception ex)
            {
                //BugSenseHandler.Instance.SendExceptionAsync(ex);

                MessageBox.Show("Hata oluştu : exec-method");
            }
        }
        public void ExchangeAccessToken(UploadStringCompletedEventHandler handler)
        {
            WebClient client = new WebClient();

            client.UploadStringCompleted += handler;
            client.UploadStringAsync(new Uri(GetAccessTokenExchangeUrl(FacebookClient.Instance.AccessToken)), "POST", "");
        }
Esempio n. 9
0
 public static void httpPost(Uri resource, string postString, UploadStringCompletedEventHandler e)
 {
     WebClient client = new WebClient();
     client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
     client.UploadStringCompleted += e;
     client.UploadStringAsync(resource, "POST", postString);
 }
Esempio n. 10
0
        /// <summary>Uploads data in a string to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the data should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the data.</param>
        /// <param name="data">The data to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <string> UploadStringTask(
            this WebClient webClient, Uri address, string method, string data)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <string>(address);

            // Setup the callback event handler
            UploadStringCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadStringCompleted -= handler);
            webClient.UploadStringCompleted += handler;

            // Start the async work
            try
            {
                webClient.UploadStringAsync(address, method, data, tcs);
            }
            catch (Exception exc)
            {
                // If something goes wrong kicking off the async work,
                // unregister the callback and cancel the created task
                webClient.UploadStringCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task that represents the async operation
            return(tcs.Task);
        }
 public BraintreeHttpClient(string merchantServerURL, UploadStringCompletedEventHandler handler)
 {
     _uri = new Uri(merchantServerURL, UriKind.Absolute);
     _webClient = new WebClient();
     _webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
     _webClient.Encoding = Encoding.UTF8;
     _webClient.UploadStringCompleted += handler;
 }
Esempio n. 12
0
 public BraintreeHttpClient(string merchantServerURL, UploadStringCompletedEventHandler handler)
 {
     _uri       = new Uri(merchantServerURL, UriKind.Absolute);
     _webClient = new WebClient();
     _webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
     _webClient.Encoding = Encoding.UTF8;
     _webClient.UploadStringCompleted += handler;
 }
        /// <summary>
        /// Helper method to upload a string from a web service asynchronously (POST).
        /// </summary>
        public static void UploadStringAsync(Uri uri, object userState, string data, UploadStringCompletedEventHandler callback)
        {
            System.Diagnostics.Debug.WriteLine(uri.ToString());
            WebClient wc = new WebClient();

            wc.UploadStringCompleted += callback;
            wc.UploadStringAsync(uri, null, data, userState);
        }
Esempio n. 14
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// uploadstringcompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this UploadStringCompletedEventHandler uploadstringcompletedeventhandler, Object sender, UploadStringCompletedEventArgs e, AsyncCallback callback)
        {
            if (uploadstringcompletedeventhandler == null)
            {
                throw new ArgumentNullException("uploadstringcompletedeventhandler");
            }

            return(uploadstringcompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Post" /> class.
 /// </summary>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="id">The identifier.</param>
 /// <param name="e">The e.</param>
 /// <param name="actionName">Name of the action.</param>
 public Delete(string controllerName, int id, UploadStringCompletedEventHandler e = null, string actionName = "")
 {
     var api = new WebApi(controllerName);
     var webClient = new RapWebClient {CookieContainer = RapClientCookie.Current};
     webClient.UploadStringCompleted += e;
     webClient.UploadStringAsync(string.IsNullOrEmpty(actionName) ? 
         new Uri(api.Delete(id)) : 
         new Uri(api.DeleteByAction(id, actionName)), "DELETE", "");
 }
Esempio n. 16
0
        private void ReturnToThisPhone(object sender, RoutedEventArgs e)
        {
            firstStep = new DownloadStringCompletedEventHandler(DidDownloadCurrentState);
            secondStep = new UploadStringCompletedEventHandler(DidTakeOver);

            var x = new WebClient();
            x.DownloadStringCompleted += firstStep;
            x.DownloadStringAsync(new Uri("http://localhost:8008/services/music"));
        }
Esempio n. 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Post" /> class.
 /// </summary>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="payLoad">The pay load.</param>
 /// <param name="e">The e.</param>
 /// <param name="methodUrl">The method URL after the controller name from web api.</param>
 public Post(string controllerName, object payLoad, UploadStringCompletedEventHandler e = null,
     string methodUrl = "")
 {
     var api = new WebApi(controllerName);
     var url = new Uri(api.Post() + methodUrl);
     var webClient = new RapWebClient {CookieContainer = RapClientCookie.Current};
     webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
     webClient.UploadStringCompleted += e;
     webClient.UploadStringAsync(url, "POST", JsonConvert.SerializeObject(payLoad));
 }
Esempio n. 18
0
        protected virtual void OnUploadStringCompleted(UploadStringCompletedEventArgs args)
        {
            CompleteAsync();
            UploadStringCompletedEventHandler handler = UploadStringCompleted;

            if (handler != null)
            {
                handler(this, args);
            }
        }
Esempio n. 19
0
        /**
         * http://stocktwits.com/developers/docs/api#streams-symbols-docs
         */
        public void GetStreamOfSymbols(string[] symbols, UploadStringCompletedEventHandler handler, int since = 0, int max = 30)
        {
            string    queryUri = "https://api.stocktwits.com/api/2/streams/symbols.json?access_token=" + AccessToken;
            WebClient client   = new WebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            client.Headers[HttpRequestHeader.UserAgent]   = API_USER_AGENT;
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(handler);
            client.UploadStringAsync(new Uri(queryUri), "GET", "symbols=" + String.Join(",", symbols));
        }
Esempio n. 20
0
        public void GetAccessToken(string code, UploadStringCompletedEventHandler handler)
        {
            string    POSTData = "client_id=" + ClientID + "&client_secret=" + ClientSecret + "&code=" + code + "&grant_type=authorization_code&redirect_uri=" + RedirectUri;
            WebClient client   = new WebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            client.Headers[HttpRequestHeader.UserAgent]   = API_USER_AGENT;
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(handler);
            client.UploadStringAsync(new Uri(RequestTokenPath), "POST", POSTData);
        }
Esempio n. 21
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="Put" /> class.
 /// </summary>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="id">The identifier.</param>
 /// <param name="payLoad">The pay load.</param>
 /// <param name="e">The e.</param>
 /// <param name="methodUrl">The method URL.</param>
 public Put(string controllerName, int id, object payLoad, UploadStringCompletedEventHandler e = null,
     string actionName = "")
 {
     var api = new WebApi(controllerName);
     var webClient = new RapWebClient {CookieContainer = RapClientCookie.Current};
     webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
     webClient.UploadStringCompleted += e;
     webClient.UploadStringAsync(string.IsNullOrEmpty(actionName) ?
         new Uri(api.Put(id)) :
         new Uri(api.PutByAction(id, actionName)), "PUT", JsonConvert.SerializeObject(payLoad));
 }
Esempio n. 22
0
    // API Calls - Posts Methods (Public Access Methods)

    public static async void getRouteSummaryForStop(int stop, UploadStringCompletedEventHandler handler)
    {
        try
        {
            await Post(new Dictionary <String, String>(), argsBase, stop, -1, handler);
        }
        catch
        {
            MessageBox.Show("There was an issue getting data, is your data connection working?");
        }
    }
Esempio n. 23
0
        public static void SalvarPerfilServidor(Perfil perfil, UploadStringCompletedEventHandler callback)
        {
            string metodo = perfil.Id == "" ? "POST" : "PUT";
            string url = perfil.Id == "" ? HttpHelper.URL_PERFILS :HttpHelper.URL_PERFILS + "/" + perfil.Id;
            string json = HttpHelper.serializar(perfil);

            WebClient client = new WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.UploadStringCompleted += callback;
            client.UploadStringAsync(new Uri(url, UriKind.Absolute), metodo, json);
        }
Esempio n. 24
0
    private static Task <XDocument> Post(WebClient webClient, Uri uri, string data, UploadStringCompletedEventHandler handler)
    {
        var taskCompletionSource = new TaskCompletionSource <XDocument>();

        webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";

        webClient.UploadStringCompleted += handler;

        webClient.UploadStringAsync(uri, data);
        return(taskCompletionSource.Task);
    }
Esempio n. 25
0
    // API Calls - Posts Methods (Public Access Methods)

    public static async void getRouteSummaryForStop(int stop, UploadStringCompletedEventHandler handler)
    {
        try
        {
            await Post(new Dictionary<String, String>(), argsBase, stop, -1, handler);
        }
        catch
        {
            MessageBox.Show("There was an issue getting data, is your data connection working?");
        }
    }
Esempio n. 26
0
        protected override void Write(AsyncLogEventInfo info)
        {
            try
            {
                var url    = new Uri(this.Url.Render(info.LogEvent));
                var layout = this.Layout.Render(info.LogEvent);
                var json   = JObject.Parse(layout).ToString(); // make sure the json is valid
                var client = new WebClient();

                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

                UploadStringCompletedEventHandler cb = null;
                cb = (s, e) =>
                {
                    if (cb != null)
                    {
                        client.UploadStringCompleted -= cb;
                    }

                    if (e.Error != null)
                    {
                        if (e.Error is WebException)
                        {
                            var we = e.Error as WebException;
                            try
                            {
                                var result = JObject.Load(new JsonTextReader(new StreamReader(we.Response.GetResponseStream())));
                                var error  = result.GetValue("error");
                                if (error != null)
                                {
                                    info.Continuation(new Exception(result.ToString(), e.Error));
                                    return;
                                }
                            }
                            catch (Exception) { info.Continuation(new Exception("Failed to send log event to ElasticSearch", e.Error)); }
                        }

                        info.Continuation(e.Error);

                        return;
                    }

                    info.Continuation(null);
                };

                client.UploadStringCompleted += cb;
                client.UploadStringAsync(url, "PUT", json);
            }
            catch (Exception ex)
            {
                info.Continuation(ex);
            }
        }
Esempio n. 27
0
    private static Task<XDocument> Post(WebClient webClient, Uri uri, string data, UploadStringCompletedEventHandler handler)
    {

        var taskCompletionSource = new TaskCompletionSource<XDocument>();

        webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";

        webClient.UploadStringCompleted += handler;

        webClient.UploadStringAsync(uri, data);
        return taskCompletionSource.Task;
    }
Esempio n. 28
0
        public static void SalvarPerfilServidor(Perfil perfil, UploadStringCompletedEventHandler callback)
        {
            string metodo = perfil.Id == "" ? "POST" : "PUT";
            string url    = perfil.Id == "" ? HttpHelper.URL_PERFILS :HttpHelper.URL_PERFILS + "/" + perfil.Id;
            string json   = HttpHelper.serializar(perfil);

            WebClient client = new WebClient();

            client.Headers["Content-Type"] = "application/json";
            client.UploadStringCompleted  += callback;
            client.UploadStringAsync(new Uri(url, UriKind.Absolute), metodo, json);
        }
Esempio n. 29
0
        /// <summary>
        /// 根据关键字获取公交站点
        /// </summary>
        /// <param name="key">根据关键字查询公交站点</param>
        /// <param name="callback">结果处理函数</param>
        /// <param name="spliter">站点分隔符</param>
        /// <param name="maxNum">最大结果数</param>
        void GetBusStopName(string key, UploadStringCompletedEventHandler callback, string spliter = "$", int maxNum = 8)
        {
            key = CommFun.Escape(key.Trim());
            string    svrUrl = ServerAddress + "?svcType=SDS&_method=GetBusStop";
            string    data   = "_method=GetBusStop&key=" + key + "&spliter=" + spliter + "&encode=0&num=" + maxNum;
            WebClient cli    = new WebClient();

            cli.Encoding = Encoding.UTF8;
            cli.Headers[HttpRequestHeader.ContentType]     = "type=text/xml;charset=utf-8";
            cli.Headers[HttpRequestHeader.ContentEncoding] = "utf-8";
            cli.UploadStringCompleted += callback;
            cli.UploadStringAsync(new Uri(svrUrl), data);
        }
        internal static IObservable <string> UploadStringAsObservable(this WebClient client, Uri address, string method, string data, string username = "", string password = "", object userToken = null)
        {
            return(Observable.Create <string>(observer =>
            {
                UploadStringCompletedEventHandler handler = (sender, args) =>
                {
                    if (args.UserState != userToken)
                    {
                        return;
                    }

                    if (args.Cancelled)
                    {
                        observer.OnCompleted();
                    }
                    else if (args.Error != null)
                    {
                        observer.OnError(args.Error);
                    }
                    else
                    {
                        try
                        {
                            observer.OnNext(args.Result);
                            observer.OnCompleted();
                        }
                        catch (Exception ex)
                        {
                            observer.OnError(ex);
                        }
                    }
                };

                client.UploadStringCompleted += handler;
                try
                {
                    if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
                    {
                        client.SetAuthenticationHeaders(username, password);
                    }
                    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                    client.UploadStringAsync(address, method, data, userToken);
                }
                catch (Exception ex)
                {
                    observer.OnError(ex);
                }

                return () => client.UploadStringCompleted -= handler;
            }));
        }
Esempio n. 31
0
    static LevelSerializer()
    {
        LevelSerializer.Deserialized = delegate
        {
        };
        LevelSerializer.GameSaved = delegate
        {
        };
        LevelSerializer.SuspendingSerialization = delegate
        {
        };
        LevelSerializer.ResumingSerialization = delegate
        {
        };
        LevelSerializer.StoreComponent = delegate
        {
        };
        LevelSerializer._collectionCount = 0;
        LevelSerializer.Progress         = delegate
        {
        };
        WebClient webClient = LevelSerializer.webClient;

        if (LevelSerializer.< > f__mg$cache0 == null)
        {
            LevelSerializer.< > f__mg$cache0 = new UploadDataCompletedEventHandler(LevelSerializer.HandleWebClientUploadDataCompleted);
        }
        webClient.UploadDataCompleted += LevelSerializer.< > f__mg$cache0;
        WebClient webClient2 = LevelSerializer.webClient;

        if (LevelSerializer.< > f__mg$cache1 == null)
        {
            LevelSerializer.< > f__mg$cache1 = new UploadStringCompletedEventHandler(LevelSerializer.HandleWebClientUploadStringCompleted);
        }
        webClient2.UploadStringCompleted += LevelSerializer.< > f__mg$cache1;
        LevelSerializer._stopCases.Add(typeof(PrefabIdentifier));
        UnitySerializer.AddPrivateType(typeof(AnimationClip));
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            UnitySerializer.ScanAllTypesForAttribute(delegate(Type tp, Attribute attr)
            {
                LevelSerializer.createdPlugins.Add(Activator.CreateInstance(tp));
            }, assembly, typeof(SerializerPlugIn));
            UnitySerializer.ScanAllTypesForAttribute(delegate(Type tp, Attribute attr)
            {
                LevelSerializer.CustomSerializers[((ComponentSerializerFor)attr).SerializesType] = (Activator.CreateInstance(tp) as IComponentSerializer);
            }, assembly, typeof(ComponentSerializerFor));
        }
        LevelSerializer.SavedGames = new Index <string, List <LevelSerializer.SaveEntry> >();
    }
Esempio n. 32
0
        public static void call_async(string address, string data, UploadStringCompletedEventHandler onComplete)
        {
            Console.WriteLine("making async request to: " + address);

            WebClient client = new WebClient();

            Debug.Assert(!string.IsNullOrEmpty(data));
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            if (onComplete != null)
            {
                client.UploadStringCompleted += onComplete;
            }
            client.UploadStringAsync(new Uri(BASE_URL + address), data);
        }
Esempio n. 33
0
        public void update_async(string playerId, UploadStringCompletedEventHandler onComplete = null, params string[] updateData)
        {
            var param = new StringBuilder();

            param.Append("token=");
            param.Append(token);

            for (int i = 0; i < updateData.Length; ++i)
            {
                param.Append("&" + updateData[i]);
            }

            call_async("Player/" + playerId + "/update", param.ToString(), onComplete);
        }
Esempio n. 34
0
        public WebClient ServiceDelete(string action, UploadStringCompletedEventHandler eventHandler)
        {
            string postData = " ";

            WebClient wc  = new WebClient();
            Uri       uri = new Uri(string.Format("{0}/{1}", PartyServiceUrl, action));

            wc.UseDefaultCredentials  = false;
            wc.Credentials            = this.Credentials;
            wc.UploadStringCompleted += eventHandler;
            wc.UploadStringAsync(uri, postData);

            return(wc);
        }
Esempio n. 35
0
        /// <summary>
        /// 获取公交换乘方案
        /// </summary>
        /// <param name="startStop">起始站点</param>
        /// <param name="endStop">结束站点</param>
        /// <param name="callback">结果处理函数</param>
        /// <param name="returnXml">是否以XML形式返回结果</param>
        void GetBusChangeRlt(string startStop, string endStop, UploadStringCompletedEventHandler callback, bool returnXml = false)
        {
            startStop = CommFun.Escape(startStop.Trim());
            endStop   = CommFun.Escape(endStop.Trim());
            String    returnType = returnXml ? "0" : "1";
            string    svrUrl     = ServerAddress + "?svcType=SDS&_method=GetBusWay";
            string    data       = "_method=GetBusWay&staPos=" + startStop + "&endPos=" + endStop + "&encode=0&outputType=" + returnType;
            WebClient cli        = new WebClient();

            cli.Encoding = Encoding.UTF8;
            cli.Headers[HttpRequestHeader.ContentType]     = "type=text/xml;charset=utf-8";
            cli.Headers[HttpRequestHeader.ContentEncoding] = "utf-8";
            cli.UploadStringCompleted += callback;
            cli.UploadStringAsync(new Uri(svrUrl), data);
        }
Esempio n. 36
0
 public LinkBDD(String function_name, Dictionary<String, String> post_data, UploadStringCompletedEventHandler callback)
 {
     WebClient client = new WebClient();
     client.UploadStringCompleted += callback;
     client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
     client.Encoding = Encoding.UTF8;
     String data = String.Empty;
     if (post_data != null)
     { 
         foreach(KeyValuePair<string, string> entry in post_data)
         {
             data += entry.Key + "=" + entry.Value + "&";
         }
     }
     client.UploadStringAsync(new Uri(URL + function_name, UriKind.Absolute), "POST", data);
 }
Esempio n. 37
0
        public void rule_async(string playerId, string action, UploadStringCompletedEventHandler onComplete, params string[] optionalData)
        {
            var param = new StringBuilder();

            param.Append("token=");
            param.Append(token);
            param.Append("&player_id=");
            param.Append(playerId);
            param.Append("&action=");
            param.Append(action);

            for (int i = 0; i < optionalData.Length; ++i)
            {
                param.Append("&" + optionalData[i]);
            }

            call_async("Engine/rule", param.ToString(), onComplete);
        }
        private void SetupErrorHandling(WebClient client)
        {
            UploadStringCompletedEventHandler cb = null;

            cb = (s, e) =>
            {
                if (cb != null)
                {
                    client.UploadStringCompleted -= cb;
                }

                if (!(e.Error is WebException))
                {
                    OnError(e.Error);
                    return;
                }

                try
                {
                    var we = e.Error as WebException;

                    JObject result = JObject.Load(new JsonTextReader(new StreamReader(we.Response.GetResponseStream() ?? Stream.Null)));
                    JToken  error  = result.GetValue("error");

                    if (error != null)
                    {
                        OnError(new Exception(result.ToString(), e.Error));
                        return;
                    }
                }
                catch (Exception)
                {
                    OnError(new Exception("Failed to send log event to ElasticSearch", e.Error));
                }

                OnError(e.Error);
            };

            client.UploadStringCompleted += cb;
        }
Esempio n. 39
0
        /// <summary>Uploads data in a string to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the data should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the data.</param>
        /// <param name="data">The data to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <string> UploadStringTask(this WebClient webClient, Uri address, string method, string data)
        {
            TaskCompletionSource <string>     tcs     = new TaskCompletionSource <string>(address);
            UploadStringCompletedEventHandler handler = null;

            handler = delegate(object sender, UploadStringCompletedEventArgs e) {
                EAPCommon.HandleCompletion <string>(tcs, e, () => e.Result, delegate {
                    webClient.UploadStringCompleted -= handler;
                });
            };
            webClient.UploadStringCompleted += handler;
            try
            {
                webClient.UploadStringAsync(address, method, data, tcs);
            }
            catch (Exception exception)
            {
                webClient.UploadStringCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
    /// <summary>Uploads data in a string to the specified resource, asynchronously.</summary>
    /// <param name="webClient">The WebClient.</param>
    /// <param name="address">The URI to which the data should be uploaded.</param>
    /// <param name="method">The HTTP method that should be used to upload the data.</param>
    /// <param name="data">The data to upload.</param>
    /// <returns>A Task containing the data in the response from the upload.</returns>
    public static Task <string> UploadStringTaskAsync(this WebClient webClient, Uri address, string method, string data)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource <string>(address);

        // Setup the callback event handler
        UploadStringCompletedEventHandler handler = null;

        handler = (sender, e) => TaskServices.HandleEapCompletion(tcs, true, e, () => e.Result, () => webClient.UploadStringCompleted -= handler);
        webClient.UploadStringCompleted += handler;

        // Start the async operation.
        try { webClient.UploadStringAsync(address, method, data, tcs); }
        catch
        {
            webClient.UploadStringCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return(tcs.Task);
    }
Esempio n. 41
0
    private static async Task<XDocument> Post(Dictionary<string, string> headers, string data, int stop, int route, UploadStringCompletedEventHandler handler)
    {
        var webClient = new WebClient();
        String uriString = urlBase + (route == -1 ? urlRouteSum : urlNextTrip);
        data = data + "&stopNo=" + stop;
        if (route != -1)
        {
            data = data + "&routeNo=" + route;
        }

        var uri = new Uri(uriString);

        if (headers != null)
        {
            foreach (var key in headers.Keys)
            {
                webClient.Headers[key] = headers[key];
            }
        }

        return await Post(webClient, uri, data, handler);
    }
    public static Task <string> UploadStringTaskAsync(this WebClient webClient, Uri address, string method, string data)
    {
        TaskCompletionSource <string>     tcs     = new TaskCompletionSource <string>(address);
        UploadStringCompletedEventHandler handler = null;

        handler = delegate(object sender, UploadStringCompletedEventArgs e)
        {
            AsyncCompatLibExtensions.HandleEapCompletion <string>(tcs, true, e, () => e.Result, delegate
            {
                webClient.UploadStringCompleted -= handler;
            });
        };
        webClient.UploadStringCompleted += handler;
        try
        {
            webClient.UploadStringAsync(address, method, data, tcs);
        }
        catch
        {
            webClient.UploadStringCompleted -= handler;
            throw;
        }
        return(tcs.Task);
    }
Esempio n. 43
0
        public void ExchangeAccessToken(UploadStringCompletedEventHandler handler)
        {
            try
            {
                WebClient client = new WebClient();
                client.UploadStringCompleted += handler;
                client.UploadStringAsync(new Uri(GetAccessTokenExchangeUrl(FacebookClients.Instance.AccessToken)), "POST", "");

            }
            catch (System.Net.WebException ex)
            {
                MessageBox.Show("Internet connection is not working : " + ex.Message);
            }

            catch (System.Exception ex)
            {
                MessageBox.Show("Error while getting access token : " + ex.Message);
            }
        }
Esempio n. 44
0
File: GS.cs Progetto: engina/SharkIT
 private JObject SecureRequest(string method, JObject parameters, UploadStringCompletedEventHandler handler)
 {
     return _Request("https://cowbell.grooveshark.com/more.php?", method, parameters, handler, null, null);
 }
Esempio n. 45
0
File: GS.cs Progetto: engina/SharkIT
        private JObject _Request(string uri, string method, JObject parameters, UploadStringCompletedEventHandler handler, object handlerToken, JObject headerOverride)
        {
            JObject request = new JObject();
            request.Add("parameters", parameters);
            JObject header = new JObject();
            header.Add("session", m_sid);
            header.Add("client", "jsqueue");
            header.Add("clientRevision", "20120123.02");
            header.Add("privacy", 0);
            // Somehow this uuid is important, and I don't really know what it is, the UUID of the JSQueue flash object ?
            header.Add("uuid", "E1AA0D1D-86EF-4CE2-AEC9-F70358E2535E");
            header.Add("country", m_countryObj);
            request.Add("header", header);
            request.Add("method", method);

            if (headerOverride != null)
            {
                IDictionaryEnumerator e = headerOverride.GetEnumerator();
                while (e.MoveNext())
                {
                    if (header.ContainsKey(e.Key))
                        header[e.Key] = e.Value;
                    else
                        header.Add(e.Key, e.Value);
                }
            }

            string t = GenerateToken(method, (string)header["client"]);
            header.Add("token", t);

            string requestStr = JSON.JsonEncode(request).Replace("\n", "").Replace(" ", "").Replace("\r", "");
            CookieAwareWebClient wc = new CookieAwareWebClient(m_cc);
            wc.UploadStringCompleted += handler;
            wc.UploadStringAsync(new Uri(uri + method), "POST", requestStr, handlerToken);
            RequestSent(this, requestStr);
            return request;
        }
Esempio n. 46
0
 public static async void getNextTripForStop(int stop, int route, UploadStringCompletedEventHandler handler)
 {
     await Post(new Dictionary<String, String>(), argsBase, stop, route, handler);
 }
Esempio n. 47
0
        public void PostMessageOnWall(string message, UploadStringCompletedEventHandler handler)
        {
            try
            {
                WebClient client = new WebClient();
                client.UploadStringCompleted += handler;
                client.UploadStringAsync(new Uri("https://graph.facebook.com/me/feed"), "POST", "message=" + HttpUtility.UrlEncode(message) + "&access_token=" + FacebookClients.Instance.AccessToken);

            }
            catch (System.Net.WebException ex)
            {
                MessageBox.Show("Internet connection is not working : " + ex.Message);
            }

            catch (System.Exception ex)
            {
                MessageBox.Show("Error while posting status on facebook : " + ex.Message);
            }
        }
Esempio n. 48
0
 public void submitCharacter(UploadStringCompletedEventHandler characterUploaded)
 {
     string charFormatString = String.Format("name={0}&classid={1}&lvl=1&exptonext={2}&maxhealth={3}&currenthealth={3}&" +
                                             "maxmana={4}&currentmana={4}&money={5}&strength={6}&agility={7}&intelligence={8}&" +
                                             "speed={9}",
                                             name, (int)type, expToNext, maxHealth,
                                             maxMana, money, strength, agility, intelligence, speed);
     charFormatString += formatAbilities(abilities) + formatItems(inventory) + formatWeapon() + formatChest() + formatHelm()
                         + formatGloves() + formatBoots() + formatLegs();
     MessageBox.Show(charFormatString);
     HttpConnection.httpPost(new Uri("characterCreate.php", UriKind.Relative), charFormatString, characterUploaded);
 }
Esempio n. 49
0
        public bool OAuthPost(string url, UploadStringCompletedEventHandler completed,
            string token = null, string tokenSecret = null)
        {
            string method = "POST";
            if (Account == null || string.IsNullOrEmpty(Account.AccessToken) || string.IsNullOrEmpty(Account.AccessTokenSecret))
            {
                return false;
            }
            if (token == null) {
                token = Account.AccessToken;
                tokenSecret = Account.AccessTokenSecret;
            }

            string normalizedUrl, normalizedRequestParameters;
            /*
            string hash = GenerateSignature(new Uri(url), CONSUMER_KEY, CONSUMER_SECRET,
                token, tokenSecret, method,
                GenerateTimestamp(), GenerateNonce(),
                out normalizedUrl, out normalizedRequestParameters);

            string signedUrl = normalizedUrl + "?" + normalizedRequestParameters
                + "&" + OAuthSignatureKey + "=" + UrlEncode(hash);
             * */
            string hash = GenerateSignature(new Uri(url), CONSUMER_KEY, CONSUMER_SECRET,
                token, tokenSecret, method,
                GenerateTimestamp(), GenerateNonce(),
                out normalizedUrl, out normalizedRequestParameters);

            MyWebClient client = new MyWebClient();
            client.UploadStringCompleted += completed;
            client.UploadStringAsync(new Uri(normalizedUrl),
                normalizedRequestParameters
                + "&" + OAuthSignatureKey + "=" + UrlEncode(hash));
            return true;
        }
Esempio n. 50
0
File: GS.cs Progetto: engina/SharkIT
 private JObject Request(string method, JObject parameters, UploadStringCompletedEventHandler handler, object handlerToken)
 {
     return _Request("http://grooveshark.com/more.php?", method, parameters, handler, handlerToken, null);
 }
Esempio n. 51
0
 public static void RefreshToken(string refreshToken, UploadStringCompletedEventHandler handler)
 {
     string data = GetUrlData(new
     {
         grant_type = HttpUtility.UrlEncode("refresh_token"),
         client_id = HttpUtility.UrlEncode(CLIENTID),
         client_secret = HttpUtility.UrlEncode(CLIENTSECRET),
         refresh_token = HttpUtility.UrlEncode(refreshToken)
     });
     WebClient webclient = new WebClient();
     webclient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
     webclient.UploadStringCompleted += handler;
     webclient.UploadStringAsync(new Uri(TokenUrl), "POST", data);
 }
Esempio n. 52
0
 public static void GetToken(string authcode, UploadStringCompletedEventHandler handler)
 {
     string data = GetUrlData(new
     {
         grant_type = HttpUtility.UrlEncode("authorization_code"),
         client_id = HttpUtility.UrlEncode(CLIENTID),
         client_secret = HttpUtility.UrlEncode(CLIENTSECRET),
         code = HttpUtility.UrlEncode(authcode),
         redirect_uri = HttpUtility.UrlEncode(KB_REDIRECTURL_KANBOXWP_DUMMYPAGE)
     });
     WebClient webclient = new WebClient();
     webclient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
     webclient.UploadStringCompleted += handler;
     webclient.UploadStringAsync(new Uri(TokenUrl), "POST", data);
 }