Esempio n. 1
0
        public static async Task <bool> markAsDeleteMsg(OutTable obj)
        {
            if (obj == null)
            {
                return(false);
            }
                        string completeUri = "https://function-queue-connect.azurewebsites.net/api/HttpPUT-CRUD-CSharp2?code=E3cZTihW7ZvJjfPgbWITpZbKApX8OHKj4BNwwKz3Sjur5HhRk3zrkA==";
            outTableChange     new_msg     = new outTableChange();

            new_msg.Message_Recive = "0";
            new_msg.Message_Send   = "0";
            new_msg.RowKey         = obj.RowKey;
            new_msg.PartitionKey   = obj.PartitionKey;
            //string json = ConnectDB.WriteFromObject(obj);
            string json = JsonConvert.SerializeObject(new_msg);

            try
            {
                                //Send the PUT request
                                Windows.Web.Http.HttpStringContent stringContent = new Windows.Web.Http.HttpStringContent(json.ToString());
                System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(new System.Net.Http.HttpMethod("PUT"), completeUri);
                request.Content = new StringContent(json,
                                                    Encoding.UTF8,
                                                    "application/json");                                 //CONTENT-TYPE header
                                System.Net.Http.HttpClient client   = new System.Net.Http.HttpClient();
                System.Net.Http.HttpResponseMessage        response = await client.SendAsync(request);   //I know I should have used async/await here!
                                    return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
 public void CompressedWebContent_Constructor_ThrowsOnUnsupportedContentType()
 {
     Assert.ThrowsException <InvalidOperationException>(() =>
     {
         var innerContent         = new Windows.Web.Http.HttpStringContent("Test");
         var CompressedWebContent = new CompressedWebContent(innerContent, "123");
     });
 }
        public async Task CompressedWebContent_BufferAllAsync_ExecutesWithoutException()
        {
            var innerContent = new Windows.Web.Http.HttpStringContent("Jim Jimmy Jim Jim Jimney");
            var CompressedWebContent = new CompressedWebContent(innerContent, "deflate");
            await CompressedWebContent.BufferAllAsync().AsTask().ConfigureAwait(false);

            //TODO: Apart from no exception thrown, not really sure how to test this.
        }
 public void CompressedWebContent_Constructor_ThrowsOnNullEncoding()
 {
     Assert.ThrowsException <ArgumentNullException>(() =>
     {
         var innerContent         = new Windows.Web.Http.HttpStringContent("Test");
         var CompressedWebContent = new CompressedWebContent(innerContent, null);
     });
 }
        public async Task CompressedWebContent_ReadAsStringAsync_ReturnsCompressedString()
        {
            var contentString        = "Jim Jimmy Jim Jim Jimney";
            var innerContent         = new Windows.Web.Http.HttpStringContent(contentString);
            var CompressedWebContent = new CompressedWebContent(innerContent, "deflate");
            var result = await CompressedWebContent.ReadAsStringAsync();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Length < contentString.Length);
        }
        public async Task CompressedWebContent_ReadAsBufferAsync_ReturnsCompressedBytes()
        {
            var contentString        = "Jim Jimmy Jim Jim Jimney";
            var innerContent         = new Windows.Web.Http.HttpStringContent(contentString);
            var CompressedWebContent = new CompressedWebContent(innerContent, "deflate");
            var result = await CompressedWebContent.ReadAsBufferAsync().AsTask().ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Length < contentString.Length);
        }
        public void CompressedWebContent_Constructor_CopiesOriginalHeaders()
        {
            var innerContent = new Windows.Web.Http.HttpStringContent("Test");

            innerContent.Headers.ContentDisposition          = new Windows.Web.Http.Headers.HttpContentDispositionHeaderValue("test");
            innerContent.Headers.ContentDisposition.FileName = "test";
            var CompressedWebContent = new CompressedWebContent(innerContent, "deflate");

            Assert.AreEqual("test", CompressedWebContent.Headers.ContentDisposition.FileName);
        }
        public async Task CompressedWebContent_ReadAsInputStreamAsync_ReturnsCompressedStream()
        {
            var contentString        = "Jim Jimmy Jim Jim Jimney";
            var innerContent         = new Windows.Web.Http.HttpStringContent(contentString);
            var CompressedWebContent = new CompressedWebContent(innerContent, "deflate");
            var result = await CompressedWebContent.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false);

            var stream = result.AsStreamForRead();

            Assert.IsNotNull(stream);
            var ms = new System.IO.MemoryStream();

            stream.CopyTo(ms);
            Assert.IsTrue(ms.Length < contentString.Length);
        }
Esempio n. 9
0
 public async Task<string> PostAsync(Uri uri, string content, CancellationToken ct, IProgress<HttpProgress> progress)
 {
     var httpContent = new Windows.Web.Http.HttpStringContent(content, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
     Windows.Web.Http.HttpResponseMessage r;
     if (progress != null)
     {
         Progress<Windows.Web.Http.HttpProgress> httpProgress = new Progress<Windows.Web.Http.HttpProgress>();
         httpProgress.ProgressChanged += HttpProgress_ProgressChanged;
         progresses[httpProgress] = progress;
         r = await Client.PostAsync(uri, httpContent).AsTask(ct, httpProgress);
     }
     else
     {
         r = await Client.PostAsync(uri, httpContent).AsTask(ct);
     }
     return await r.Content.ReadAsStringAsync();
 }
Esempio n. 10
0
        public static async Task <string> headUpload(string stunum, string fileUri, string uri = "http://hongyan.cqupt.edu.cn/cyxbsMobile/index.php/home/Photo/upload", bool isPath = false)
        {
            Windows.Web.Http.HttpClient _httpClient = new Windows.Web.Http.HttpClient();
            CancellationTokenSource     _cts        = new CancellationTokenSource();

            Windows.Web.Http.HttpStringContent stunumStringContent = new Windows.Web.Http.HttpStringContent(stunum);
            string head = "";
            //IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
            IStorageFile saveFile;

            if (isPath)
            {
                saveFile = await StorageFile.GetFileFromPathAsync(fileUri);
            }
            else
            {
                saveFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(fileUri));
            }

            try
            {
                // 构造需要上传的文件数据
                IRandomAccessStreamWithContentType stream1 = await saveFile.OpenReadAsync();

                Windows.Web.Http.HttpStreamContent            streamContent = new Windows.Web.Http.HttpStreamContent(stream1);
                Windows.Web.Http.HttpMultipartFormDataContent fileContent   = new Windows.Web.Http.HttpMultipartFormDataContent();

                fileContent.Add(streamContent, "fold", "head.png");
                fileContent.Add(stunumStringContent, "stunum");

                Windows.Web.Http.HttpResponseMessage response =
                    await
                    _httpClient.PostAsync(new Uri(uri), fileContent)
                    .AsTask(_cts.Token);

                head = Utils.ConvertUnicodeStringToChinese(await response.Content.ReadAsStringAsync().AsTask(_cts.Token));
                Debug.WriteLine(head);
                return(head);
            }
            catch (Exception)
            {
                Debug.WriteLine("上传头像失败,编辑页面");
                return("");
            }
        }
Esempio n. 11
0
        public async Task <string> PostAsync(Uri uri, string content, CancellationToken ct, IProgress <HttpProgress> progress)
        {
            var httpContent = new Windows.Web.Http.HttpStringContent(content, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

            Windows.Web.Http.HttpResponseMessage r;
            if (progress != null)
            {
                Progress <Windows.Web.Http.HttpProgress> httpProgress = new Progress <Windows.Web.Http.HttpProgress>();
                httpProgress.ProgressChanged += HttpProgress_ProgressChanged;
                progresses[httpProgress]      = progress;
                r = await Client.PostAsync(uri, httpContent).AsTask(ct, httpProgress);
            }
            else
            {
                r = await Client.PostAsync(uri, httpContent).AsTask(ct);
            }
            return(await r.Content.ReadAsStringAsync());
        }
Esempio n. 12
0
        public async Task <Answer> PostAsync(string api, string content)
        {
            Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();

            try
            {
                var postContent     = new Windows.Web.Http.HttpStringContent(content);
                Uri resourceAddress = new Uri(api);

                Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(resourceAddress, postContent);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                {
                    return(new Answer(responseContent, ResponseStatus.Success));
                }
                else if (response.StatusCode == Windows.Web.Http.HttpStatusCode.BadRequest)
                {
                    return(new Answer(responseContent, ResponseStatus.InvalidToken));
                }
                else if ((int)response.StatusCode == 429)
                {
                    return(new Answer(responseContent, ResponseStatus.InvalidToken));
                }
            }
            catch (HttpRequestException)
            {
                client.Dispose();
            }
            catch (Exception)
            {
                client.Dispose();
            }

            Uri dataUri = new Uri("ms-appx:///DataModel/ConnectionError.json");
            var file    = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(dataUri);

            string jsonText = await Windows.Storage.FileIO.ReadTextAsync(file);

            return(new Answer(jsonText, ResponseStatus.ConnectionError));
        }
Esempio n. 13
0
        /// <summary>
        /// GetToken method
        /// </summary>
        /// <param name="subscriptionKey">SubscriptionKey associated with the SpeechToText
        /// Cognitive Service subscription.
        /// </param>
        /// <return>Token which is used for all calls to the SpeechToText REST API.
        /// </return>
        public async System.Threading.Tasks.Task <string> GetToken(string subscriptionKey)
        {
            if (string.IsNullOrEmpty(subscriptionKey))
            {
                return(string.Empty);
            }
            SubscriptionKey = subscriptionKey;
            try
            {
                Token = string.Empty;
                Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient();
                hc.DefaultRequestHeaders.TryAppendWithoutValidation("Ocp-Apim-Subscription-Key", SubscriptionKey);
                Windows.Web.Http.HttpStringContent   content = new Windows.Web.Http.HttpStringContent(String.Empty);
                Windows.Web.Http.HttpResponseMessage hrm     = await hc.PostAsync(new Uri(AuthUrl), content);

                if (hrm != null)
                {
                    switch (hrm.StatusCode)
                    {
                    case Windows.Web.Http.HttpStatusCode.Ok:
                        var b = await hrm.Content.ReadAsBufferAsync();

                        string result = System.Text.UTF8Encoding.UTF8.GetString(b.ToArray());
                        if (!string.IsNullOrEmpty(result))
                        {
                            Token = "Bearer  " + result;
                            return(Token);
                        }
                        break;

                    default:
                        System.Diagnostics.Debug.WriteLine("Http Response Error:" + hrm.StatusCode.ToString() + " reason: " + hrm.ReasonPhrase.ToString());
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception while getting the token: " + ex.Message);
            }
            return(string.Empty);
        }
Esempio n. 14
0
        private async void SaveArmy(PlanArmy army)
        {
            // Construct the HttpClient and Uri. This endpoint is for test purposes only.
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            Uri uri = new Uri(Constants.ArmiesController);

            // Construct the JSON to post.
            Windows.Web.Http.HttpStringContent content = new Windows.Web.Http.HttpStringContent(
                JsonConvert.SerializeObject(army),
                Windows.Storage.Streams.UnicodeEncoding.Utf8,
                "application/json");

            // Post the JSON and wait for a response.
            Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                uri,
                content);

            // Make sure the post succeeded, and write out the response.
            httpResponseMessage.EnsureSuccessStatusCode();
            var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
        }
Esempio n. 15
0
        public static async Task<string> headUpload(string stunum, string fileUri, string uri = "http://hongyan.cqupt.edu.cn/cyxbsMobile/index.php/home/Photo/upload", bool isPath = false)
        {
            Windows.Web.Http.HttpClient _httpClient = new Windows.Web.Http.HttpClient();
            CancellationTokenSource _cts = new CancellationTokenSource();
            Windows.Web.Http.HttpStringContent stunumStringContent = new Windows.Web.Http.HttpStringContent(stunum);
            string head = "";
            //IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
            IStorageFile saveFile;
            if (isPath)
                saveFile = await StorageFile.GetFileFromPathAsync(fileUri);
            else
                saveFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(fileUri));

            try
            {
                // 构造需要上传的文件数据
                IRandomAccessStreamWithContentType stream1 = await saveFile.OpenReadAsync();
                Windows.Web.Http.HttpStreamContent streamContent = new Windows.Web.Http.HttpStreamContent(stream1);
                Windows.Web.Http.HttpMultipartFormDataContent fileContent = new Windows.Web.Http.HttpMultipartFormDataContent();

                fileContent.Add(streamContent, "fold", "head.png");
                fileContent.Add(stunumStringContent, "stunum");

                Windows.Web.Http.HttpResponseMessage response =
                    await
                        _httpClient.PostAsync(new Uri(uri), fileContent)
                            .AsTask(_cts.Token);
                head = Utils.ConvertUnicodeStringToChinese(await response.Content.ReadAsStringAsync().AsTask(_cts.Token));
                Debug.WriteLine(head);
                return head;
            }
            catch (Exception)
            {
                Debug.WriteLine("上传头像失败,编辑页面");
                return "";
            }
        }
Esempio n. 16
0
        private async Task GetTwitterUserNameAsync(string webAuthResultResponseData)
        {
            //
            // Acquiring a access_token first
            //
            try
            {
                string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token"));
                string request_token = null;
                string oauth_verifier = null;
                String[] keyValPairs = responseData.Split('&');

                for (int i = 0; i < keyValPairs.Length; i++)
                {
                    String[] splits = keyValPairs[i].Split('=');
                    switch (splits[0])
                    {
                        case "oauth_token":
                            request_token = splits[1];
                            break;
                        case "oauth_verifier":
                            oauth_verifier = splits[1];
                            break;
                    }
                }

                String TwitterUrl = "https://api.twitter.com/oauth/access_token";

                string timeStamp = GetTimeStamp();
                string nonce = GetNonce();

                String SigBaseStringParams = "oauth_consumer_key=" + "ooWEcrlhooUKVOxSgsVNDJ1RK";
                SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
                SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
                SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
                SigBaseStringParams += "&" + "oauth_token=" + request_token;
                SigBaseStringParams += "&" + "oauth_version=1.0";
                String SigBaseString = "POST&";
                SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

                String Signature = GetSignature(SigBaseString, "BtLpq9ZlFzXrFklC2f1CXqy8EsSzgRRVPZrKVh0imI2TOrZAan");

                Windows.Web.Http.HttpStringContent httpContent = new Windows.Web.Http.HttpStringContent("oauth_verifier=" + oauth_verifier, Windows.Storage.Streams.UnicodeEncoding.Utf8);
                httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                string authorizationHeaderParams = "oauth_consumer_key=\"" + "ooWEcrlhooUKVOxSgsVNDJ1RK" + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(request_token) + "\", oauth_version=\"1.0\"";

                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

                httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", authorizationHeaderParams);
                var httpResponseMessage = await httpClient.PostAsync(new Uri(TwitterUrl), httpContent);
                string response = await httpResponseMessage.Content.ReadAsStringAsync();

                String[] Tokens = response.Split('&');
                string oauth_token_secret = null;
                string access_token = null;
                string screen_name = null;
                string user_id = null;

                for (int i = 0; i < Tokens.Length; i++)
                {
                    String[] splits = Tokens[i].Split('=');
                    switch (splits[0])
                    {
                        case "screen_name":
                            screen_name = splits[1];
                            break;
                        case "oauth_token":
                            access_token = splits[1];
                            break;
                        case "oauth_token_secret":
                            oauth_token_secret = splits[1];
                            break;
                        case "user_id":
                            user_id = splits[1];
                            break;
                    }
                }

                // Check if everything is fine AND do_SOCIAL__CNX
                if (user_id != null && access_token != null && oauth_token_secret != null)
                {
                    social_connection(user_id, oauth_token_secret, "twitter");
                }
            }
            catch (Exception Error)
            {
                new MessageDialog("Erreur lors de la recuperation du token Twitter").ShowAsync();
            }
        }
Esempio n. 17
0
 private async void LoadAboutData(string hash)
 {
     var httpclient = new Windows.Web.Http.HttpClient();
     TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
     var time = Convert.ToInt64(ts.TotalMilliseconds).ToString();
     var key = Class.MD5.GetMd5String("1005Ilwieks28dk2k092lksi2UIkp8150" + time);
     var postobj = new JsonObject();
     postobj.Add("appid", JsonValue.CreateStringValue("1005"));
     postobj.Add("mid", JsonValue.CreateStringValue(""));
     postobj.Add("clientver", JsonValue.CreateStringValue("8150"));
     postobj.Add("clienttime", JsonValue.CreateStringValue("1469035332000"));
     postobj.Add("key", JsonValue.CreateStringValue("27b498a7d890373fadb673baa1dabf7e"));
     var array = new JsonArray();
     var videodata = new JsonObject();
     videodata.Add("video_hash", JsonValue.CreateStringValue(hash));
     videodata.Add("video_id", JsonValue.CreateNumberValue(0));
     array.Add(videodata);
     postobj.Add("data", array);
     var postdata = new Windows.Web.Http.HttpStringContent(postobj.ToString());
     var result= await httpclient.PostAsync(new Uri("http://kmr.service.kugou.com/v1/video/related"), postdata);
     var json = await result.Content.ReadAsStringAsync();
     json = json.Replace("{size}", "150");
     var obj = JsonObject.Parse(json);
     AboutMVListView.ItemsSource = Class.data.DataContractJsonDeSerialize<List<AboutMVdata>>(obj.GetNamedArray("data")[0].GetArray().ToString());
 }
Esempio n. 18
0
 private static async Task<List<string>> GetSingerPics(int singerid)
 {
     try
     {
         var httpclient = new Windows.Web.Http.HttpClient();
         TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
         var time = Convert.ToInt64(ts.TotalMilliseconds).ToString();
         var key = Class.MD5.GetMd5String("1005Ilwieks28dk2k092lksi2UIkp8150" + time);
         var postobj = new JsonObject();
         var array = new JsonArray();
         var videodata = new JsonObject();
         videodata.Add("author_name", JsonValue.CreateStringValue(""));
         videodata.Add("author_id", JsonValue.CreateNumberValue(singerid));
         array.Add(videodata);
         postobj.Add("data", array);
         postobj.Add("appid", JsonValue.CreateStringValue("1005"));
         postobj.Add("mid", JsonValue.CreateStringValue(""));
         postobj.Add("type", JsonValue.CreateNumberValue(5));
         postobj.Add("clienttime", JsonValue.CreateStringValue("1469035332000"));
         postobj.Add("key", JsonValue.CreateStringValue("27b498a7d890373fadb673baa1dabf7e"));
         postobj.Add("clientver", JsonValue.CreateStringValue("8150"));
         var postdata = new Windows.Web.Http.HttpStringContent(postobj.ToString());
         var result = await httpclient.PostAsync(new Uri("http://kmr.service.kugou.com/v1/author_image/author"), postdata);
         var json = await result.Content.ReadAsStringAsync();
         var obj=JObject.Parse(json);
         var piclist = new List<string>();
         for (int i = 0; i < obj["data"][0][0]["imgs"]["5"].Count(); i++)
         {
             piclist.Add(obj["data"][0][0]["imgs"]["5"][i]["filename"].ToString());
         }
         for (int i = 0; i < piclist.Count; i++)
         {
             var head = "http://singerimg.kugou.com/uploadpic/mobilehead/{size}/";
             for (int j = 0; j < 8; j++)
             {
                 head = head + (piclist[i])[j].ToString();
             }
             piclist[i] = head + "/" + piclist[i];
         }
         return piclist;
     }
     catch (Exception)
     {
         return null;
     }
 }
 public void CompressedWebContent_Constructor_ConstructsOkWithContentAndDeflateEncoding()
 {
     var innerContent         = new Windows.Web.Http.HttpStringContent("Test");
     var CompressedWebContent = new CompressedWebContent(innerContent, "deflate");
 }