UploadValuesAsync() public method

public UploadValuesAsync ( System address, System data ) : void
address System
data System
return void
Ejemplo n.º 1
0
        internal static void SendNotifications(IEnumerable<string> apiKeys, string application, string header, string message)
        {
            var data = new NameValueCollection();
            data["AuthorizationToken"] = "";
            data["Body"] = message;
            data["IsImportant"] = IsImportant;
            data["IsSilent"] = IsSilent;
            data["Source"] = application;
            data["TimeToLive"] = TimeToLive;
            data["Title"] = header;
            if (!Validate(data))
            {
                return;
            }

            foreach (var apiKey in apiKeys)
            {
                using (var client = new WebClient())
                {
                    data.Set("AuthorizationToken", apiKey);

                    client.Headers[HttpRequestHeader.ContentType] = RequestContentType;
                    client.UploadValuesAsync(new Uri(RequestUrl), data);
                }
            }
        }
Ejemplo n.º 2
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
Ejemplo n.º 3
0
        private void PostToServer(Session session)
        {
            string oauth    = OAuth;
            string url      = session.Request.PathAndQuery;
            string request  = session.Request.BodyAsString;
            string response = session.Response.BodyAsString;

            request = RequestRegex.Replace(request, "");

            try
            {
                //*
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    wc.Headers["User-Agent"] = "ElectronicObserver/v" + SoftwareInformation.VersionEnglish;

                    if (Proxy != null)
                    {
                        wc.Proxy = Proxy;
                    }

                    System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection
                    {
                        { "token", oauth },
                        // agent key for 'ElectronicObserver'
                        // https://github.com/about518/kanColleDbPost/issues/3#issuecomment-105534030
                        { "agent", "L57Mi4hJeCYinbbBSH5K" },
                        { "url", url },
                        { "requestbody", request },
                        { "responsebody", response }
                    };

                    wc.UploadValuesCompleted += (sender, e) =>
                    {
                        if (e.Error != null)
                        {
                            // 結構頻繁に出るのでレポートは残さない方針で 申し訳ないです
                            //Utility.ErrorReporter.SendErrorReport( e.Error, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) );

                            Utility.Logger.Add(1, string.Format("艦これ統計データベースへの {0} の送信に失敗しました。{1}", url.Substring(url.IndexOf("/api") + 1), e.Error.Message));
                        }
                        else
                        {
                            Utility.Logger.Add(0, string.Format("艦これ統計データベースへ {0} を送信しました。", url.Substring(url.IndexOf("/api") + 1)));
                        }
                    };

                    wc.UploadValuesAsync(new Uri("http://api.kancolle-db.net/2/"), post);
                }
                //*/
            }
            catch (Exception ex)
            {
                Utility.ErrorReporter.SendErrorReport(ex, "艦これ統計データベースへの送信中にエラーが発生しました。");
            }
        }
Ejemplo n.º 4
0
        public override bool Upload(UploadService activeService, ExtendedScreenshot screenshot)
        {
            if (InProgress)
                return false;

            Trace.WriteLine("Starting upload process...", string.Format("FormsUploader.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

            this.ActiveService = activeService;
            this.InProgress = true;
            OnUploadStarted(new EventArgs());

            try
            {
                using (var wc = new WebClient())
                {
                    wc.UploadProgressChanged += UploadProgressChanged;
                    wc.UploadValuesCompleted += UploadValuesCompleted;

                    var bg = new BackgroundWorker();
                    bg.DoWork += (o, a) =>
                        {
                            Trace.WriteLine("Starting stream conversion... ", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));

                            var ImageData = string.Empty;
                            using (var ms = screenshot.EditedScreenshotPNGImageStream())
                                ImageData = Convert.ToBase64String(ms.ToArray());

                            var CurrentUploadValues = new NameValueCollection();
                            foreach (var k in activeService.UploadValues.AllKeys.ToList())
                                CurrentUploadValues.Add(k, activeService.UploadValues[k].Replace("%i", ImageData));

                            Trace.WriteLine("Stream conversion complete.", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));
                            Trace.WriteLine("Starting async upload...", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));

                            wc.UploadValuesAsync(new Uri(activeService.EndpointUrl), CurrentUploadValues);

                            Trace.WriteLine("Upload start complete.", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));
                        };
                    bg.RunWorkerAsync();
                }

                return true;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception occurred during upload: {0}", ex.GetBaseException()), string.Format("FormsUploader.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

                InProgress = false;
                OnUploadEnded(new UploaderEndedEventArgs(ex.GetBaseException()));

                return false;
            }
        }
        public ConnectDatabase(string Email, string Password)
        {
            WebClient client = new WebClient();
            Uri uri = new Uri("http://192.168.100.12/php/includes/process_login_android.php");
            Uri localUri = new Uri("http://localhost/php/android_api.php");
            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("Email", Email);
            parameters.Add("Password", Password);

            client.UploadValuesCompleted += client_UploadValuesCompleted;
            client.UploadValuesAsync(uri, parameters);
        }
Ejemplo n.º 6
0
        private void PostToServer(Titanium.Web.Proxy.EventArguments.SessionEventArgs e)
        {
            string oauth    = OAuth;
            string url      = e.ProxySession.Request.RequestUri.PathAndQuery;
            string request  = e.GetRequestBodyAsString();
            string response = e.GetResponseBodyAsString();

            request = RequestRegex.Replace(request, "");

            try {
                //*
                using (System.Net.WebClient wc = new System.Net.WebClient()) {
                    wc.Headers["User-Agent"] = "ElectronicObserver/v" + SoftwareInformation.VersionEnglish;

                    if (Proxy != null)
                    {
                        wc.Proxy = Proxy;
                    }

                    System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection();
                    post.Add("token", oauth);
                    // agent key for 'ElectronicObserver'
                    // https://github.com/about518/kanColleDbPost/issues/3#issuecomment-105534030
                    post.Add("agent", "L57Mi4hJeCYinbbBSH5K");
                    post.Add("url", url);
                    post.Add("requestbody", request);
                    post.Add("responsebody", response);

                    wc.UploadValuesCompleted += (sender, ev) => {
                        if (ev.Error != null)
                        {
                            // 結構頻繁に出るのでレポートは残さない方針で 申し訳ないです
                            //Utility.ErrorReporter.SendErrorReport( e.Error, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) );

                            Utility.Logger.Add(3, string.Format(LoggerRes.FailedDatabaseSend, url.Substring(url.IndexOf("/api") + 1), ev.Error.Message));
                        }
                        else
                        {
                            Utility.Logger.Add(1, string.Format(LoggerRes.SentDatabase, url.Substring(url.IndexOf("/api") + 1)));
                        }
                    };

                    wc.UploadValuesAsync(new Uri("http://api.kancolle-db.net/2/"), post);
                }
                //*/
            } catch (Exception ex) {
                Utility.ErrorReporter.SendErrorReport(ex, LoggerRes.ErrorDatabaseSending);
            }
        }
Ejemplo n.º 7
0
 private void RefreshOnlineStatus()
 {
     try
     {
         using (var client = new WebClient())
         {
             var data = new NameValueCollection();
             client.UploadValuesAsync(refreshUri, "POST", data);
         }
     }
     catch (Exception ex)
     {
         Logger.Log("Error refreshing online status in PoeTradeOnlineHelper: " + ex.ToString());
     }
 }
        private void RefreshOnlineStatus()
        {
            try
            {
                // Trigger the online signal again when we are about to expire with poe.trade
                var timeSinceLastOnline = DateTime.Now - lastOnlineTime;
                if (timeSinceLastOnline.Minutes > 55)
                {
                    currentlyOnline = false;
                }

                Func<Process, bool> IsPoE = (c => c.MainWindowTitle.Contains("Path of Exile") || c.ProcessName.Contains("PathOfExile"));
                var idleTime = GetIdleTime();

                if (idleTime >= TimeSpan.FromMinutes(10) || !Process.GetProcesses().Any(IsPoE))
                {
                    // Prevent from spamming poe.trade
                    if (currentlyOnline)
                    {
                        using (var client = new WebClient())
                        {
                            var offlineUri = new Uri(refreshUri.OriginalString + "/offline");
                            var data = new NameValueCollection();
                            client.UploadValuesAsync(offlineUri, "POST", data);
                        }
                    }

                    // User is AFK or PoE is not running.
                    currentlyOnline = false;
                    return;
                }

                if (!currentlyOnline)
                {
                    using (var client = new WebClient())
                    {
                        var data = new NameValueCollection();
                        client.UploadValuesAsync(refreshUri, "POST", data);
                        currentlyOnline = true;
                        lastOnlineTime = DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Error refreshing online/offline status in PoeTradeOnlineHelper: " + ex.ToString());
            }
        }
Ejemplo n.º 9
0
        public static void SendNotification(string message, string title, NotificationType type = NotificationType.Info, string notificationUrl = "")
        {
            var url = string.Format("http://{0}:{1}/api/notification", Host, Port);
            var uri = new Uri(url);

            using (var webClient = new WebClient())
            {
                webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                webClient.UploadValuesAsync(uri, "POST", new NameValueCollection{
                    {"message", message},
                    {"title", title},
                    {"type", GetNotificationType(type)},
                    {"url", notificationUrl}
                });
            }
        }
Ejemplo n.º 10
0
 public void PostToImgur(Image image, UISystem.UIButton button)
 {
     uploadButton = button;
     var stream = new MemoryStream();
     image.Save(stream, ImageFormat.Png);
     var inArray = stream.GetBuffer();
     using (var client = new WebClient())
     {
         client.UploadProgressChanged += w_UploadProgressChanged;
         client.UploadValuesCompleted += w_UploadValuesCompleted;
         var values2 = new NameValueCollection();
         values2.Add("key", "eeb1018be96322f46df76ceb36576e08");
         values2.Add("image", Convert.ToBase64String(inArray));
         var data = values2;
         client.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), data);
     }
 }
Ejemplo n.º 11
0
 public void PostToImgur(string filename)
 {
     changeValueEnabled();
     Bitmap bitmap = new Bitmap(filename);
     MemoryStream memoryStream = new MemoryStream();
     bitmap.Save(memoryStream, ImageFormat.Jpeg);
     using (var w = new WebClient())
     {
         w.UploadProgressChanged += new UploadProgressChangedEventHandler(delegate(object send, UploadProgressChangedEventArgs arg)
             {
                 int percent = arg.ProgressPercentage;
                 progressBar.Value = percent > 0 ? (percent < 45 ? percent * 2 : (percent >= 90 ? percent : 90)) : 0;
             });
         this.FormClosing += new FormClosingEventHandler(delegate(object send, FormClosingEventArgs arg)
             {
                 w.CancelAsync();
             });
         var values = new NameValueCollection
         {
             { "key", IMGUR_API_KEY },
             { "image", Convert.ToBase64String(memoryStream.ToArray()) }
         };
         string debug = values.ToString();
         byte[] response = new byte[0];
         w.UploadValuesCompleted += new UploadValuesCompletedEventHandler(delegate(object send, UploadValuesCompletedEventArgs arg)
         {
             if (arg.Cancelled) return;
             response = arg.Result;
             XDocument xDocument = XDocument.Load(new MemoryStream(response));
             bitmap.Dispose();
             _address = (string)xDocument.Root.Element("original_image");
             this.Close();
         });
         w.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), values);
         buttonClose.Click -= buttonClose_Click;
         buttonClose.Click += new EventHandler(delegate(object send, EventArgs arg)
             {
                 w.CancelAsync();
                 changeValueEnabled();
                 buttonClose.Click += buttonClose_Click;
             });
     }
 }
        /// <summary>
        /// Uploads data to the specified resource.
        /// </summary>
        /// <param name="client">The object that uploads to the resource.</param>
        /// <param name="address">The URI of the resource to receive the collection.</param>
        /// <param name="method">The HTTP method used to send data to the resource.  If <see langword="null"/>, the default is POST for HTTP and STOR for FTP.</param>
        /// <param name="values">The collection of data as name/value pairs to send to the resource.</param>
        /// <returns>An observable that caches the response from the server and replays it to observers.</returns>
        public static IObservable <byte[]> UploadValuesObservable(
            this WebClient client,
            Uri address,
            string method,
            NameValueCollection values)
        {
            Contract.Requires(client != null);
            Contract.Requires(address != null);
            Contract.Requires(values != null);
            Contract.Ensures(Contract.Result <IObservable <byte[]> >() != null);

            return(Observable2.FromEventBasedAsyncPattern <UploadValuesCompletedEventHandler, UploadValuesCompletedEventArgs>(
                       handler => handler.Invoke,
                       handler => client.UploadValuesCompleted += handler,
                       handler => client.UploadValuesCompleted -= handler,
                       token => client.UploadValuesAsync(address, method, values, token),
                       client.CancelAsync)
                   .Select(e => e.EventArgs.Result));
        }
Ejemplo n.º 13
0
        public HttpStatusCode PushFeed(string xml, string gsaHost, bool async)
        {
            using (var client = new WebClient())
            {
                var values = new NameValueCollection();
                values["feedtype"] = "incremental";
                values["datasource"] = "web";
                values["data"] = xml;

                try
                {
                    if (async)
                    {
                        client.UploadValuesAsync(new Uri(string.Format("{0}:19900/xmlfeed", gsaHost)), values);
                    }
                    else
                    {
                        client.UploadValues(new Uri(string.Format("{0}:19900/xmlfeed", gsaHost)), values);
                    }
                }
                catch (WebException wex)
                {
                    if (wex.Status == WebExceptionStatus.ProtocolError)
                    {
                        var response = wex.Response as HttpWebResponse;
                        if (response != null)
                        {
                            return response.StatusCode;
                        }
                    }
                    return HttpStatusCode.InternalServerError;
                }
                catch (Exception ex)
                {
                    return HttpStatusCode.InternalServerError;
                }

                return HttpStatusCode.OK;
            }
        }
Ejemplo n.º 14
0
        private async void SinglePhish()
        {
            var form = (HtmlForm)lbForms.SelectedItem;
            var fields = form.Inputs;
            Phish phish = new Phish(fields);
            WebClient wc = new WebClient();

            Uri actionUrl;
            if (!Uri.TryCreate(_uri, form.ActionUrl, out actionUrl)) return;


            await Task.Run(() =>
                         {
                             try
                             {
                                 wc.UploadValuesAsync(actionUrl, phish.NVC);
                             }
                             catch
                             {
                             }
                         });
        }
        public void RegisterClient()
        {
            try
            {
                System.Net.WebClient wclient = new System.Net.WebClient();
                Uri uri = new Uri(ConfigManager.WebService + "/newClient.php");
                NameValueCollection param = new NameValueCollection();

                param.Add("email", client.email);
                param.Add("password", client.HashPassword());
                param.Add("name", client.name);
                param.Add("lastName", client.lastName);
                param.Add("macAddress", DeviceManager.GetMacAdress(this));

                wclient.UploadValuesCompleted += Wclient_UploadValuesCompleted;
                wclient.UploadValuesAsync(uri, param);
            }
            catch (Exception ex)
            {
                Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
Ejemplo n.º 16
0
 public static void DoUploadImage(Image img, string filename, FormMain evntfrm)
 {
     var UploaderClient = new WebClient();
     UploaderClient.Proxy = null; // fix bug http://bytes.com/topic/net/answers/792637-webclient-freezes-ten-seconds-first-connect
     ImageConverter converter = new ImageConverter();
     UploaderClient.UploadProgressChanged += new UploadProgressChangedEventHandler(evntfrm.UploaderClient_UploadProgressChanged);
     UploaderClient.UploadValuesCompleted += new UploadValuesCompletedEventHandler(evntfrm.UploaderClient_UploadValuesCompleted);
     String imagedata;
     using (var stream = new MemoryStream())
     {
         if (Settings.Instance.UploadImageFormat == Settings.Format.Png)
         {
             img.Save(stream, ImageFormat.Png);
         }
         else
         {
             var encparams = new EncoderParameters(1);
             encparams.Param[0] = new EncoderParameter(Encoder.Quality, Settings.Instance.UploadImageQuality);
             img.Save(stream, ImageCodecInfo.GetImageDecoders().FirstOrDefault(fmt => fmt.FormatID == ImageFormat.Jpeg.Guid), encparams);
         }
         imagedata = Convert.ToBase64String(stream.ToArray());
     }
     var values = new NameValueCollection
         {
             { "key", Settings.Instance.ImgurApiKey },
             { "name", filename + "." + Settings.Instance.UploadImageFormat },
             { "image", imagedata }
         };
     string s = "Starting " + filename + " upload in format: " + Settings.Instance.UploadImageFormat + ", " + Utility.FormatBytes(imagedata.Length) + " - " + img.Width + "x" + img.Height;
     int i;
     if (evntfrm.listBoxImages.Items[0].ToString().StartsWith("Up"))
         i = 0;
     else
         i = evntfrm.listBoxImages.Items.Add(s);
     evntfrm.Log("(" + i + ") " + s);
     UploaderClient.UploadValuesAsync(imguri, "POST", values, i);
     UploadingClients.Add(i, UploaderClient);
 }
Ejemplo n.º 17
0
        public static void sendPushNotification(int providerIndex, string key, string title, string message)
        {
            WebClient client = new WebClient();
            NameValueCollection data = new NameValueCollection();
            client.Proxy = null;

            Uri api = null;
            NameValueCollection parameters = null;

            if (providerIndex == 1)
            {
                parameters = new NameValueCollection {
                    { "token", "X52StO16VHy9Jho2mac2G0RNNJD6qP" },
                    { "user", key },
                    { "title", title },
                    { "message", message }
                };

                api = new Uri("https://api.pushover.net/1/messages.json");
            }
            else if (providerIndex == 2 || providerIndex == 3)
            {
                parameters = new NameValueCollection {
                    { "apikey", key },
                    { "application", "Dungeon Teller" },
                    { "event", title },
                    { "description", message }
                };

                if (providerIndex == 2)
                    api = new Uri("https://www.notifymyandroid.com/publicapi/notify");
                if (providerIndex == 3)
                    api = new Uri("https://api.prowlapp.com/publicapi/add");
            }

            client.UploadValuesAsync(api, "POST", parameters);
        }
Ejemplo n.º 18
0
        public string Send(int timeoutSec = 10)
        {
            var wc = new WebClient();
            wc.UploadValuesCompleted += wc_UploadValuesCompleted;

            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("Origin", "http://elpis.adamhaile.net");

            if (PRequest.Proxy != null)
                wc.Proxy = PRequest.Proxy;

            wc.UploadValuesAsync(new Uri(_url), "POST", _params);

            DateTime start = DateTime.Now;
            while (!_uploadComplete && ((DateTime.Now - start).TotalMilliseconds < (timeoutSec * 1000)))
                Thread.Sleep(25);

            if (_uploadComplete)
                return _uploadResult;

            wc.CancelAsync();

            throw new Exception("Timeout waiting for POST to " + _url);
        }
Ejemplo n.º 19
0
        public void ExecuteAsync(Template template)
        {
            AsyncManager.OutstandingOperations.Increment();
            var client = new WebClient { Encoding = Encoding.UTF8 };
            client.UploadValuesCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    template.Response = Encoding.UTF8.GetString(e.Result);
                }
                else
                {
                    var exception = (WebException)e.Error;
                    var responseStream = exception.Response.GetResponseStream();
                    if (responseStream != null)
                        template.Response = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
                }
                AsyncManager.Parameters["template"] = template;

                AsyncManager.OutstandingOperations.Decrement();
            };

            // SandboxにTemplateをPOSTしてビルド&実行!
            // ※なのでTemplate内でIsPostを見ると常にtrue...
            var uri = new Uri(ConfigurationManager.AppSettings["SandboxUri"]);
            var values = new NameValueCollection();
            var extensions = new Dictionary<string, string>
                                 {
                                     {"cshtml", "csdoit"},
                                     {"vbhtml", "vbdoit"}
                                 };
            var pageName = "default." + extensions[template.Language ?? "cshtml"];
            values["Razor"] = template.Razor;
            values["PageName"] = pageName;
            client.UploadValuesAsync(uri, "POST", values);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Sends a message to a remote server asychronously.
        /// </summary>
        /// <param name="action">The action to perform.</param>
        /// <param name="request">The request to send to the server.</param>
        /// <param name="userState">Any user state data.</param>
        public virtual void SendMessageAsync(string action, ServerRequest request, object userState)
        {
            // Ensure that async is only called once (or once with the user state)
            lock (lockObject)
            {
                if (userState == null)
                {
                    if (isBusy) throw new InvalidOperationException();
                    isBusy = true;
                }
                else if (asyncOperations.ContainsKey(userState))
                {
                    if (asyncOperations.ContainsKey(userState)) throw new ArgumentException("Duplicate userState", "userState");
                }
            }

            // Initialise the web client
            WebClient client = new WebClient();
            client.UploadValuesCompleted += delegate(object sender, UploadValuesCompletedEventArgs e)
            {
                if (SendMessageCompleted != null)
                {
                    if ((e.Error != null) && !e.Cancelled)
                    {
                        // Convert the response into a response object
                        string response = Encoding.UTF8.GetString(e.Result);
                        Response result = XmlConversionUtil.ProcessResponse(response);

                        MessageReceivedEventArgs args = new MessageReceivedEventArgs(result, null, false, userState);
                        SendMessageCompleted(this, args);
                    }
                    else
                    {
                        MessageReceivedEventArgs args = new MessageReceivedEventArgs(null, e.Error, e.Cancelled, userState);
                        SendMessageCompleted(this, args);
                    }
                }
                CompleteAsyncCall(userState);
            };
            lock (lockObject)
            {
                asyncOperations.Add(userState ?? string.Empty, client);
            }

            try
            {
                // Generate the target URI
                Uri targetAddress = GenerateTargetUri(request);

                // Build the request and send it
                NameValueCollection formData = new NameValueCollection();
                formData.Add("action", action);
                formData.Add("message", request.ToString());
                client.UploadValuesAsync(targetAddress, "POST", formData);
            }
            catch (Exception error)
            {
                if (SendMessageCompleted != null)
                {
                    MessageReceivedEventArgs args = new MessageReceivedEventArgs(null, error, false, userState);
                    SendMessageCompleted(this, args);
                }
                CompleteAsyncCall(userState);
            }
        }
        public void InsertUserAuthAsync(string username, Action yield)
        {
            var _0600003f_user = UTF8ToBase64StringOrDefault(username);

            var c = new WebClient();
            c.UploadValuesCompleted +=
                (sender, args) =>
                {
                    var resultBytes = args.Result;
                    var data = Encoding.UTF8.GetString(resultBytes);
                    yield();
                };

            c.UploadValuesAsync(
                // generated, whenn will the uri change and break this?
                address: new Uri("http://" + methodURL + "/xml/InsertUserAuth"),
                    data: new System.Collections.Specialized.NameValueCollection { 
                        {"WebMethodMetadataToken","0600003f"},
                        {"WebMethodMetadataName","InsertUserAuth"},
                                { "_0600003f_user", _0600003f_user}
                            }
            );
        }
Ejemplo n.º 22
0
        private void SubmitBugReport(string email)
        {
            try {
                const string url = UpdateChecker.UpdateCheckHost + "tool/report_bug";
                WebClient wc = new WebClient();
                wc.Proxy = null;
                var data = new NameValueCollection();
                data.Set("renderer_version", typeof(Map).Assembly.GetName().Version.ToString());
                data.Set("input_map", File.ReadAllText(tbInput.Text));
                data.Set("input_name", Path.GetFileName(tbInput.Text));
                data.Set("commandline", GetCommandLine());
                data.Set("log_text", rtbLog.Text);
                data.Set("email", email);

                wc.OpenWriteCompleted += (o, args) => UpdateStatus("sending bug report.. connected", 15);
                wc.UploadProgressChanged += (o, args) => {
                    double pct = 15 + Math.Round(85.0 * (args.TotalBytesToSend / args.BytesSent) / 100.0, 0);
                    UpdateStatus("sending bug report.. uploading " + pct + "%", (int)pct);
                };
                wc.UploadValuesCompleted += (o, args) => {
                    if (args.Cancelled || args.Error != null)
                        BugReportFailed();
                    else
                        UpdateStatus("bug report sent", 100);
                };

                wc.UploadValuesAsync(new Uri(url), "POST", data);
                UpdateStatus("sending bug report.. ", 5);
            }
            catch {
                BugReportFailed();
            }
        }
Ejemplo n.º 23
0
        private void Btn_registreer_Click(object sender, EventArgs e)
        {
            /* Gebruiker klikte op registreer */

            WebClient client = new WebClient();
            Uri uri = new Uri("http://bringmans.be/Flyer_gebruiker.php");
            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("naam", txt_voornaam.Text);
            parameters.Add("email", txt_email.Text);
            parameters.Add("wachtwoord", txt_wachtwoord.Text);

            client.UploadValuesCompleted += client_UploadValuesCompleted;
            client.UploadValuesAsync(uri, parameters);
        }
Ejemplo n.º 24
0
 public override void OnActivate()
 {
     Main.clrInput();
     if (!loaded)
     {
         uITextPanel.SetText("Mod Browser", 0.8f, true);
         modListAll.Clear();
         try
         {
             ServicePointManager.Expect100Continue = false;
             string url = "http://javid.ddns.net/tModLoader/listmods.php";
             var values = new NameValueCollection
             {
                 { "modloaderversion", ModLoader.versionedName },
             };
             using (WebClient client = new WebClient())
             {
                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
                 client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(UploadComplete);
                 client.UploadValuesAsync(new Uri(url), "POST", values);
             }
         }
         catch (WebException e)
         {
             if (e.Status == WebExceptionStatus.Timeout)
             {
                 uITextPanel.SetText("Mod Browser OFFLINE (Busy)", 0.8f, true);
                 return;
             }
             if (e.Status == WebExceptionStatus.ProtocolError)
             {
                 var resp = (HttpWebResponse)e.Response;
                 if (resp.StatusCode == HttpStatusCode.NotFound)
                 {
                     uITextPanel.SetText("Mod Browser OFFLINE (404)", 0.8f, true);
                     return;
                 }
                 uITextPanel.SetText("Mod Browser OFFLINE..", 0.8f, true);
                 return;
             }
         }
         catch (Exception e)
         {
             ErrorLogger.LogModBrowserException(e);
             return;
         }
     }
 }
        public void RetreiveListOOfDomains(Action<string> yield)
        {
            // X:\jsc.svn\examples\java\Test\JVMCLRWebClient\JVMCLRWebClient\Program.cs

            //var _06000039_curr = UTF8ToBase64StringOrDefault(curr);

            var c = new WebClient();
            c.UploadValuesCompleted +=
                (sender, args) =>
                {
                    var resultBytes = args.Result;
                    var data = Encoding.UTF8.GetString(resultBytes);

                    //resultString = "<document><TaskComplete><TaskResult>11</TaskResult></TaskComplete></document>"

                    var xml = XElement.Parse(data);
                    Console.WriteLine(xml.Element("TaskComplete").Element("TaskResult").Value);
                    var TaskResult = UTF8FromBase64StringOrDefault(xml.Element("TaskComplete").Element("TaskResult").Value);
                    Console.WriteLine(TaskResult);
                    yield(TaskResult);
                };


            // X:\jsc.svn\examples\actionscript\Test\TestWebClient\TestWebClient\ApplicationSprite.cs

            c.UploadValuesAsync(
                // generated, whenn will the uri change and break this?
                address: new Uri(cloudflareUrl),
                    data: new System.Collections.Specialized.NameValueCollection { 
                        {"WebMethodMetadataToken","06000039"},
                        {"WebMethodMetadataName","GetCurrencyRateBasedOnString"},
                                { "_06000039_currency", _06000039_curr},
                            }
            );
        }   
Ejemplo n.º 26
0
 public void UploadValuesAndReturnStringAsync(string url, Action<string> action, Action<Exception> onConnectionFail, IWebProxy proxy = null)
 {
     WebClient webClient = new WebClient();
     if (proxy != null)
         webClient.Proxy = proxy;
     webClient.UploadValuesCompleted += (s, uploadEventArgs) =>
     {
         try
         {
             // todo: more error handeling when authenticating
             byte[] result = uploadEventArgs.Result;
             string resultAsStr = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
             action(resultAsStr);
         } 
         catch (WebException ex)
         {
             var serverUnavailableException = ToServerUnavailableException(url, ex);
             onConnectionFail(serverUnavailableException);
         } 
         catch (ServerUnavailableException ex)
         {
             onConnectionFail(ex);
         }
         catch (Exception ex)
         {
             WebException innerException = ex.InnerException as WebException;
             if (innerException != null)
             {
                 var serverUnavailableException = ToServerUnavailableException(url, innerException);
                 onConnectionFail(serverUnavailableException);
                 return;
             }
             _log.Error("Error in UploadValuesAndReturnXmlAsync", ex);
             throw;
         }
     };
     webClient.UploadValuesAsync(new Uri(url), "POST", _data);
 }
Ejemplo n.º 27
0
        protected override void Post(string url, Object data, Action<Object,Object> callback)
        {
            var webClient = new WebClient ();
            var formattedUrl = new Uri(url);

            webClient.UploadValuesCompleted += (object sender, UploadValuesCompletedEventArgs e) => {
                callback(e.Error, e.Result);
            };

            if (data is NameValueCollection) webClient.UploadValuesAsync (formattedUrl, data as NameValueCollection);
            else callback (null,null);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // X:\jsc.svn\examples\actionscript\Test\TestWebClient\TestWebClient\ApplicationSprite.cs
            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\WebGL\Uint8ClampedArray.cs

            new IHTMLButton { "invoke" }.AttachToDocument().WhenClicked(
                button =>
                {
                    var w = new WebClient();


                    w.UploadValuesCompleted +=
                        (sender, args) =>
                        {
                            if (args.Error != null)
                            {
                                //t.text = "UploadValuesCompleted error " + new { args.Error }.ToString();

                                return;
                            }

                            // DownloadStringAsync { Length = 2822 }

                            var data = Encoding.UTF8.GetString(args.Result);
                            // 

                            new IHTMLPre { 


                            
                                "UploadValuesCompleted " + new { args.Result.Length }.ToString() + "\n\n" + data

                            }.AttachToDocument();


                        };



                    //UploadValuesCompleted { Length = 77 }
                    //<document><TaskComplete><TaskResult>13</TaskResult></TaskComplete></document>
                    // crossdomain.xml	
                    //GET
                    //404
                    // UploadValuesCompleted error { Error = Error: securityError { errorID = 2048, text = Error #2048 } }
                    w.UploadValuesAsync(
                        address: new Uri("http://my.monese.com/xml?WebMethod=06000010&n=GetUserID"),
                            data: new System.Collections.Specialized.NameValueCollection { 
                                { "_06000010_username", ""},
                                { "_06000010_psw", ""}
                            }
                    );

                    //w.UploadValuesAsync(
                    //    new Uri("/xml?WebMethod=06000001&n=WebMethod2", UriKind.Relative),
                    //       data: new System.Collections.Specialized.NameValueCollection { 
                    //            { "_06000001_username", ""},
                    //            { "_06000001_psw", ""}
                    //        }
                    //);

                    //  w.UploadValuesAsync(
                    //    new Uri("/xml?WebMethod=06000002&n=WebMethod4", UriKind.Relative),
                    //       data: new System.Collections.Specialized.NameValueCollection { 
                    //                  { "_06000002_username", ""},
                    //                  { "_06000002_psw", ""}
                    //              }
                    //);
                }
            );

            @"Hello world".ToDocumentTitle();

            this.WebMethod2(
                  "",
                  ""
              ).ContinueWithResult(
              y =>
              {
                  new IHTMLPre { 


                            
                               new {y}

                            }.AttachToDocument();
              }
            );

            // Send data from JavaScript to the server tier
            this.WebMethod4(
                "",
                ""
            );
        }
Ejemplo n.º 29
0
 /// <summary>
 /// ポストを送信する(旧)
 /// (送りっぱなし)
 /// throwPostOld
 /// </summary>
 /// <param name="url"></param>
 /// <param name="postData"></param>
 public static void throwPostOld(string url, NameValueCollection postData)
 {
     using (WebClient wc = new System.Net.WebClient())
     {
         wc.UploadValuesAsync(new Uri(url), null, postData);
     }
 }
        public Task<UploaderEndedEventArgs> Upload(ExtendedScreenshot screenshot)
        {
            Trace.WriteLine("Starting upload process...", string.Format("MultipartFormDataUploadService.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

            var t = new TaskCompletionSource<UploaderEndedEventArgs>();

            try
            {
                using (var wc = new WebClient())
                {
                    wc.UploadProgressChanged += (s, e) =>
                    {
                        this.UploadProgress(this, new UploaderProgressEventArgs(screenshot, (e.BytesSent * 100) / e.TotalBytesToSend));
                    };

                    wc.UploadValuesCompleted += (s, e) =>
                    {
                        Trace.WriteLine("Upload complete.", string.Format("MultipartFormDataUploadService.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

                        XmlDocument ResponseDoc = new XmlDocument();
                        ResponseDoc.Load(new MemoryStream(e.Result));
                        ResponseDoc.Save(Configuration.LocalPath + @"\response.txt");

                        XmlNodeList ImageLink = ResponseDoc.SelectNodes(this.ImageLinkXPath);
                        screenshot.Remote.ImageLink = ImageLink.Count > 0 ? ImageLink[0].InnerText : null;

                        XmlNodeList DeleteLink = ResponseDoc.SelectNodes(this.DeleteLinkXPath);
                        screenshot.Remote.DeleteLink = DeleteLink.Count > 0 ? DeleteLink[0].InnerText : null;

                        var result = new UploaderEndedEventArgs(screenshot);
                        this.UploadEnded(this, result);
                        t.SetResult(result);
                    };

                    Trace.WriteLine("Starting stream conversion... ", string.Format("MultipartFormDataUploadService.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

                    var ImageData = string.Empty;
                    using (var ms = screenshot.EditedScreenshotPNGImageStream())
                        ImageData = Convert.ToBase64String(ms.ToArray());

                    var CurrentUploadValues = new NameValueCollection();
                    foreach (var k in this.UploadValues.AllKeys.ToList())
                        CurrentUploadValues.Add(k, this.UploadValues[k].Replace("%i", ImageData));

                    Trace.WriteLine("Stream conversion complete.", string.Format("MultipartFormDataUploadService.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));
                    Trace.WriteLine("Starting upload...", string.Format("MultipartFormDataUploadService.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

                    wc.UploadValuesAsync(new Uri(this.EndpointUrl), CurrentUploadValues);

                    this.UploadStarted(this, new UploaderProgressEventArgs(screenshot, 0));
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception occurred during upload: {0}", ex.GetBaseException()), string.Format("MultipartFormDataUploadService.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

                var result = new UploaderEndedEventArgs(ex.GetBaseException());
                this.UploadEnded(this, result);
                t.SetResult(result);
            }

            return t.Task;
        }
Ejemplo n.º 31
0
        private void PostToServer( Session oSession )
        {
            string oauth = OAuth;
            string url = oSession.fullUrl;
            string request = oSession.GetRequestBodyAsString();
            string response = oSession.GetResponseBodyAsString();

            request = RequestRegex.Replace( request, "" );

            try {

                //*
                using ( System.Net.WebClient wc = new System.Net.WebClient() ) {
                    wc.Headers["User-Agent"] = "ElectronicObserver/v" + SoftwareInformation.VersionEnglish;

                    if ( Proxy != null ) {
                        wc.Proxy = Proxy;
                    }

                    System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection();
                    post.Add( "token", oauth );
                    // agent key for 'ElectronicObserver'
                    // https://github.com/about518/kanColleDbPost/issues/3#issuecomment-105534030
                    post.Add( "agent", "L57Mi4hJeCYinbbBSH5K" );
                    post.Add( "url", url );
                    post.Add( "requestbody", request );
                    post.Add( "responsebody", response );

                    wc.UploadValuesCompleted += ( sender, e ) => {
                        if ( e.Error != null ) {

                            // 結構頻繁に出るのでレポートは残さない方針で 申し訳ないです
                            //Utility.ErrorReporter.SendErrorReport( e.Error, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) );

                            Utility.Logger.Add( 1, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。{1}", url.Substring( url.IndexOf( "/api" ) + 1 ), e.Error.Message ) );

                        } else {
                            Utility.Logger.Add( 1, string.Format( "艦これ統計データベースへ {0} を送信しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) );
                        }
                    };

                    wc.UploadValuesAsync( new Uri( "http://api.kancolle-db.net/2/" ), post );
                }
                //*/

            } catch ( Exception ex ) {

                Utility.ErrorReporter.SendErrorReport( ex, "艦これ統計データベースへの送信中にエラーが発生しました。" );
            }
        }
Ejemplo n.º 32
0
        void btnInsertDenuncia_Click(object sender, EventArgs e)
        {
			Toast.MakeText (this, "Creando denuncia...", ToastLength.Short).Show();
            cliente = new WebClient();
            NameValueCollection parametros = new NameValueCollection();
            parametros.Add("idusuario", "1");
            parametros.Add("idtipo", selectedId.ToString());
            parametros.Add("pais", Shared.address.CountryName);
            parametros.Add("ciudad", Shared.address.Locality);
            parametros.Add("calle", Shared.address.FeatureName);
            parametros.Add("lat", Shared.address.Latitude.ToString());
            parametros.Add("lng", Shared.address.Longitude.ToString());
            parametros.Add("descripcion", txtDescripcion.Text);
            if (bitmap != null)
            {
                MemoryStream memStream = new MemoryStream();
                bitmap.Compress(Bitmap.CompressFormat.Webp, 100, memStream);
                byte[] fotoData = memStream.ToArray();
                parametros.Add("imagebase64", Convert.ToBase64String(fotoData));
            }
            else
            {
                parametros.Add("imagebase64", null);
            }
            cliente.UploadValuesAsync(MainActivity.WebServices["setDenuncia"],parametros);
            cliente.UploadValuesCompleted += cliente_UploadValuesCompleted;
        }
Ejemplo n.º 33
0
        public static void Invoke(InternalWebMethodRequest that)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/20150301
            //Console.WriteLine("InternalWebMethodRequest.Invoke");


            var w = new System.Net.WebClient();

            w.UploadValuesCompleted +=
                (sender, args) =>
            {
                //if (args.Error != null)
                //{
                //    //t.text = "UploadValuesCompleted error " + new { args.Error }.ToString();

                //    return;
                //}

                // DownloadStringAsync { Length = 2822 }

                //var data = Encoding.UTF8.GetString(args.Result);

                // does this work in android webview?
                that.Complete(args.Result, w);
            };

            //var x = new IXMLHttpRequest();

            // we are using
            // "xml" as path
            // "WebMethod" as method selector
            // we could hide those details into post.
            // what about generic methods
            // X:\jsc.svn\examples\javascript\svg\SVGNavigationTiming\SVGNavigationTiming\Application.cs

            // http://xhr.spec.whatwg.org/
            // X:\jsc.svn\examples\javascript\Test\TestWebMethodIPAddress\TestWebMethodIPAddress\ApplicationWebService.cs

            // will this help us?
            // IE will thow InvalidStateError
            //x.withCredentials = true;

            ////x.open(HTTPMethodEnum.POST, Target);
            ////// http://stackoverflow.com/questions/12072315/uncaught-error-invalid-state-err-dom-exception-11

            ////x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            ////x.send(
            ////    globalscl::ScriptCoreLib.JavaScript.BCLImplementation.System.Net.__WebClient.ToFormDataString(
            ////        that.InternalUploadValues
            ////    )
            ////);

            ////x.InvokeOnComplete(that.Complete, 50);

            that.InternalUploadValues["WebMethodMetadataToken"] = that.MetadataToken;
            that.InternalUploadValues["WebMethodMetadataName"]  = that.Name;

            // do we have a previous etag available?
            if (MetadataTokenToETagLookup.ContainsKey(that.MetadataToken))
            {
                // send in the etag to get 304.
                that.InternalUploadValues["ETag"] = Convert.ToBase64String(MetadataTokenToETagLookup[that.MetadataToken]);
            }

            //var Target = "/xml?WebMethod=" + that.MetadataToken + "&n=" + that.Name;

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201401/20140110-xml
            // description?
            var Target = "/xml/" + that.Name;

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/20150301
            //Console.WriteLine("InternalWebMethodRequest.Invoke WebClient UploadValuesAsync");


            w.UploadValuesAsync(
                new Uri(Target, UriKind.Relative),
                that.InternalUploadValues
                );
        }
Ejemplo n.º 34
0
        private Uri UploadToBlitline(Guid g, XDocument doc, Boolean nearImage)
        {
            var blitlineJson = "";
            var location = new Uri(doc.Element("PostResponse").Element("Location").Value);
            if (location.ToString().EndsWith(".gif"))
            {
                blitlineJson = string.Format(@"{{
                ""application_id"":""{0}"",
                ""src"":""{1}"",
                ""pre_process"":{{
                    ""resize_gif_to_fit"":{{
                        ""params"":{{
                            ""width"":256,
                            ""height"":256
                        }},
                        ""s3_destination"":{{
                            ""bucket"": {{
                                ""name"": ""{2}"",
                                ""location"": ""us-west-1""
                            }},
                            ""key"":""{3}{4}.gif""
                        }}
                    }}
                }},
                ""functions"":[
                    {{
                        ""name"":""no_op"",
                        ""save"":{{
                            ""image_identifier"":""{3}{4}""
                        }}
                    }}
                ]
            }}", "BLITLINE KEY", location.ToString(), _isLoggedIn ? BUCKET_REGISTERED_GIF : BUCKET_ANONYMOUS_GIF, g.ToString(), nearImage ? "-n" : ""); /* CHANGEME - Blitline key */

            }
            else
            {
                blitlineJson = string.Format(@"{{
                ""application_id"":""{0}"",
                ""src"":""{1}"",
                ""functions"":[
                    {{
                        ""name"":""pad_resize_to_fit"",
                        ""params"":{{
                            ""width"":256,
                            ""height"":256,
                            ""color"":""transparent""
                        }},
                        ""save"":{{
                            ""image_identifier"":""{3}{4}"",
                            ""s3_destination"":{{
                                ""bucket"": {{
                                    ""name"": ""{2}"",
                                    ""location"": ""us-west-1""
                                }},
                                ""key"":""{3}{4}.png"",
                                ""extension"":"".png"",
                                ""png_quantize"":true
                            }}
                        }}
                    }}
                ]
            }}", "BLITLINE KEY", location.ToString(), _isLoggedIn ? BUCKET_REGISTERED_GIF : BUCKET_ANONYMOUS_GIF, g.ToString(), nearImage ? "-n" : ""); /* CHANGEME - Blitline key */

            }

            WebClient c = new WebClient();
            NameValueCollection values = new NameValueCollection();
            values.Add("json", blitlineJson);
            c.UploadValuesAsync(new Uri("http://api.blitline.com/job"), "POST", values);
            return location;
        }
Ejemplo n.º 35
0
            public Task<string> Fetch()
            {
                System.Console.WriteLine("post: " + Uri);
                var tcs = new TaskCompletionSource<string>();
                var webClient = new WebClient();
                webClient.UploadValuesCompleted += (s, e) =>
                {
                    try
                    {
                        tcs.SetResult(Encoding.GetEncoding("iso-8859-15").GetString(e.Result));
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }

                };
                webClient.Encoding = Encoding.UTF8;
                webClient.UploadValuesAsync(Uri, values);
                return tcs.Task;
            }
Ejemplo n.º 36
0
        public static void GetCurrencyRateBasedOnStringAsync(string curr, Action<string> yield)
        {
            //java.lang.Object, rt
            //{ addressString = http://my.monese.com/xml/GetCurrencyRateBasedOnString }
            //before writeBytes { Length = 106 }
            //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
            //before Read
            //yield UploadValuesAsync { Length = 83 }
            //{ Error =  }
            //{ data = <document><TaskComplete><TaskResult>MC44NA==</TaskResult></TaskComplete></document> }

            // X:\jsc.svn\examples\java\Test\JVMCLRWebClient\JVMCLRWebClient\Program.cs

            var _06000039_curr = UTF8ToBase64StringOrDefault(curr);

            //enter UploadValuesAsync
            //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
            //yield UploadValuesAsync

            //HtmlElement: Access denied | my.monese.com used CloudFlare to restrict access</title>
            var c = new WebClient();
            c.UploadValuesCompleted +=
                (sender, args) =>
                {

                    //Additional information: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details.

                    //[System.Net.WebException] = {"The underlying connection was closed: An unexpected error occurred on a receive."}
                    Console.WriteLine(new { args.Error });

                    var resultBytes = args.Result;
                    var data = Encoding.UTF8.GetString(resultBytes);

                    //data = "<document><TaskComplete><TaskResult>MC44NA==</TaskResult></TaskComplete></document>"
                    // /xml/GetCurrencyRateBasedOnString 200 84ms

                    Console.WriteLine(new { data });

                    ////var xml = XElement.Parse(data);
                    ////Console.WriteLine(xml.Element("TaskComplete").Element("TaskResult").Value);
                    ////var TaskResult = UTF8FromBase64StringOrDefault(xml.Element("TaskComplete").Element("TaskResult").Value);
                    ////Console.WriteLine(TaskResult);
                    ////yield(TaskResult);
                };


            // X:\jsc.svn\examples\actionscript\Test\TestWebClient\TestWebClient\ApplicationSprite.cs

            c.UploadValuesAsync(
                // generated, whenn will the uri change and break this?
                address: new Uri("http://my.monese.com/xml/GetCurrencyRateBasedOnString"),
                    data: new System.Collections.Specialized.NameValueCollection { 
                        {"WebMethodMetadataToken","06000039"},
                        {"WebMethodMetadataName","GetCurrencyRateBasedOnString"},
                                { "_06000039_currency", _06000039_curr},
                            }
            );
        }