Пример #1
0
 private void SendPOSTRequest(string url, string data)
 {
     using (WebClient wc = new WebClient())
     {
         wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         wc.UploadStringAsync(new Uri(url), "POST", data);
     }
 }
Пример #2
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;
    }
Пример #3
0
    public static void PostHighScore(string name, long score)
    {
        try
        {
            WebClient   webClient = new WebClient();

            webClient.Headers.Add("Content-Type", "application/json");

            webClient.UploadStringAsync(_updateUri, "{ name : '" + name + "', score : " + score + " }");

            webClient.Dispose();
        }
        catch(System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
    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);
    }
Пример #5
0
    //! Sends player name, location and color to the server.
    public void SendPlayerInfo()
    {
        Dictionary <string, string> values = new Dictionary <string, string>
        {
            { "name", PlayerPrefs.GetString("UserName") },
            { "x", playerController.gameObject.transform.position.x.ToString() },
            { "y", playerController.gameObject.transform.position.y.ToString() },
            { "z", playerController.gameObject.transform.position.z.ToString() },
            { "fx", Camera.main.transform.forward.x.ToString() },
            { "fz", Camera.main.transform.forward.z.ToString() },
            { "r", playerRed },
            { "g", playerGreen },
            { "b", playerBlue },
            { "ip", PlayerPrefs.GetString("ip") },
            { "password", PlayerPrefs.GetString("password") }
        };

        using (WebClient client = new WebClient())
        {
            Uri uri = null;
            try
            {
                uri = new Uri(networkController.serverURL + "/players");
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
                SceneManager.LoadScene(0);
            }
            client.UploadStringAsync(uri, "POST", "@" + values["name"] + ":"
                                     + values["x"] + "," + values["y"] + "," + values["z"]
                                     + "," + values["fx"] + "," + values["fz"] + ","
                                     + values["r"] + "," + values["g"] + "," + values["b"]
                                     + "," + values["ip"] + "," + values["password"]);
        }
    }
        public void LoadAds(int nDistinctAds)
        {
            Logger.Log(this, "LoadAd: Entered");
            this.nDistinctAds = nDistinctAds;

            AdRequest adRequest = new AdRequest(AdType.IMAGE_TEXTURE, this.adUnitId, this.nDistinctAds, AdConfigurer.GetAppParams());

            WebClient webClient = new WebClient();

            webClient.Headers.Add("Content-Type", "application/json");
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(OnAdResponseReceived);
            try
            {
                webClient.UploadStringAsync(new Uri(AdConfigurer.GetServerConfigedParams().imageTextureAdUnitUrl), "POST", JsonConvert.SerializeObject(adRequest));
            }
            catch (System.Net.WebException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
        }
Пример #7
0
        public static Task <string> UploadStringTaskAsync(this WebClient client, Uri uri, string data)
        {
            TaskCompletionSource <string>     taskCompletionSource = new TaskCompletionSource <string>();
            UploadStringCompletedEventHandler cancelled            = null;

            cancelled = (object sender, UploadStringCompletedEventArgs e) =>
            {
                client.UploadStringCompleted -= cancelled;
                if (e.Cancelled)
                {
                    taskCompletionSource.SetCanceled();
                    return;
                }
                if (e.Error != null)
                {
                    taskCompletionSource.SetException(e.Error);
                    return;
                }
                taskCompletionSource.SetResult(e.Result);
            };
            client.UploadStringCompleted += cancelled;
            client.UploadStringAsync(uri, data);
            return(taskCompletionSource.Task);
        }
Пример #8
0
        public override void ProcessCommand(OSAEMethod method)
        {
            this.Log.Info("Received Command: " + method.MethodName + " | to Cam: " + method.ObjectName);
            camName = method.ObjectName;
            // OSAEObject obj = OSAEObjectManager.GetObjectByName(camName);
            camIpAddress = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "IP Address").Value;
            camPort      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "Port").Value;
            camUser      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "Username").Value;
            camPass      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "Password").Value;
            camStream    = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "Stream Address").Value;
            camSnapShot  = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "camSnapShot").Value;
            ptzUP        = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzUP").Value;
            ptzDOWN      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzDOWN").Value;
            ptzLEFT      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzLEFT").Value;
            ptzRIGHT     = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzRIGHT").Value;
            ptzIN        = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzIN").Value;
            ptzOUT       = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzOUT").Value;
            ptzFOCUSIN   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzFOCUSIN").Value;
            ptzFOCUSOUT  = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzFOCUSOUT").Value;
            ptzPRESET1   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzPRESET1").Value;
            ptzPRESET2   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzPRESET2").Value;
            ptzPRESET3   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzPRESET3").Value;
            ptzPRESET4   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzPRESET4").Value;
            ptzPRESET5   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzPRESET5").Value;
            ptzPRESET6   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "ptzPRESET6").Value;
            CUSTOM1      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "CUSTOM1").Value;
            CUSTOM2      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "CUSTOM2").Value;
            CUSTOM3      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "CUSTOM3").Value;
            CUSTOM4      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "CUSTOM4").Value;
            CUSTOM5      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "CUSTOM5").Value;
            CUSTOM6      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "CUSTOM6").Value;
            camSloc      = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "Save Location").Value;
            camDegrees   = OSAEObjectPropertyManager.GetObjectPropertyValue(camName, "Degrees").Value;
            camSloc      = camSloc + @"\";
            if (method.Parameter1 != "")
            {
                camDegrees = method.Parameter1;
            }
            if (method.Parameter2 != "")
            {
                camOptional = method.Parameter2;
            }
            sMethod = method.MethodName;
            WebClient wc = new WebClient();

            wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
            if (sMethod == "UP")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzUP)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "DOWN")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzDOWN)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "LEFT")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzLEFT)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "RIGHT")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzRIGHT)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "IN")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzIN)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "OUT")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzOUT)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "FOCUSIN")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzFOCUSIN)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "FOCUSOUT")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzFOCUSOUT)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "PRESET1")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzPRESET1)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "PRESET2")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzPRESET2)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "PRESET3")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzPRESET3)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "PRESET4")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzPRESET4)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "PRESET5")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzPRESET5)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "PRESET6")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(ptzPRESET6)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "CUSTOM1")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(CUSTOM1)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "CUSTOM2")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(CUSTOM2)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "CUSTOM3")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(CUSTOM3)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "CUSTOM4")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(CUSTOM4)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "CUSTOM5")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(CUSTOM5)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "CUSTOM6")
            {
                try
                {
                    wc.UploadStringAsync(new Uri(replaceFielddata(CUSTOM6)), "POST", "");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "SNAPSHOT")
            {
                string i = DateTime.Now.ToLongTimeString();
                string j = DateTime.Now.ToShortDateString();
                i = i.Replace(":", "_");
                j = j.Replace("/", "_");
                i = j + "_" + i;
                i = i.Replace(" ", "");
                try
                {
                    var URI = new Uri(replaceFielddata(camSnapShot));
                    wc.DownloadFile(URI, camSloc + camName + "_" + i + ".jpg");
                    this.Log.Info(camSloc + camName + "_" + i + ".jpg was created");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            else if (sMethod == "SETUP")
            {
                try
                {
                    //System.Windows.Forms.MessageBox.Show("Test");
                }
                catch (Exception ex)
                {
                    this.Log.Info("An error occurred!!!: " + ex.Message);
                }
            }
            this.Log.Info("===================================================");
        }
Пример #9
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);


            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetActionBar(toolbar);
            ActionBar.Title = this.Title;

            EditText etUtente   = FindViewById <EditText>(Resource.Id.etUtente);
            EditText etPassword = FindViewById <EditText>(Resource.Id.etPassword);
            Button   btEntra    = FindViewById <Button>(Resource.Id.btEntra);

            btEntra.Click += (object sender, EventArgs e) =>
            {
                JSONObject jsobjIn = new JSONObject();
                jsobjIn.Put("username", etUtente.Text);
                jsobjIn.Put("password", etPassword.Text);

                ProgressDialog dialog = new ProgressDialog(this);
                dialog.SetMessage("Accesso in corso");
                dialog.SetCancelable(false);
                dialog.Show();

                string    data   = jsobjIn.ToString(); //"{\"username\":\"2644\",\"password\":63936}";
                WebClient client = new WebClient();
                client.Encoding = System.Text.Encoding.UTF8;

                client.UploadStringAsync(new Uri("http://2.115.37.22/umbriaeq/rest/b2brest.php?op=login"), data);
                client.UploadStringCompleted += (object sender2, UploadStringCompletedEventArgs e2) =>
                {
                    String reply = e2.Result;
                    //string reply = client.UploadString("http://2.115.37.22/umbriaeq/rest/b2brest.php?op=login", data);
                    JSONObject jsobj = new JSONObject(reply);
                    string     cod   = jsobj.GetString("codice");
                    string     descr = jsobj.GetString("descrizione");

                    if (cod == "0")
                    {
                        string id_sess = jsobj.GetString("user_id");

                        // Categorie
                        String       reply_cat    = client.DownloadString("http://2.115.37.22/umbriaeq/rest/b2brest.php?op=catall&session_id=" + id_sess);
                        String       filename     = Path.Combine(Application.CacheDir.AbsolutePath, "b2bAppCacheC0.txt");
                        StreamWriter streamWriter = new StreamWriter(filename, false);
                        String       cat_padre    = "0";

                        JSONObject jsobj2 = new JSONObject(reply_cat);
                        string     cod2   = jsobj2.GetString("codice");
                        if (cod2 == "0")
                        {
                            JSONArray catArray = jsobj2.GetJSONArray("categorie");

                            for (int i = 0; i < catArray.Length(); i++)
                            {
                                JSONObject item = (JSONObject)catArray.Get(i);
                                String     catp = item.GetString("cat_padre");
                                if (catp != cat_padre)
                                {
                                    streamWriter.Close();
                                    filename     = Path.Combine(Application.CacheDir.AbsolutePath, "b2bAppCacheC" + catp + ".txt");
                                    streamWriter = new StreamWriter(filename, false);
                                    cat_padre    = catp;
                                }
                                String idc   = item.GetString("category_id");
                                String categ = item.GetString("categoria");
                                streamWriter.WriteLine(idc + ";" + categ);
                            }
                            streamWriter.Close();
                        }

                        //Articoli
                        //String reply_art = client.DownloadString("http://2.115.37.22/umbriaeq/rest/b2brest.php?op=articoli/all&session_id=" + id_sess);
                        client.DownloadStringAsync(new Uri("http://2.115.37.22/umbriaeq/rest/b2brest.php?op=articoli/all&session_id=" + id_sess));
                        client.DownloadStringCompleted += (object sender3, DownloadStringCompletedEventArgs e3) =>
                        {
                            filename     = Path.Combine(Application.CacheDir.AbsolutePath, "b2bAppCacheA0.txt");
                            streamWriter = new StreamWriter(filename, false);
                            cat_padre    = "0";

                            String reply_art = e3.Result;
                            jsobj2 = new JSONObject(reply_art);
                            cod2   = jsobj2.GetString("codice");
                            if (cod2 == "0")
                            {
                                JSONArray catArray = jsobj2.GetJSONArray("articoli");

                                for (int i = 0; i < catArray.Length(); i++)
                                {
                                    JSONObject item = (JSONObject)catArray.Get(i);
                                    String     catp = item.GetString("category_id");
                                    if (catp != cat_padre)
                                    {
                                        streamWriter.Close();
                                        filename     = Path.Combine(Application.CacheDir.AbsolutePath, "b2bAppCacheA" + catp + ".txt");
                                        streamWriter = new StreamWriter(filename, false);
                                        cat_padre    = catp;
                                    }
                                    String idp  = item.GetString("product_id");
                                    String nome = item.GetString("nome");
                                    streamWriter.WriteLine(idp + ";" + nome);
                                }
                                streamWriter.Close();
                            }
                        };


                        Intent intent = new Intent(this, typeof(CatActivity));
                        intent.PutExtra("id_sess", id_sess);
                        intent.PutExtra("cat_padre", "0");
                        intent.PutExtra("path", "/");
                        StartActivity(intent);

                        dialog.Dismiss();
                    }
                };
            };
        }
 /// <summary>
 /// Sending tag to server
 /// </summary>
 /// <param name="tagList">Tags list</param>
 public void SendRequest(List <KeyValuePair <string, object> > tagList)
 {
     _webClient.UploadStringAsync(Constants.TagsUrl, BuildRequest(tagList));
 }
Пример #11
0
        private static void DownloadDataAsync(string method, string baseUrl, string data, string contentType,
                                              string authHeader, Action <FlickrResult <string> > callback)
        {
#if NETFX_CORE
            var client = new System.Net.Http.HttpClient();
            if (!String.IsNullOrEmpty(contentType))
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", contentType);
            }
            if (!String.IsNullOrEmpty(authHeader))
            {
                client.DefaultRequestHeaders.Add("Authorization", authHeader);
            }

            if (method == "POST")
            {
                var content       = client.PostAsync(baseUrl, new System.Net.Http.StringContent(data, System.Text.Encoding.UTF8, contentType)).Result.Content;
                var stringContent = content as System.Net.Http.StringContent;
                var result        = new FlickrResult <string> {
                    Result = content.ReadAsStringAsync().Result
                };
                callback(result);
            }
            else
            {
                var content = client.GetStringAsync(baseUrl).Result;
                var result  = new FlickrResult <string> {
                    Result = content
                };
                callback(result);
            }
#else
            var client = new WebClient();
            if (!String.IsNullOrEmpty(contentType))
            {
                client.Headers["Content-Type"] = contentType;
            }
            if (!String.IsNullOrEmpty(authHeader))
            {
                client.Headers["Authorization"] = authHeader;
            }

            if (method == "POST")
            {
                client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e)
                {
                    var result = new FlickrResult <string>();
                    if (e.Error != null)
                    {
                        result.Error = e.Error;
                        callback(result);
                        return;
                    }

                    result.Result = e.Result;
                    callback(result);
                    return;
                };

                client.UploadStringAsync(new Uri(baseUrl), data);
            }
            else
            {
                client.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
                {
                    var result = new FlickrResult <string>();
                    if (e.Error != null)
                    {
                        result.Error = e.Error;
                        callback(result);
                        return;
                    }

                    result.Result = e.Result;
                    callback(result);
                    return;
                };

                client.DownloadStringAsync(new Uri(baseUrl));
            }
#endif
        }
Пример #12
0
        public static void UploadString_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();
            
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null, null); });
        }
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            ui_handBusy.IsBusy = true;

            string json = "[";

            BaseObjectList list = daninfos.ItemsSource as BaseObjectList;

            List <GeneralObject> removed = new List <GeneralObject>();

            //对于每一条记录
            foreach (GeneralObject go in list)
            {
                // 抄表记录里的上期指数
                var lastinputnum = go.GetPropertyValue("lastinputgasnum");

                // 本次抄表指数
                var lastrecord = go.GetPropertyValue("lastrecord");

                // 抄表记录里的阶梯类型
                var stairType = go.GetPropertyValue("f_stairtype");

                // 抄表记录里的id
                var id = go.GetPropertyValue("id");
                // 抄表记录里的用水量
                var pregas = go.GetPropertyValue("oughtamount");
                // 本次指数为空,这条不上传
                if (lastrecord == null)
                {
                    continue;
                }

                // 本期指数小于上期指数,不上传
                if (double.Parse(lastrecord.ToString()) < double.Parse(lastinputnum.ToString()))
                {
                    continue;
                }

                // 从列表中去除
                removed.Add(go);

                //已经有项目,加逗号区分
                if (json != "[")
                {
                    json += ',';
                }
                //产生要发送后台的JSON串
                json += ("{userid:" + go.GetPropertyValue("f_userid") + ",reading:" + lastrecord + ",lastreading:" + lastinputnum + ",stairType:" + stairType + ",pregas:" + pregas + "}");
            }

            json += "]";

            foreach (GeneralObject go in removed)
            {
                list.Remove(go);
            }
            //将产生的json串送后台服务进行处理
            WebClientInfo wci    = Application.Current.Resources["server"] as WebClientInfo;
            string        uri    = wci.BaseAddress + "/handcharge/record/batch/" + ui_handdate.SelectedDate + "/" + ui_sgnetwork.Text + "/" + ui_sgoperator.Text + "/" + chaobiaoriqi.SelectedDate + "?uuid=" + System.Guid.NewGuid().ToString();
            WebClient     client = new WebClient();

            client.UploadStringCompleted += client_UploadStringCompleted;
            client.UploadStringAsync(new Uri(uri), json);
        }
        private void getInfo2(string id)
        {
            {
                //NavigationService.Navigate(new Uri("/LoggedMainPages/Scan.xaml", UriKind.Relative));
                if (IsNetworkAvailable())
                {
                    try
                    {
                        var webClient = new WebClient();
                        webClient.Headers[HttpRequestHeader.ContentType] = "text/json";
                        webClient.UploadStringCompleted += this.sendPostCompleted;
                        LoggedUser user      = LoggedUser.Instance;
                        UserData   _userData = user.GetLoggedUser();
                        string     json      = "{\"IdFrom\":\"" + _userData.Id + "\"," +
                                               "\"IdTo\":\"" + id + "\"}";

                        webClient.UploadStringAsync((new Uri(App.webService + "/api/Friends/AddFriendFromIds")), "POST", json);
                    }
                    catch (WebException webex)
                    {
                        HttpWebResponse webResp = (HttpWebResponse)webex.Response;

                        switch (webResp.StatusCode)
                        {
                        case HttpStatusCode.NotFound:     // 404
                            break;

                        case HttpStatusCode.InternalServerError:     // 500
                            break;

                        default:
                            break;
                        }
                    }
                }
                else
                {
                    SolidColorBrush  mybrush    = new SolidColorBrush(Color.FromArgb(255, 0, 175, 240));
                    CustomMessageBox messageBox = new CustomMessageBox()
                    {
                        Caption           = AppResources.NoInternetConnection,
                        Message           = AppResources.NoInternetConnectionMessage,
                        LeftButtonContent = AppResources.OkTitle,
                        Background        = mybrush,
                        IsFullScreen      = false,
                    };


                    messageBox.Dismissed += (s1, e1) =>
                    {
                        switch (e1.Result)
                        {
                        case CustomMessageBoxResult.LeftButton:
                            apagarCam();
                            NavigationService.Navigate(new Uri("/LoggedMainPages/LoggedMainPage.xaml", UriKind.Relative));
                            break;

                        case CustomMessageBoxResult.None:
                            // Acción.
                            break;

                        default:
                            break;
                        }
                    };

                    messageBox.Show();
                }
            }
        }
Пример #15
0
        private void ProcessRequest(MegaRequest req)
        {
            if (req.retries > 1)
            {
                Thread.Sleep((int)(Math.Pow(2, req.retries) * 100));
                // 0,400,800,1600,3200ms etc
            }
            var wc = new WebClient();

            wc.Proxy = Proxy;
            wc.UploadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    try
                    {
                        var response = String.Format("{{root:{0}}}", e.Result);
                        var r        = JObject.Parse(response)["root"];

                        #region error handling
                        if (r.Type == JTokenType.Integer && r.ToObject <int>() < 0)
                        {
                            ProcessError(req, r.ToObject <int>());
                            return;
                        }
                        if (r.Type == JTokenType.Array)
                        {
                            if (r[0].Type == JTokenType.Integer && r[0].ToObject <int>() < 0)
                            {
                                ProcessError(req, r[0].ToObject <int>());
                                return;
                            }
                        }
                        else
                        {
                            req.HandleError(MegaApiError.EUNEXPECTED);
                            ProcessNext();
                            return;
                        }
                        #endregion

                        req.HandleSuccess(r[0]);
                        ProcessNext();
                    }
                    catch (JsonException)
                    {
                        req.HandleError(MegaApiError.EUNEXPECTED);
                        ProcessNext();
                    }
                }
                else
                {
                    ProcessAgain(req);
                }
            };
            try
            {
                if (req.IsTracking)
                {
                    tracking.Add(((ITrackingRequest)req).TrackingId);
                }

                wc.UploadStringAsync(BuildCsUri(req), GetData(req));
            }
            catch (WebException) { ProcessAgain(req, false); }
        }
Пример #16
0
        static void versionCheckWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DeletePreviouslyDownloadedFiles();

            // We need to check to see if a new version is available. We do this in the background.
            // If a new version is available, the version number is returned as the result of the background
            // processing. If no new version is available, null is returned.
            WebClient    client  = new WebClient();
            CheckResults results = new CheckResults();

            // Download latest version.
            string latestVersion    = null;
            string latestPrerelease = null;

            try {
                latestVersion = client.DownloadString(downloadLocation + latestVersionName);
            }
            catch (WebException) {
                latestVersion = null;
            }

            // Only check latest prerelease if this is a pre-release.
            if (Util.IsPrerelease(VersionNumber.Current))
            {
                try {
                    latestPrerelease = client.DownloadString(downloadLocation + latestPreleaseName);
                }
                catch (WebException) {
                    latestPrerelease = null;
                }
            }

            if (latestVersion != null)
            {
                // Get first line and second line.
                string[] lines    = latestVersion.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                string   version  = lines.Length > 0 ? lines[0] : null;
                string   filename = lines.Length > 1 ? lines[1] : null;

                if (!string.IsNullOrEmpty(version) && !string.IsNullOrEmpty(filename))
                {
                    results.CurrentVersion  = version;
                    results.CurrentFileName = filename;
                }
            }

            if (latestPrerelease != null)
            {
                // Get first line and second line.
                string[] lines    = latestPrerelease.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                string   version  = lines.Length > 0 ? lines[0] : null;
                string   filename = lines.Length > 1 ? lines[1] : null;

                if (!string.IsNullOrEmpty(version) && !string.IsNullOrEmpty(filename))
                {
                    results.PrereleaseVersion  = version;
                    results.PrereleaseFileName = filename;
                }
            }

            // Collect anonymous statistics, so we can know number of time the program is invoked, and from where, which version and language people are using.
            string uiLanguage = Settings.Default.UILanguage;

            if (string.IsNullOrEmpty(uiLanguage))
            {
                uiLanguage = CultureInfo.CurrentUICulture.Name;
            }

            string status = string.Format("{{\"Version\":\"{0}\", \"Locale\":\"{1}\", \"TimeZone\":\"{2}\", \"UILang\":\"{3}\", \"ClientId\":\"{4}\", \"OSVersion\":\"{5}\"}}",
                                          JsonEncode(VersionNumber.Current),
                                          JsonEncode(CultureInfo.CurrentCulture.Name),
                                          JsonEncode(TimeZone.CurrentTimeZone.StandardName),
                                          JsonEncode(uiLanguage),
                                          JsonEncode(Settings.Default.ClientId.ToString()),
                                          JsonEncode(CrashReporterDotNET.HelperMethods.GetWindowsVersion()));

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

            try {
                client.UploadStringAsync(new Uri("http://monitor.purple-pen.org/api/Invocation"), status);
            }
            catch (WebException ex) {
                // Ignore problems.
                Debug.WriteLine(ex.ToString());
            }

            e.Result = results;
        }
Пример #17
0
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            ui_handBusy.IsBusy = true;

            string json = "[";

            BaseObjectList list = daninfos.ItemsSource as BaseObjectList;

            List <GeneralObject> removed = new List <GeneralObject>();

            //对于每一条记录
            foreach (GeneralObject go in list)
            {
                //表状态
                var meterstate = meter.SelectedValue;

                // 抄表记录里的上期指数
                var lastinputnum = go.GetPropertyValue("lastinputgasnum");

                // 本次抄表指数
                var lastrecord = go.GetPropertyValue("lastrecord");

                // 本次指数为空,这条不上传
                if (lastrecord == null)
                {
                    continue;
                }

                // 本期指数小于上期指数,不上传
                if (double.Parse(lastrecord.ToString()) < double.Parse(lastinputnum.ToString()))
                {
                    continue;
                }

                // 从列表中去除
                removed.Add(go);

                //已经有项目,加逗号区分
                if (json != "[")
                {
                    json += ',';
                }
                //产生要发送后台的JSON串
                json += ("{userid:'" + go.GetPropertyValue("f_userid") + "',lastreading:" + lastinputnum + ",reading:" + lastrecord + ",meterstate:" + meterstate + "}");
            }

            json += "]";

            foreach (GeneralObject go in removed)
            {
                list.Remove(go);
            }
            //获取登录用户组织信息

            GeneralObject loginUser   = (GeneralObject)FrameworkElementExtension.FindResource(this, "LoginUser");
            string        orgpathstr  = (string)loginUser.GetPropertyValue("orgpathstr");
            string        loginuserid = (string)loginUser.GetPropertyValue("id");
            //将产生的json串送后台服务进行处理
            WebClientInfo wci    = Application.Current.Resources["server"] as WebClientInfo;
            string        uri    = wci.BaseAddress + "/handcharge/record/batch/" + ui_handdate.SelectedDate + "/" + ui_sgnetwork.Text + "/" + loginuserid + "/" + chaobiaoriqi.SelectedDate + "/" + meter.SelectedValue.ToString() + "/" + orgpathstr + "?uuid=" + System.Guid.NewGuid().ToString();
            WebClient     client = new WebClient();

            client.UploadStringCompleted += client_UploadStringCompleted;
            client.UploadStringAsync(new Uri(uri), json);
        }
        private void btnSave_Click(System.Object sender, System.Windows.RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtUsername.Text))
            {
                MessageBox.Show("Please input (Username)");
                return;
            }
            if (string.IsNullOrEmpty(this.txtPassword.Password.ToString()))
            {
                MessageBox.Show("Please input (Password)");
                return;
            }
            if (string.IsNullOrEmpty(this.txtConPassword.Password.ToString()))
            {
                MessageBox.Show("Please input (Confirm Username)");
                return;
            }
            if (this.txtPassword.Password.ToString() != this.txtConPassword.Password.ToString())
            {
                MessageBox.Show("Password Not Match!");
                return;
            }
            if (string.IsNullOrEmpty(this.txtName.Text))
            {
                MessageBox.Show("Please input (Name)");
                return;
            }
            if (string.IsNullOrEmpty(this.txtTel.Text))
            {
                MessageBox.Show("Please input (Tel)");
                return;
            }
            if (string.IsNullOrEmpty(this.txtEmail.Text))
            {
                MessageBox.Show("Please input (Email)");
                return;
            }
            string url = "http://roboviper.besaba.com/imaginecup/json/saveData.php";
            Uri    uri = new Uri(url, UriKind.Absolute);

            StringBuilder postData = new StringBuilder();

            postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(this.txtUsername.Text));
            postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString()));
            postData.AppendFormat("&{0}={1}", "sName", HttpUtility.UrlEncode(this.txtName.Text));
            postData.AppendFormat("&{0}={1}", "sTel", HttpUtility.UrlEncode(this.txtTel.Text));
            postData.AppendFormat("&{0}={1}", "sEmail", HttpUtility.UrlEncode(this.txtEmail.Text));

            WebClient client = default(WebClient);

            client = new WebClient();
            client.Headers[HttpRequestHeader.ContentType]   = "application/x-www-form-urlencoded";
            client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();

            client.UploadStringCompleted += client_UploadStringCompleted;
            client.UploadProgressChanged += client_UploadProgressChanged;

            client.UploadStringAsync(uri, "POST", postData.ToString());

            prog = new ProgressIndicator();
            prog.IsIndeterminate = true;
            prog.IsVisible       = true;
            prog.Text            = "Loading....";
            SystemTray.SetProgressIndicator(this, prog);
        }
Пример #19
0
        private void sendButton_Click(object sender, EventArgs e)
        {
            if (pluginBox.SelectedIndex == -1)
            {
                MessageBox.Show("Please select the problematic plugin.\n(Or \"Not Applicable\" if it doesn't concern a plugin.)");
                return;
            }

            if (problemText.Text.Length == 0)
            {
                MessageBox.Show("Please write what the problem is.");
                return;
            }

            String version;

            try {
                version = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            } catch (System.Deployment.Application.InvalidDeploymentException) {
                version = "";
            }

            String report = String.Format(@"SkypeBot bug report
-----------------------------
Filed by: {0}
Version: {1}
Plugin: {2}
-----------------------------
Problem description:

{3}
-----------------------------",
                                          nameBox.Text,
                                          version,
                                          pluginBox.SelectedItem,
                                          problemText.Text);

            if (attachLog.Checked)
            {
                report += "\nLog contents:\n\n";
                String[] logFiles = { "debug.log", "debug.log.1" };

                foreach (String fileName in logFiles)
                {
                    String logFile = Path.Combine(Directory.GetCurrentDirectory(), fileName);

                    if (!File.Exists(logFile))
                    {
                        continue;
                    }

                    // The logfile may be locked by the logger, so let us open it read-only, just in case.
                    FileStream   fs     = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader reader = new StreamReader(fs);
                    report += String.Format("{0}:\n", fileName);
                    report += reader.ReadToEnd();
                    report += "\n\n";

                    reader.Close();
                    fs.Close();
                }
            }

            WebClient wc = new WebClient();

            wc.UploadStringCompleted += (snd, ev) => MessageBox.Show("Your report has been sent. Thank you.");
            wc.UploadStringAsync(new Uri("http://mathemaniac.org/apps/skypebot/errorlogger.php"), "POST", report);
            Close();
        }
Пример #20
0
        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            UploadFile();
            if (string.IsNullOrEmpty(this.username.Text))
            {
                MessageBox.Show("Please input (Username)");
                return;
            }
            if (string.IsNullOrEmpty(this.txtPassword.Password.ToString()))
            {
                MessageBox.Show("Please input (Password)");
                return;
            }
            if (string.IsNullOrEmpty(this.txtConPassword.Password.ToString()))
            {
                MessageBox.Show("Please input (Confirm Username)");
                return;
            }
            if (this.txtPassword.Password.ToString() != this.txtConPassword.Password.ToString())
            {
                MessageBox.Show("Password Not Match!");
                return;
            }

            if (string.IsNullOrEmpty(this.email.Text))
            {
                MessageBox.Show("Please input (Email)");
                return;
            }

            /*store application info**/
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            // txtInput is a TextBox defined in XAML.
            if (!settings.Contains("Image"))
            {
                settings.Add("Image", imgTxtBx.Text);
            }
            else
            {
                settings["Image"] = imgTxtBx.Text;
            }
            settings.Save();
            /***/
            // string url = "http://localhost/vaginosis/online/mregistration";
            string        url      = "http://www.novariss.com/vaginosis/index.php/Online/mregistration";
            Uri           uri      = new Uri(url, UriKind.Absolute);
            StringBuilder postData = new StringBuilder();

            postData.AppendFormat("{0}={1}", "username", HttpUtility.UrlEncode(this.username.Text));
            postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(this.txtPassword.Password.ToString()));

            postData.AppendFormat("&{0}={1}", "email", HttpUtility.UrlEncode(this.email.Text));

            WebClient client = default(WebClient);

            client = new WebClient();
            client.Headers[HttpRequestHeader.ContentType]   = "application/x-www-form-urlencoded";
            client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();

            client.UploadStringCompleted += client_UploadStringCompleted;
            client.UploadProgressChanged += client_UploadProgressChanged;

            client.UploadStringAsync(uri, "POST", postData.ToString());

            prog = new ProgressIndicator();
            prog.IsIndeterminate = true;
            prog.IsVisible       = true;
            prog.Text            = "Loading....";
            SystemTray.SetProgressIndicator(this, prog);
        }
Пример #21
0
        private void listen()
        {
            Timer t = new Timer();

            t.Interval = 1000;
            t.Start();

            while (true)
            {
                if (t.Interval == 1000)
                {
                    string tempString = string.Empty;
                    tempString = System.Windows.Forms.Clipboard.GetText();
                    var element = AutomationElement.FocusedElement;
                    if ((!string.IsNullOrWhiteSpace(tempString)))
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine(tempString);
                        string selectedText = string.Empty;
                        if (sb.ToString() != "\r\n")
                        {
                            popUpX = GetCursorPosition().X;
                            popUpY = GetCursorPosition().Y;
                            translateWord.originalWord = sb.ToString();
                            try
                            {
                                string content = translateWord.originalWord;
                                translateIsDone = false;

                                // Set the From and To language
                                //string fromLanguage = "English";
                                //string toLanguage = "Turkish";

                                // Create a Language mapping
                                var languageMap = new Dictionary <string, string>();
                                InitLanguageMap(languageMap);

                                // Create an instance of WebClient in order to make the language translation
                                //Uri address = new Uri("http://translate.google.com/");
                                Uri       address = new Uri("https://translate.google.com/");
                                WebClient wc      = new WebClient();
                                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                                wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

                                // Async Upload to the specified source
                                // i.e http://translate.google.com/translate_t for handling the translation.
                                wc.UploadStringAsync(address,
                                                     GetPostData(languageMap[fromLanguage], languageMap[toLanguage], content));

                                while (wc.IsBusy || !translateIsDone)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                }
                                if (!string.IsNullOrWhiteSpace(translateWord.translatedWord))
                                {
                                    if (oldSelectedText != translateWord.originalWord)
                                    {
                                        oldSelectedText = translateWord.originalWord;
                                        int uzunluk = oldSelectedText.Length;
                                        Yaz(oldSelectedText.Remove(uzunluk - 2, 2) + " :   " + translateWord.translatedWord + "\n");
                                        PopUp frm = new PopUp(translateWord.translatedWord, 500, 500);
                                        frm.Location = new Point(popUpX, popUpY);
                                        frm.ShowDialog();
                                        translateWord.originalWord   = string.Empty;
                                        translateWord.translatedWord = string.Empty;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Bir hata oluştu." + ex.Message);
                            }
                        }
                        element = null;
                    }
                }
            }
        }
Пример #22
0
        public static async Task SendWebClientRequests(bool tracingDisabled, string url, string requestContent)
        {
            Console.WriteLine($"[WebClient] sending requests to {url}");

            using (var webClient = new WebClient())
            {
                webClient.Encoding = Utf8;

                if (tracingDisabled)
                {
                    webClient.Headers.Add(HttpHeaderNames.TracingEnabled, "false");
                }

                using (Tracer.Instance.StartActive("WebClient"))
                {
                    using (Tracer.Instance.StartActive("DownloadData"))
                    {
                        webClient.DownloadData(url);
                        Console.WriteLine("Received response for client.DownloadData(String)");

                        webClient.DownloadData(new Uri(url));
                        Console.WriteLine("Received response for client.DownloadData(Uri)");
                    }

                    using (Tracer.Instance.StartActive("DownloadDataAsync"))
                    {
                        webClient.DownloadDataAsync(new Uri(url));
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.DownloadDataAsync(Uri)");

                        webClient.DownloadDataAsync(new Uri(url), null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.DownloadDataAsync(Uri, Object)");
                    }

                    using (Tracer.Instance.StartActive("DownloadDataTaskAsync"))
                    {
                        await webClient.DownloadDataTaskAsync(url);

                        Console.WriteLine("Received response for client.DownloadDataTaskAsync(String)");

                        await webClient.DownloadDataTaskAsync(new Uri(url));

                        Console.WriteLine("Received response for client.DownloadDataTaskAsync(Uri)");
                    }

                    using (Tracer.Instance.StartActive("DownloadFile"))
                    {
                        webClient.DownloadFile(url, "DownloadFile.string.txt");
                        Console.WriteLine("Received response for client.DownloadFile(String, String)");

                        webClient.DownloadFile(new Uri(url), "DownloadFile.uri.txt");
                        Console.WriteLine("Received response for client.DownloadFile(Uri, String)");
                    }

                    using (Tracer.Instance.StartActive("DownloadFileAsync"))
                    {
                        webClient.DownloadFileAsync(new Uri(url), "DownloadFileAsync.uri.txt");
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.DownloadFileAsync(Uri, String)");

                        webClient.DownloadFileAsync(new Uri(url), "DownloadFileAsync.uri_token.txt", null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.DownloadFileAsync(Uri, String, Object)");
                    }

                    using (Tracer.Instance.StartActive("DownloadFileTaskAsync"))
                    {
                        await webClient.DownloadFileTaskAsync(url, "DownloadFileTaskAsync.string.txt");

                        Console.WriteLine("Received response for client.DownloadFileTaskAsync(String, String)");

                        await webClient.DownloadFileTaskAsync(new Uri(url), "DownloadFileTaskAsync.uri.txt");

                        Console.WriteLine("Received response for client.DownloadFileTaskAsync(Uri, String)");
                    }

                    using (Tracer.Instance.StartActive("DownloadString"))
                    {
                        webClient.DownloadString(url);
                        Console.WriteLine("Received response for client.DownloadString(String)");

                        webClient.DownloadString(new Uri(url));
                        Console.WriteLine("Received response for client.DownloadString(Uri)");
                    }

                    using (Tracer.Instance.StartActive("DownloadStringAsync"))
                    {
                        webClient.DownloadStringAsync(new Uri(url));
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.DownloadStringAsync(Uri)");

                        webClient.DownloadStringAsync(new Uri(url), null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.DownloadStringAsync(Uri, Object)");
                    }

                    using (Tracer.Instance.StartActive("DownloadStringTaskAsync"))
                    {
                        await webClient.DownloadStringTaskAsync(url);

                        Console.WriteLine("Received response for client.DownloadStringTaskAsync(String)");

                        await webClient.DownloadStringTaskAsync(new Uri(url));

                        Console.WriteLine("Received response for client.DownloadStringTaskAsync(Uri)");
                    }

                    using (Tracer.Instance.StartActive("OpenRead"))
                    {
                        webClient.OpenRead(url).Close();
                        Console.WriteLine("Received response for client.OpenRead(String)");

                        webClient.OpenRead(new Uri(url)).Close();
                        Console.WriteLine("Received response for client.OpenRead(Uri)");
                    }

                    using (Tracer.Instance.StartActive("OpenReadAsync"))
                    {
                        webClient.OpenReadAsync(new Uri(url));
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.OpenReadAsync(Uri)");

                        webClient.OpenReadAsync(new Uri(url), null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.OpenReadAsync(Uri, Object)");
                    }

                    using (Tracer.Instance.StartActive("OpenReadTaskAsync"))
                    {
                        using Stream readStream1 = await webClient.OpenReadTaskAsync(url);

                        Console.WriteLine("Received response for client.OpenReadTaskAsync(String)");

                        using Stream readStream2 = await webClient.OpenReadTaskAsync(new Uri (url));

                        Console.WriteLine("Received response for client.OpenReadTaskAsync(Uri)");
                    }

                    using (Tracer.Instance.StartActive("UploadData"))
                    {
                        webClient.UploadData(url, new byte[0]);
                        Console.WriteLine("Received response for client.UploadData(String, Byte[])");

                        webClient.UploadData(new Uri(url), new byte[0]);
                        Console.WriteLine("Received response for client.UploadData(Uri, Byte[])");

                        webClient.UploadData(url, "POST", new byte[0]);
                        Console.WriteLine("Received response for client.UploadData(String, String, Byte[])");

                        webClient.UploadData(new Uri(url), "POST", new byte[0]);
                        Console.WriteLine("Received response for client.UploadData(Uri, String, Byte[])");
                    }

                    using (Tracer.Instance.StartActive("UploadDataAsync"))
                    {
                        webClient.UploadDataAsync(new Uri(url), new byte[0]);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadDataAsync(Uri, Byte[])");

                        webClient.UploadDataAsync(new Uri(url), "POST", new byte[0]);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadDataAsync(Uri, String, Byte[])");

                        webClient.UploadDataAsync(new Uri(url), "POST", new byte[0], null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadDataAsync(Uri, String, Byte[], Object)");
                    }

                    using (Tracer.Instance.StartActive("UploadDataTaskAsync"))
                    {
                        await webClient.UploadDataTaskAsync(url, new byte[0]);

                        Console.WriteLine("Received response for client.UploadDataTaskAsync(String, Byte[])");

                        await webClient.UploadDataTaskAsync(new Uri(url), new byte[0]);

                        Console.WriteLine("Received response for client.UploadDataTaskAsync(Uri, Byte[])");

                        await webClient.UploadDataTaskAsync(url, "POST", new byte[0]);

                        Console.WriteLine("Received response for client.UploadDataTaskAsync(String, String, Byte[])");

                        await webClient.UploadDataTaskAsync(new Uri(url), "POST", new byte[0]);

                        Console.WriteLine("Received response for client.UploadDataTaskAsync(Uri, String, Byte[])");
                    }

                    File.WriteAllText("UploadFile.txt", requestContent);

                    using (Tracer.Instance.StartActive("UploadFile"))
                    {
                        webClient.UploadFile(url, "UploadFile.txt");
                        Console.WriteLine("Received response for client.UploadFile(String, String)");

                        webClient.UploadFile(new Uri(url), "UploadFile.txt");
                        Console.WriteLine("Received response for client.UploadFile(Uri, String)");

                        webClient.UploadFile(url, "POST", "UploadFile.txt");
                        Console.WriteLine("Received response for client.UploadFile(String, String, String)");

                        webClient.UploadFile(new Uri(url), "POST", "UploadFile.txt");
                        Console.WriteLine("Received response for client.UploadFile(Uri, String, String)");
                    }

                    using (Tracer.Instance.StartActive("UploadFileAsync"))
                    {
                        webClient.UploadFileAsync(new Uri(url), "UploadFile.txt");
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadFileAsync(Uri, String)");

                        webClient.UploadFileAsync(new Uri(url), "POST", "UploadFile.txt");
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadFileAsync(Uri, String, String)");

                        webClient.UploadFileAsync(new Uri(url), "POST", "UploadFile.txt", null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadFileAsync(Uri, String, String, Object)");
                    }

                    using (Tracer.Instance.StartActive("UploadFileTaskAsync"))
                    {
                        await webClient.UploadFileTaskAsync(url, "UploadFile.txt");

                        Console.WriteLine("Received response for client.UploadFileTaskAsync(String, String)");

                        await webClient.UploadFileTaskAsync(new Uri(url), "UploadFile.txt");

                        Console.WriteLine("Received response for client.UploadFileTaskAsync(Uri, String)");

                        await webClient.UploadFileTaskAsync(url, "POST", "UploadFile.txt");

                        Console.WriteLine("Received response for client.UploadFileTaskAsync(String, String, String)");

                        await webClient.UploadFileTaskAsync(new Uri(url), "POST", "UploadFile.txt");

                        Console.WriteLine("Received response for client.UploadFileTaskAsync(Uri, String, String)");
                    }

                    using (Tracer.Instance.StartActive("UploadString"))
                    {
                        webClient.UploadString(url, requestContent);
                        Console.WriteLine("Received response for client.UploadString(String, String)");

                        webClient.UploadString(new Uri(url), requestContent);
                        Console.WriteLine("Received response for client.UploadString(Uri, String)");

                        webClient.UploadString(url, "POST", requestContent);
                        Console.WriteLine("Received response for client.UploadString(String, String, String)");

                        webClient.UploadString(new Uri(url), "POST", requestContent);
                        Console.WriteLine("Received response for client.UploadString(Uri, String, String)");
                    }

                    using (Tracer.Instance.StartActive("UploadStringAsync"))
                    {
                        webClient.UploadStringAsync(new Uri(url), requestContent);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadStringAsync(Uri, String)");

                        webClient.UploadStringAsync(new Uri(url), "POST", requestContent);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadStringAsync(Uri, String, String)");

                        webClient.UploadStringAsync(new Uri(url), "POST", requestContent, null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadStringAsync(Uri, String, String, Object)");
                    }

                    using (Tracer.Instance.StartActive("UploadStringTaskAsync"))
                    {
                        await webClient.UploadStringTaskAsync(url, requestContent);

                        Console.WriteLine("Received response for client.UploadStringTaskAsync(String, String)");

                        await webClient.UploadStringTaskAsync(new Uri(url), requestContent);

                        Console.WriteLine("Received response for client.UploadStringTaskAsync(Uri, String)");

                        await webClient.UploadStringTaskAsync(url, "POST", requestContent);

                        Console.WriteLine("Received response for client.UploadStringTaskAsync(String, String, String)");

                        await webClient.UploadStringTaskAsync(new Uri(url), "POST", requestContent);

                        Console.WriteLine("Received response for client.UploadStringTaskAsync(Uri, String, String)");
                    }

                    var values = new NameValueCollection();
                    using (Tracer.Instance.StartActive("UploadValues"))
                    {
                        webClient.UploadValues(url, values);
                        Console.WriteLine("Received response for client.UploadValues(String, NameValueCollection)");

                        webClient.UploadValues(new Uri(url), values);
                        Console.WriteLine("Received response for client.UploadValues(Uri, NameValueCollection)");

                        webClient.UploadValues(url, "POST", values);
                        Console.WriteLine("Received response for client.UploadValues(String, String, NameValueCollection)");

                        webClient.UploadValues(new Uri(url), "POST", values);
                        Console.WriteLine("Received response for client.UploadValues(Uri, String, NameValueCollection)");
                    }

                    using (Tracer.Instance.StartActive("UploadValuesAsync"))
                    {
                        webClient.UploadValuesAsync(new Uri(url), values);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadValuesAsync(Uri, NameValueCollection)");

                        webClient.UploadValuesAsync(new Uri(url), "POST", values);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadValuesAsync(Uri, String, NameValueCollection)");

                        webClient.UploadValuesAsync(new Uri(url), "POST", values, null);
                        while (webClient.IsBusy)
                        {
                            ;
                        }
                        Console.WriteLine("Received response for client.UploadValuesAsync(Uri, String, NameValueCollection, Object)");
                    }

                    using (Tracer.Instance.StartActive("UploadValuesTaskAsync"))
                    {
                        await webClient.UploadValuesTaskAsync(url, values);

                        Console.WriteLine("Received response for client.UploadValuesTaskAsync(String, NameValueCollection)");

                        await webClient.UploadValuesTaskAsync(new Uri(url), values);

                        Console.WriteLine("Received response for client.UploadValuesTaskAsync(Uri, NameValueCollection)");

                        await webClient.UploadValuesTaskAsync(url, "POST", values);

                        Console.WriteLine("Received response for client.UploadValuesTaskAsync(String, String, NameValueCollection)");

                        await webClient.UploadValuesTaskAsync(new Uri(url), "POST", values);

                        Console.WriteLine("Received response for client.UploadValuesTaskAsync(Uri, String, NameValueCollection)");
                    }
                }
            }
        }
Пример #23
0
        public static T1 RestCallSync <T1>(string input, string endpoint, bool post)
        {
            try
            {
                if (post)
                {
#if WINDOWS_PHONE
                    /*var client = new HttpClient();
                     * //client.BaseAddress = endpoint;
                     *
                     * StringContent content = new StringContent(input, Encoding.UTF8, "application/json");
                     * //content.Headers.Expires = DateTime.UtcNow;
                     *
                     * //var tt = client.GetStreamAsync(endpoint).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().GetResult();
                     *
                     * //Byte[] bytes = Encoding.UTF8.GetBytes(input);
                     *
                     * var m = new HttpRequestMessage(HttpMethod.Get, endpoint);
                     * //m.Content = content;
                     *
                     * HttpResponseMessage resp = client.SendAsync(m).Result;
                     *
                     * var t = client.PostAsync(endpoint, content).ConfigureAwait(continueOnCapturedContext:false).GetAwaiter();
                     * while (!t.IsCompleted)
                     * {
                     *  Thread.Sleep(1000);
                     *
                     *  //t.Wait();
                     * }
                     *
                     * //HttpResponseMessage answer = t.Result;
                     * HttpResponseMessage answer = t.GetResult();
                     * //HttpResponseMessage answer = client.PostAsync(endpoint, content).GetAwaiter().GetResult();
                     * string re = answer.Content.ReadAsStringAsync().Result;
                     * T1 response = JsonConvert.DeserializeObject<T1>(re);
                     * return response;*/

                    WebClient wc  = new WebClient();
                    Uri       uri = new Uri(endpoint);
                    wc.Headers["Content-Type"]   = "application/json";
                    wc.Headers["Cache-Control"]  = "no-cache";
                    wc.Headers["Content-Length"] = input.Length.ToString();
                    wc.UploadStringCompleted    += wc_UploadStringCompleted;
                    wc.UploadStringAsync(uri, "POST", input);


                    var t = getPOSTResponse();

                    T1 response = JsonConvert.DeserializeObject <T1>(t);
                    //wc.CancelAsync();
                    wc = null;
                    return(response);
#else
                    /*client.PostAsync(endpoint,)
                     *
                     * client.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString("r");
                     * client.Headers[HttpRequestHeader.ContentType] = "application/json";
                     *
                     * Byte[] bytes = Encoding.UTF8.GetBytes(input);
                     *
                     * client.OpenWriteAsync(new Uri(endpoint), "POST");
                     *
                     *
                     * //var answer = client.UploadStringAsync(new Uri(endpoint), "POST", input);*/


                    var http = (HttpWebRequest)WebRequest.Create(new Uri(endpoint));
                    //http.Accept = "application/json";
                    http.ContentType = "application/json";
                    if (http.Headers == null)
                    {
                        http.Headers = new WebHeaderCollection();
                    }

                    // Depends on OS!
#if (__ANDROID__ || __IOS__)
                    // Should work for every Android-Version now
                    http.IfModifiedSince = DateTime.UtcNow;
#else
                    // Windows Phone does not know these properties
                    http.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString("r");
#endif
                    http.Method = "POST";

                    Byte[] bytes = Encoding.UTF8.GetBytes(input);

                    using (var stream = Task.Factory.FromAsync <Stream>(http.BeginGetRequestStream,
                                                                        http.EndGetRequestStream, null).Result)
                    {
                        // Write the bytes to the stream
                        stream.WriteAsync(bytes, 0, bytes.Length);
                    }

                    using (var response = Task.Factory.FromAsync <WebResponse>(http.BeginGetResponse,
                                                                               http.EndGetResponse, null).Result)
                    {
                        var stream  = response.GetResponseStream();
                        var sr      = new StreamReader(stream);
                        var content = sr.ReadToEnd();

                        T1 answer = JsonConvert.DeserializeObject <T1>(content);
                        return(answer);
                    }
#endif
                }
                else
                {
                    // For GET, use a simple httpClient
                    HttpClient client = new HttpClient();

                    var response = client.GetAsync(new Uri(endpoint)).Result;
                    var result   = response.Content.ReadAsStringAsync().Result;
                    T1  answer   = JsonConvert.DeserializeObject <T1>(result);
                    //client.CancelPendingRequests();
                    client = null;
                    return(answer);
                }
            }
            catch (Exception ex)
            {
                return(default(T1));
            }
        }
Пример #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("--- Download data sample ---");
            WebClient webclient = new WebClient();

            webclient.Headers.Add("Referer", "http://www.example.com"); // Replace with your domain here
            // Registrer a handler that will execute when download is completed.
            webclient.UploadStringCompleted += (obj, arguments) =>
            {
                if (arguments.Cancelled == true)
                {
                    Console.Write("Request cancelled by user");
                }
                else if (arguments.Error != null)
                {
                    Console.WriteLine(arguments.Error.Message);
                    Console.Write("Request Failed");
                }
                else
                {
                    Console.WriteLine(formatXML(arguments.Result));
                    Console.Write("Data downloaded");
                }
                Console.WriteLine(", press 'X' to exit.");
            };

            try
            {
                string apiKey = System.IO.File.ReadAllText(Environment.CurrentDirectory + "\\" + "api.key");
                // API server url
                Uri    address     = new Uri("http://api.trafikinfo.trafikverket.se/v1/data.xml");
                string requestBody = "<REQUEST>" +
                                     // Use your valid authenticationkey
                                     "<LOGIN authenticationkey='" + apiKey + "'/>" +
                                     "<QUERY objecttype='TrainMessage' >" +
                                     "<FILTER>" +
                                     "<IN name='AffectedLocation' value='Blg'/>" +
                                     "</FILTER>" +
                                     "<EXCLUDE>Deleted</EXCLUDE>" +
                                     "</QUERY>" +
                                     "</REQUEST>";

                webclient.Headers["Content-Type"] = "text/xml";
                Console.WriteLine("Fetching data ... (press 'C' to cancel)");
                webclient.UploadStringAsync(address, "POST", requestBody);
            }
            catch (UriFormatException)
            {
                Console.WriteLine("Malformed url, press 'X' to exit.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("An error occured, press 'X' to exit.");
            }

            char keychar = ' ';

            while (keychar != 'X')
            {
                keychar = Char.ToUpper(Console.ReadKey().KeyChar);
                if (keychar == 'C')
                {
                    webclient.CancelAsync();
                }
            }
        }
Пример #25
0
        private void StartWork(object state)
        {
            // Login
            this.onProgress(this, new HDCallBackEventArgs(this, new TaskProgress(UIResources.TASKDSP_LOGIN, 20)));
            WebClient webClient = new WebClient();

            webClient.Headers["content-type"] = "application/x-www-form-urlencoded";
            webClient.Encoding = Encoding.UTF8;
            bool isLoggedIn = false;

            webClient.UploadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    string result = e.Result;
                    if (result.Contains("pass"))
                    {
                        isLoggedIn = true;
                    }
                }
                else
                {
                    isLoggedIn = false;
                }
                nextOneAutoResetEvent.Set();
            };
            StringBuilder sb       = new StringBuilder();
            string        postData = string.Format(@"u={0}&p={1}", HttpUtility.UrlEncode(this.UserId), HttpUtility.UrlEncode(this.password));

            webClient.UploadStringAsync(new Uri(Globals.WebRootUrl + @"membership/admin-rest-login.html", UriKind.Absolute), "POST", postData);
            nextOneAutoResetEvent.WaitOne();
            if (!isLoggedIn)
            {
                Globals.IsLoggedIn = false;
                this.AsyncHanlder(this, new HDCallBackEventArgs(this, new Exception(UIResources.AUTH_NOROLE), null));
                return;
            }
            else
            {
                Globals.IsLoggedIn = true;
            }

            // Get all categories
            this.onProgress(this, new HDCallBackEventArgs(this, new TaskProgress("Loading all categories...", 70)));
            EventHandler <getAll_CategoryCompletedEventArgs> h1 = (s, e) =>
            {
                if (e.Error == null)
                {
                    this.MDC.allCategories = new List <category>(e.Result);
                }
                nextOneAutoResetEvent.Set();
            };

            Globals.WSClient.getAll_CategoryCompleted += h1;
            Globals.WSClient.getAll_CategoryAsync();
            nextOneAutoResetEvent.WaitOne();
            Globals.WSClient.getAll_CategoryCompleted -= h1;

            //
            // Add filter by category
            //
            int currentTreeNodeCount = ViewItem.Counter;

            foreach (category c in this.mdc.allCategories)
            {
                // Parent is 1 - items
                ViewItem categoryAvi = new ViewItem((int)c.id + currentTreeNodeCount, (int)c.id, 1, c.name, c.pageTitle, PageEnum.ItemListPage);
                this.mdc.itemsTreeView.Add(categoryAvi);
                ContentPageContext cpc = new ContentPageContext(c.id);
                this.AddViewContext(PageEnum.ItemListPage, c.id, cpc);
                this.AddViewContext(PageEnum.ItemDetailsPage, c.id, cpc);
            }

            // Get all tabs
            this.onProgress(this, new HDCallBackEventArgs(this, new TaskProgress(UIResources.WAITINDICATOR_LOADING, 80)));
            EventHandler <getAll_TabCompletedEventArgs> h2 = (s, e) =>
            {
                if (e.Error == null)
                {
                    this.MDC.allTabs = new List <tab>(e.Result);
                }
                nextOneAutoResetEvent.Set();
            };

            Globals.WSClient.getAll_TabCompleted += h2;
            Globals.WSClient.getAll_TabAsync();
            nextOneAutoResetEvent.WaitOne();
            Globals.WSClient.getAll_TabCompleted -= h2;

            // Get all brands
            this.onProgress(this, new HDCallBackEventArgs(this, new TaskProgress(UIResources.WAITINDICATOR_LOADING, 85)));
            EventHandler <getAll_BrandCompletedEventArgs> h3 = (s, e) =>
            {
                if (e.Error == null)
                {
                    this.MDC.allBrands = new List <brand>(e.Result);
                }
                nextOneAutoResetEvent.Set();
            };

            Globals.WSClient.getAll_BrandCompleted += h3;
            Globals.WSClient.getAll_BrandAsync();
            nextOneAutoResetEvent.WaitOne();
            Globals.WSClient.getAll_BrandCompleted -= h3;

            // Get all item templates
            Globals.WSClient.getByType_TemplateCompleted += new EventHandler <getByType_TemplateCompletedEventArgs>(WSClient_getByType_TemplateCompleted);
            Globals.WSClient.getByType_TemplateAsync(templateTypeEnum.ITEM);
            nextOneAutoResetEvent.WaitOne();
            Globals.WSClient.getByType_TemplateCompleted -= new EventHandler <getByType_TemplateCompletedEventArgs>(WSClient_getByType_TemplateCompleted);

            // Get all category templates
            this.onProgress(this, new HDCallBackEventArgs(this, new TaskProgress(UIResources.WAITINDICATOR_LOADING, 95)));
            EventHandler <getByType_TemplateCompletedEventArgs> h5 = (s, e) =>
            {
                if (e.Error == null)
                {
                    this.MDC.allCategoryTemplates = new List <template>(e.Result);
                }
                nextOneAutoResetEvent.Set();
            };

            Globals.WSClient.getByType_TemplateCompleted += h5;
            Globals.WSClient.getByType_TemplateAsync(templateTypeEnum.CATEGORY);
            nextOneAutoResetEvent.WaitOne();
            Globals.WSClient.getByType_TemplateCompleted -= h5;

            // Call back
            if (null != this.AsyncHanlder)
            {
                this.AsyncHanlder(this, new HDCallBackEventArgs(this, null));
            }
        }
Пример #26
0
        protected async Task NewMemoSpeech()
        {
            string message;

            try
            {
                this.SpeechUI.Settings.ShowConfirmation = false;
                message = CensorProfanity((await SpeechUI.RecognizeWithUIAsync()).RecognitionResult.Text);
            }
            catch
            {
                Conversation.Add(new Message("Hello", MessageSide.User));
                return;
            }

            // Got call back.
            Conversation.Add(new Message(message, MessageSide.User));
            message = message.Trim('.', '?', '!').ToLowerInvariant();

            WebClient client = new WebClient();

            if (this.IsTeach)
            {
                Conversation.Add(new Message(String.Format("Adding memo {0}.", message), MessageSide.Cloud));
                BeginScrollDown();
                await this.Synthesizer.SpeakTextAsync(String.Format("Adding memo {0}.", message));

                // Call API
                client.Headers[HttpRequestHeader.Accept] = "application/json";
                client.DownloadStringAsync(
                    new Uri(String.Format(Api.TimeExtractionUri, HttpUtility.UrlEncode(message), DateTime.Now.ToString("s"))));

                // Get time extraction response
                client.DownloadStringCompleted += async(sender, e) =>
                {
                    if (e.Error == null)
                    {
                        DateTime[] time = await JsonConvert.DeserializeObjectAsync <DateTime[]>(e.Result);

                        if (time.Length > 0)
                        {
                            SetupPopup(message, time[0], true);
                        }
                        else
                        {
                            SetupPopup(message, DateTime.Now + new TimeSpan(0, 30, 0), false);
                        }
                    }
                    else
                    {
                        SetupPopup(message, DateTime.Now + new TimeSpan(0, 30, 0), false);
                    }
                };

                // Get geo-position
                Geoposition geoposition;
                if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] == true)
                {
                    Geolocator geolocator = new Geolocator();
                    geolocator.DesiredAccuracyInMeters = 50;

                    try
                    {
                        geoposition = await geolocator.GetGeopositionAsync(
                            maximumAge : TimeSpan.FromMinutes(5),
                            timeout : TimeSpan.FromSeconds(10)
                            );

                        this.CurrentLatitude  = geoposition.Coordinate.Latitude;
                        this.CurrentLongitude = geoposition.Coordinate.Longitude;
                    }
                    catch
                    {
                        this.CurrentLatitude  = null;
                        this.CurrentLongitude = null;
                    }
                }
            }
            else
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.Accept]      = "application/json";
                client.UploadStringAsync(
                    new Uri(String.Format(Api.RetrieveUri, Phone.ID)),
                    JsonConvert.SerializeObject(new
                {
                    content = message
                }));
                client.UploadStringCompleted += async(sender, args) =>
                {
                    if (args.Error == null)
                    {
                        string[] results = JsonConvert.DeserializeObject <string[]>(args.Result);
                        if (results.Length > 0)
                        {
                            IAsyncAction resultAction = this.Synthesizer.SpeakTextAsync(results[0]);
                            this.Conversation.Add(new Message(results[0], MessageSide.Cloud));
                            this.BeginScrollDown();
                            await resultAction;
                        }
                        else
                        {
                            IAsyncAction resultAction = this.Synthesizer.SpeakTextAsync("Can't recall \"" + message + "\".");
                            this.Conversation.Add(new Message("Can't recall \"" + message + "\".", MessageSide.Cloud));
                            this.BeginScrollDown();
                            await resultAction;
                        }
                    }
                    else
                    {
                        await HandleInternetException();
                    }
                };
            }
        }
Пример #27
0
        private void Click_check(object sender, EventArgs e)
        {
            if (IsNetworkAvailable())
            {
                try
                {
                    var webClient = new WebClient();
                    webClient.Headers[HttpRequestHeader.ContentType] = "text/json";
                    webClient.UploadStringCompleted += this.sendPostCompleted;
                    UserData u    = LoggedUser.Instance.userReg;
                    string   json = "{\"Name\":\"" + u.Name + "\"," +
                                    "\"Mail\":\"" + u.Mail + "\"," +
                                    "\"FacebookId\":\"" + u.FacebookId + "\"," +
                                    "\"LinkedInId\":\"" + u.LinkedInId + "\"," +
                                    "\"Password\":\"" + u.Password + "\"}";
                    System.Diagnostics.Debug.WriteLine(json);

                    webClient.UploadStringAsync((new Uri(App.webService + "/api/Users/SignUp/")), "POST", json);
                }
                catch (WebException webex)
                {
                    HttpWebResponse webResp = (HttpWebResponse)webex.Response;

                    switch (webResp.StatusCode)
                    {
                    case HttpStatusCode.NotFound:     // 404
                        break;

                    case HttpStatusCode.InternalServerError:     // 500
                        break;

                    default:
                        break;
                    }
                }
            }
            else
            {
                SolidColorBrush  mybrush    = new SolidColorBrush(Color.FromArgb(255, 0, 175, 240));
                CustomMessageBox messageBox = new CustomMessageBox()
                {
                    Caption           = AppResources.NoInternetConnection,
                    Message           = AppResources.NoInternetConnectionMessageRegister,
                    LeftButtonContent = AppResources.OkTitle,
                    Background        = mybrush,
                    IsFullScreen      = false,
                };


                messageBox.Dismissed += (s1, e1) =>
                {
                    switch (e1.Result)
                    {
                    case CustomMessageBoxResult.LeftButton:
                        break;

                    case CustomMessageBoxResult.None:
                        // Acción.
                        break;

                    default:
                        break;
                    }
                };

                messageBox.Show();
            }
        }
Пример #28
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }
        /// <summary>
        /// Call web service for senduserdetails
        /// </summary>
        private void CallSendUserDetailsWebService()
        {
            objYourDetTCViewModel.ProgressBarVisibilty = Visibility.Visible;
            string apiUrl = RxConstants.sendUserDetails;
            string gender = "0";

            try
            {
                if (objYourDetTCViewModel.IsMaleSelected)
                {
                    gender = "1";
                }
                else
                {
                    gender = "0";
                }
                string deviceUniqueID = string.Empty;
                object deviceID;

                if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out deviceID))
                {
                    deviceUniqueID = deviceID.ToString();
                }

                string deviceName = string.Empty;
                object devicename;

                if (DeviceExtendedProperties.TryGetValue("DeviceName", out devicename))
                {
                    deviceName = devicename.ToString();
                }
                string emptyStringValue = "Choose Doctor for surgery (Optional)";
                SendUserDetailsRequest objInputParameters = new SendUserDetailsRequest
                {
                    pharmacyid = App.LoginPharId.ToUpper(),
                    model      = DeviceModel,
                    os         = "Windows Phone",
                    fullname   = objYourDetTCViewModel.FirstName + " " + objYourDetTCViewModel.LastName,
                    nhs        = objYourDetTCViewModel.NHS,
                    birthdate  = objYourDetTCViewModel.DOB,
                    address1   = objYourDetTCViewModel.AddressLine1,
                    address2   = objYourDetTCViewModel.AddressLine2,
                    postcode   = objYourDetTCViewModel.PostCode,
                    phone      = objYourDetTCViewModel.MobileNo,
                    mail       = objYourDetTCViewModel.EmailId,
                    sex        = gender,
                    pin        = App.HashPIN,
                    country    = objYourDetTCViewModel.SelectedCountry,
                    surgery    = new SendUserDetailsRequestSurgery
                    {
                        name    = ((!string.IsNullOrEmpty(App.SurgeonSaved)) && (!string.IsNullOrWhiteSpace(App.SurgeonSaved)) && (App.SurgeonSaved != emptyStringValue)) ? App.SurgeonSaved : string.Empty,
                        address = ((!string.IsNullOrEmpty(App.SurgeonAddress)) && (!string.IsNullOrWhiteSpace(App.SurgeonAddress)) && (App.SurgeonSaved != emptyStringValue)) ? App.SurgeonAddress : string.Empty
                    },
                    system_version   = "android",
                    app_version      = "1.6",
                    branding_version = "MLP"
                };
                WebClient sendUserDetailswebservicecall = new WebClient();
                var       uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute);

                var json = JsonHelper.Serialize(objInputParameters);
                sendUserDetailswebservicecall.Headers["Content-type"] = "application/json";
                sendUserDetailswebservicecall.UploadStringCompleted  += sendUserDetailswebservicecall_UploadStringCompleted;

                sendUserDetailswebservicecall.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception)
            {
                objYourDetTCViewModel.HitVisibility        = true;
                objYourDetTCViewModel.ProgressBarVisibilty = Visibility.Collapsed;
                MessageBox.Show("Sorry, Unable to process your request.");
            }
        }
Пример #30
0
        public void FetchTrainMessages(Label TrainInfoLabel, int TrainNumber, string StationShortName, string ArrivalTime)
        {
            WebClient webclient = new WebClient();

            webclient.UploadStringCompleted += (obj, arguments) =>
            {
                var ListOfResult = FormatTrainMessagesJSON(arguments.Result);

                TrainInfoLabel.Text = "Info: ";
                foreach (var Tmessage in ListOfResult)
                {
                    if (Tmessage.LocationSignature == StationShortName && Tmessage.AdvertisedTimeAtLocation == ArrivalTime)
                    {
                        if (Tmessage.Canceled == true)
                        {
                            foreach (var explanation in Tmessage.Deviation)
                            {
                                TrainInfoLabel.Text += explanation + " ";
                            }
                            TrainInfoLabel.Text += Tmessage.WebLink;
                        }
                        else
                        {
                            if (Tmessage.ToLocation != null)
                            {
                                if (Tmessage.ActivityType == "Avgang")
                                {
                                    if (Tmessage.EstimatedTimeAtLocation != null)
                                    {
                                        var newTime = Tmessage.EstimatedTimeAtLocation.Split('T');
                                        TrainInfoLabel.Text += "Estimerad tid: " + newTime[1].Substring(0, 5) + " ";
                                    }
                                    else
                                    {
                                        var Time = Tmessage.AdvertisedTimeAtLocation.Split('T');
                                        TrainInfoLabel.Text += "Ankomsttid: " + Time[1].Substring(0, 5) + " ";
                                    }


                                    var ToLocationName = GetStationFullName(Tmessage.ToLocation[0].LocationName);
                                    if (Tmessage.ToLocation[0].LocationName == "No.nk")
                                    {
                                        ToLocationName = "Narvik";
                                    }

                                    TrainInfoLabel.Text +=
                                        " TrainNr: " + Tmessage.AdvertisedTrainIdent +
                                        "  mot " + ToLocationName;
                                }
                            }
                        }
                    }
                }
            };

            Uri    address     = new Uri(ImportantVariables.APIAdress);
            string requestBody = ImportantVariables.RequestTrainMessageQuery(TrainNumber);

            webclient.Encoding = Encoding.UTF8;
            webclient.UploadStringAsync(address, "POST", requestBody);
        }
Пример #31
0
        public static void TranslateComponent(object Obj, string TranslateTo)
        {
            string tData = "", nData = "";

            if (Obj.GetType() == typeof(Label) || Obj.GetType() == typeof(Button) ||
                Obj.GetType() == typeof(CheckBox) || Obj.GetType() == typeof(GroupBox) ||
                Obj.GetType() == typeof(TabPage))
            {
                tData = ((Control)Obj).Text;
                nData = ((Control)Obj).Name;
                if (Includes.Registry.GetText(nData, tData, TranslateTo, FirstTranslate, ref tData))
                {
                    ((Control)Obj).Text = tData;
                    return;
                }
            }
            else if (Obj.GetType() == typeof(ToolStripMenuItem))
            {
                tData = ((ToolStripMenuItem)Obj).Text;
                nData = ((ToolStripMenuItem)Obj).Name;
                if (Includes.Registry.GetText(nData, tData, TranslateTo, FirstTranslate, ref tData))
                {
                    ((ToolStripMenuItem)Obj).Text = tData;
                    return;
                }
            }
            else if (Obj.GetType() == typeof(ColumnHeader))
            {
                tData = ((ColumnHeader)Obj).Text;
                nData = ((ColumnHeader)Obj).Name;
                if (Includes.Registry.GetText(nData, tData, TranslateTo, FirstTranslate, ref tData))
                {
                    ((ColumnHeader)Obj).Text = tData;
                    return;
                }
            }

            try
            {
                using (WebClient wb = new WebClient())
                {
                    wb.Headers.Add(HttpRequestHeader.UserAgent, "AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1");
                    wb.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");
                    wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    wb.Encoding = Encoding.UTF8;
                    wb.UploadStringCompleted += (e, a) =>
                    {
                        if (a.Cancelled)
                        {
                            return;
                        }
                        if (a.Result.Length > 0 && a.Result.Contains("\"trans\""))
                        {
                            string[] splts = a.Result.Split('"');
                            if (splts.Length > 5)
                            {
                                if (Obj.GetType() == typeof(Label) || Obj.GetType() == typeof(Button) ||
                                    Obj.GetType() == typeof(CheckBox) || Obj.GetType() == typeof(GroupBox) ||
                                    Obj.GetType() == typeof(TabPage))
                                {
                                    ((Control)Obj).Text = splts[5];
                                }
                                else if (Obj.GetType() == typeof(ToolStripMenuItem))
                                {
                                    ((ToolStripMenuItem)Obj).Text = splts[5];
                                }
                                else if (Obj.GetType() == typeof(ColumnHeader))
                                {
                                    ((ColumnHeader)Obj).Text = splts[5];
                                }
                                else
                                {
                                    return;
                                }

                                Includes.Registry.GetText(nData, splts[5], TranslateTo, false, ref tData);
                            }
                        }
                    };


                    wb.UploadStringAsync(new Uri("https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e"), "POST", "sl=en&tl=" + TranslateTo + "&q=" + WebUtility.UrlEncode(tData));
                }
            }
            catch
            {
            }
        }
Пример #32
0
        /// <summary>
        /// Call web service for send nomination
        /// </summary>
        private void CallSendNominationWebService()
        {
            objYourDetlginViewModel.ProgressBarVisibilty = Visibility.Visible;
            string apiUrl = RxConstants.sendNomination;

            try
            {
                string gender = "0";
                if (objYourDetlginViewModel.IsMaleSelected)
                {
                    gender = "1";
                }
                else
                {
                    gender = "0";
                }


                if (objYourDetlginViewModel.IsMailSelected)
                {
                    verifyBy = "mail";
                }
                else
                {
                    verifyBy = "sms";
                }

                string deviceUniqueID = string.Empty;
                object deviceID;

                if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out deviceID))
                {
                    byte[] myDeviceID = (byte[])deviceID;
                    deviceUniqueID = Convert.ToBase64String(myDeviceID);
                }

                string deviceName = string.Empty;
                object devicename;

                if (DeviceExtendedProperties.TryGetValue("DeviceName", out devicename))
                {
                    deviceName = devicename.ToString();
                }
                string emptyStringValue = "Choose Doctor for surgery (Optional)";
                SendNominationRequest objInputParameters = new SendNominationRequest
                {
                    pharmacyid = App.SignUpPharId.ToUpper(),
                    deviceid   = deviceUniqueID,
                    model      = DeviceModel,
                    os         = "Windows Phone",
                    pushid     = App.ApId,
                    fullname   = objYourDetlginViewModel.FirstName + " " + objYourDetlginViewModel.LastName,
                    nhs        = objYourDetlginViewModel.NHS,
                    birthdate  = objYourDetlginViewModel.DOB.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
                    address1   = objYourDetlginViewModel.AddressLine1,
                    address2   = objYourDetlginViewModel.AddressLine2,
                    postcode   = objYourDetlginViewModel.PostCode,
                    phone      = objYourDetlginViewModel.MobileNo,
                    mail       = objYourDetlginViewModel.EmailId,
                    sex        = gender,
                    pin        = App.HashPIN,
                    country    = objYourDetlginViewModel.SelectedCountry,
                    mode       = "new",
                    verifyby   = verifyBy,
                    surgery    = new SendNominationRequestSurgery
                    {
                        name = ((!string.IsNullOrEmpty(App.SelectedSurgen)) && (!string.IsNullOrWhiteSpace(App.SelectedSurgen)) && (App.SelectedSurgen != emptyStringValue)) ? App.SelectedSurgen : string.Empty,

                        address = ((!string.IsNullOrEmpty(App.SurgeonAddress)) && (!string.IsNullOrWhiteSpace(App.SurgeonAddress)) && (App.SelectedSurgen != emptyStringValue)) ? App.SurgeonAddress : string.Empty
                    },
                    system_version   = "android",
                    app_version      = "1.6",
                    branding_version = "MLP"
                };
                App.SelectedSurgen = string.Empty;
                App.SurgeonAddress = string.Empty;
                WebClient sendNominationswebservicecall = new WebClient();
                var       uri = new Uri(apiUrl, UriKind.RelativeOrAbsolute);

                var json = JsonHelper.Serialize(objInputParameters);
                sendNominationswebservicecall.Headers["Content-type"] = "application/json";
                sendNominationswebservicecall.UploadStringCompleted  += sendNominationswebservicecall_UploadStringCompleted;

                sendNominationswebservicecall.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception)
            {
                MessageBox.Show("Sorry, Unable to process your request.");
            }
        }
Пример #33
0
        private void SendResults()
        {
            string finalURL = Application.Current.Host.Source.AbsoluteUri;

            string[] temps = finalURL.Split('/');
            string   postUrl;

            //TODO: Enum this
            string result            = "";
            string resultRebuffering = "";
            string resultFrameDrops  = "";
            string resultDesync      = "";
            string resultResolution  = "";

            if (App.ro.result == 0)
            {
                result = "GOOD";
            }
            else if (App.ro.result == 1)
            {
                result = "POOR";

                //old results
                //result = "FAIR";
            }
            else if (App.ro.result == 2)
            {
                result = "POOR";
            }
            else
            {
                result = "Unknown";
            }

            if (App.ro.resultRebuffering == 0)
            {
                resultRebuffering = "GOOD";
            }
            else if (App.ro.resultRebuffering == 1)
            {
                resultRebuffering = "POOR";

                //old results
                //resultRebuffering = "FAIR";
            }
            else if (App.ro.resultRebuffering == 2)
            {
                resultRebuffering = "POOR";
            }
            else
            {
                resultRebuffering = "Unknown";
            }

            if (App.ro.resultDroppedFrames == 0)
            {
                resultFrameDrops = "GOOD";
            }
            else if (App.ro.resultDroppedFrames == 1)
            {
                resultFrameDrops = "POOR";

                //old results
                //resultFrameDrops = "FAIR";
            }
            else if (App.ro.resultDroppedFrames == 2)
            {
                resultFrameDrops = "POOR";
            }
            else
            {
                resultFrameDrops = "Unknown";
            }

            if (App.ro.resultDesync == 0)
            {
                resultDesync = "GOOD";
            }
            else if (App.ro.resultDesync == 1)
            {
                resultDesync = "POOR";

                //old results
                //resultDesync = "FAIR";
            }
            else if (App.ro.resultDesync == 2)
            {
                resultDesync = "POOR";
            }
            else
            {
                resultDesync = "Unknown";
            }

            StringBuilder mediaResolution = new StringBuilder();

            mediaResolution.Append(App.ro.SelectedMedia.ToString());
            mediaResolution.Remove(0, 1);
            resultResolution = mediaResolution.ToString();
            string sessionId = App.ro.sessionId;

            string parameter = new StringBuilder("result=" + result + "&" +
                                                 "resultRebuffering=" + resultRebuffering + "&" +
                                                 "resultFrameDrops=" + resultFrameDrops + "&" +
                                                 "resultDesync=" + resultDesync + "&" +
                                                 "resultResolution=" + resultResolution + "&" +
                                                 "sessionId=" + sessionId).ToString();

            postUrl         = "http://" + App.ServerIp + "/iemt/result.php?" + parameter;
            tbMessages.Text = postUrl;

            try
            {
                var wc = new WebClient();
                wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
                wc.UploadStringAsync(new Uri(postUrl), "POST");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            //debug
            string postDebugUrl = "http://" + App.MediaServerIp + "/iemt/result.php?" + parameter;

            try
            {
                var wc = new WebClient();
                wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
                wc.UploadStringAsync(new Uri(postDebugUrl), "POST");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Пример #34
0
        protected override void Write(AsyncLogEventInfo info)
        {
            try
            {
                var client = new WebClient();
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

                if (_authorizationHeader != null)
                {
                    client.Headers[HttpRequestHeader.Authorization] = _authorizationHeader;
                }

                var url    = new Uri(_url + _indexTemplate.Render(info.LogEvent));
                var layout = this.Layout.Render(info.LogEvent);
                var json   = JObject.Parse(layout); // make sure the json is valid

                if (info.LogEvent.Exception != null)
                {
                    var nfo = JObject.FromObject(info.LogEvent.Exception);
                    json.Add("exception", nfo);
                }

                var message = json["@message"].ToString();

                if (IsStringAValidJson(message))
                {
                    json["@message"] = JObject.Parse(message);
                }
                else
                {
                    json["@message"] = JObject.Parse(string.Format(@"{{ ""Content"":""{0}""}}", message));
                }


                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, "POST", json.ToString());
            }
            catch (Exception ex)
            {
                info.Continuation(ex);
            }
        }
Пример #35
0
        public ConversationPage()
        {
            InitializeComponent();

            this.TR.btnRetrieve.Checked   += this.btnRetrieve_Checked;
            this.TR.btnTeach.Checked      += this.btnTeach_Checked;
            this.TR.btnRetrieve.Unchecked += this.btnTeach_Checked;
            this.TR.btnTeach.Unchecked    += this.btnRetrieve_Checked;
            this.TS.MouseLeftButtonDown   += this.tapToSpeakGrid_MouseLeftButtonDown;
            this.TS.MouseLeftButtonUp     += this.tapToSpeakGrid_MouseLeftButtonUp;

            this.DataContext = Conversation;

            this.SpeechUI    = new SpeechRecognizerUI();
            this.Synthesizer = new SpeechSynthesizer();

            NewMemoPopUp                     = new Popup();
            NewMemoPopUpControl              = new NewMemoPopUp();
            NewMemoPopUpControl.Width        = Application.Current.Host.Content.ActualWidth;
            NewMemoPopUpControl.btnOK.Click += (s, args) =>
            {
                MemoItem item = new MemoItem();
                item.Latitude  = this.CurrentLatitude;
                item.Longitude = this.CurrentLongitude;
                item.Content   = this.NewMemoPopUpControl.txtBox.Text;
                item.HasAlarm  = this.NewMemoPopUpControl.alarmCheck.IsChecked.Value;
                DateTime?date = NewMemoPopUpControl.datePicker.Value;
                DateTime?time = NewMemoPopUpControl.timePicker.Value;
                item.RemindTime = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day,
                                               time.Value.Hour, time.Value.Minute, time.Value.Second);
                string teachRequest = JsonConvert.SerializeObject(item);
                NewMemoPopUp.IsOpen = false;
                WebClient client = new WebClient();
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.Accept]      = "application/json";
                client.UploadStringAsync(new Uri(String.Format(Api.TeachUri, Phone.ID)), teachRequest);
                client.UploadStringCompleted += async(obj, e) =>
                {
                    if (e.Error == null)
                    {
                        if (item.HasAlarm)
                        {
                            Reminder reminder = new Reminder(item.RemindTime.ToString());
                            reminder.Title          = "Speech Memo Reminder";
                            reminder.Content        = item.Content;
                            reminder.BeginTime      = item.RemindTime;
                            reminder.ExpirationTime = item.RemindTime + new TimeSpan(0, 5, 0);
                            reminder.NavigationUri  = new Uri("/MainPage.xaml", UriKind.Relative);
                            try
                            {
                                ScheduledActionService.Add(reminder);
                            }
                            catch
                            {
                            }
                        }
                        string       x      = JsonConvert.DeserializeObject <string>(e.Result);
                        IAsyncAction action = this.Synthesizer.SpeakTextAsync(x);
                        this.Conversation.Add(new Message(x, MessageSide.Cloud));
                        this.BeginScrollDown();
                        await action;
                    }
                    else
                    {
                        await HandleInternetException();
                    }
                };
            };

            NewMemoPopUpControl.btnCancel.Click += (s, args) =>
            {
                NewMemoPopUp.IsOpen = false;
            };

            NewMemoPopUp.Child = NewMemoPopUpControl;
            Startup();
        }