private static async Task DownloadToCacheFileAsync(Uri uri, string fileName, Action<int> progress) { try { using (var client = new Windows.Web.Http.HttpClient()) { var requestAsync = client.GetAsync(uri); requestAsync.Progress += (i, p) => { if (null != progress) { if (p.TotalBytesToReceive != 0 && p.TotalBytesToReceive != null) { progress((int)((p.BytesReceived * 100) / p.TotalBytesToReceive)); } } }; using (var message = await requestAsync) { using (var fileStream = await CreateTempFileStreamAsync(fileName)) { using (var responseStream = await message.Content.ReadAsInputStreamAsync()) { await responseStream.AsStreamForRead().CopyToAsync(fileStream); } } } } } catch { await DeleteTempFileAsync(fileName); throw; } }
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()); }
//jos valittu thumbnail sisältää albumin public async Task GetAlbumInfo() { if (Boolean.Parse(lista[5])) { try { Windows.Web.Http.HttpClient hc = new Windows.Web.Http.HttpClient(); hc.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Authorization", "9adfc8a3fd65c2b"); var data = await hc.GetStringAsync(new Uri(url + lista[4].ToString())); System.Diagnostics.Debug.WriteLine("ALBUMIN DATAN LATAAMINEN ONNISTUI" + data); JObject json = JObject.Parse(data); for (int i = 0; i < json["data"]["images"].Count(); i++) { var item = new AlbumModel(); if (Boolean.Parse((string)json["data"]["images"][i]["animated"])) { item = new AlbumModel { title = (string)json["data"]["title"], description = (string)json["data"]["images"][i]["description"], id = (string)json["data"]["images"][i]["id"], mp4 = (string)json["data"]["images"][i]["mp4"] }; } else { item = new AlbumModel { link = (string)json["data"]["images"][i]["link"], title = (string)json["data"]["title"], id = (string)json["data"]["images"][i]["id"], description = (string)json["data"]["images"][i]["description"] }; } album.Add(item); } } catch (Exception e) { ShowMessage("Virhe albumi datan lataamisessa"); } } }
public static async void getdata() { //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b"); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } CommunicationScreen.Message = httpResponseBody; string[] trimresponse = httpResponseBody.Split('"'); long timestamp = Convert.ToInt64(trimresponse[1]); DateTime newdatetime = new DateTime(timestamp); TimeSpan correction = new TimeSpan(14, 30, 00); newdatetime.Subtract(correction); CommunicationScreen.Message += "\r\n\r\n" + string.Format("{0:hh:mm:ss tt}", newdatetime - correction); MainPage.newdatetime = newdatetime - correction; }
public static async Task GetReservationsAsync(CancellationToken token, ObservableCollection<Reservation> reservationList, string searchTerm = "", int locationId = 0, int profileId = 0, int page = 0, int itemsPerPage = 0) { var reservationResult = new ReservationResult(); using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = StorageService.LoadSetting("ApiKey"); var apiUrl = StorageService.LoadSetting("ApiUrl"); var profileToken = StorageService.LoadSetting("ProfileToken"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); httpClient.DefaultRequestHeaders.Add("profileToken", profileToken); try { //var criteria = new ReservationListCriteria { // ItemsPerPage = itemsPerPage, // LocationId = locationId, // MeetingTypeIds = new List<int>() { 2 }, // Page = page, // ProfileId = profileId, // SearchTerm = searchTerm, // StartDate = DateTime.Now, // StatusIds = new List<int>() { 2 } //}; var url = apiUrl + "/api/reservation/profile"; //if (locationId > 0) { //} //if (profileId > 0) { // url = url + "/profile"; //} //url = url + "?" + JsonConvert.SerializeObject(criteria); using (var httpResponse = await httpClient.GetAsync(new Uri(url)).AsTask(token)) { string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); reservationResult = JsonConvert.DeserializeObject<ReservationResult>(json); } } catch (Exception) { } } foreach (var reservation in reservationResult.Results) { reservationList.Add(reservation); } }
// code from //https://msdn.microsoft.com/en-us/library/windows/apps/mt187345.aspx async void getUser(int searchQuery) { //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://178.62.9.141:5000/datathon/customer/" + searchQuery); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } // custom tbkJsonRes.Text = httpResponseBody; }
protected async void UpdateIfUriIsInCache(Uri uri, TextBlock cacheStatusTextBlock) { var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.OnlyFromCache; var httpClient = new Windows.Web.Http.HttpClient(filter); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri); try { await httpClient.SendRequestAsync(request); cacheStatusTextBlock.Text = "Yes"; cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Green); } catch { cacheStatusTextBlock.Text = "No"; cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red); } }
public static async Task<string> GetUrltoHtml(string url) { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://www.contoso.com"); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } return httpResponseBody; }
async Task<bool> TryConnect() { bool result = false; var client = new Windows.Web.Http.HttpClient(); client.DefaultRequestHeaders.Add("device-id", deviceId.ToString()); client.DefaultRequestHeaders.Add("device-message", "Hello from RPi2"); var response = client.GetAsync(new Uri("http://egholservice.azurewebsites.net/api/DeviceConnect"), Windows.Web.Http.HttpCompletionOption.ResponseContentRead); response.AsTask().Wait(); var responseResult = response.GetResults(); if (responseResult.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { result = true; var received = await responseResult.Content.ReadAsStringAsync(); Debug.WriteLine("Recieved - " + received); } else { Debug.WriteLine("TryConnect Failed - " + responseResult.StatusCode); } return result; }
async private void InitializeAdaptiveMediaSource(System.Uri uri, MediaElement m) { httpClient = new Windows.Web.Http.HttpClient(); httpClient.DefaultRequestHeaders.TryAppendWithoutValidation("X-CustomHeader", "This is a custom header"); AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient); if (result.Status == AdaptiveMediaSourceCreationStatus.Success) { ams = result.MediaSource; m.SetMediaStreamSource(ams); //Register for download requested event ams.DownloadRequested += DownloadRequested; //Register for download success and failure events ams.DownloadCompleted += DownloadCompleted; ams.DownloadFailed += DownloadFailed; } else { rootPage.NotifyUser("Error creating the AdaptiveMediaSource\n\t" + result.Status, NotifyType.ErrorMessage); } }
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 ""; } }
private static async Task<CheckInKnowledgeTagResult> GetCheckInKnowledgeTagDataAsync(CancellationToken token, int channelId = 0, int locationId = 0, int eventId = 0, string searchTerm = "", int page = 1, int itemsPerPage = 10) { var tagResults = new CheckInKnowledgeTagResult(); using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = Common.StorageService.LoadSetting("ApiKey"); var apiUrl = Common.StorageService.LoadSetting("ApiUrl"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); try { var criteria = new TagKnowledgeCriteria { ChannelId = channelId, EventId = eventId, ItemsPerPage = itemsPerPage, LocationId = locationId, Page = page, SearchTerm = searchTerm }; var url = apiUrl + "/api/checkin/knowledge?" + JsonConvert.SerializeObject(criteria); var httpResponse = await httpClient.GetAsync(new Uri(url)).AsTask(token); string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); tagResults = JsonConvert.DeserializeObject<CheckInKnowledgeTagResult>(json); } catch (Exception e) { } } return tagResults; }
private static async Task<List<LocationText>> GetLocationTextDataAsync(CancellationToken token, int locationId, string languageCode = "en") { var locationTexts = new List<LocationText>(); using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = Common.StorageService.LoadSetting("ApiKey"); var apiUrl = Common.StorageService.LoadSetting("ApiUrl"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); try { var url = apiUrl + "/api/locations/text/" + locationId; var httpResponse = await httpClient.GetAsync(new Uri(url)).AsTask(token); string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); locationTexts = JsonConvert.DeserializeObject<List<LocationText>>(json); } catch (Exception e) { } } return locationTexts; }
private static async Task<ObservableCollection<Event>> GetEventsDataAsync(DateTime date, int locationId = 0, string searchTerm = "", double latitude = 0, double longitude = 0, int radius = 0, string workingOn = "", int page = 0, int itemsPerPage = 0) { var events = new ObservableCollection<Event>(); using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = Common.StorageService.LoadSetting("ApiKey"); var apiUrl = Common.StorageService.LoadSetting("ApiUrl"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); httpClient.DefaultRequestHeaders.Add("token", apiKey); try { var criteria = new EventListCriteria { SearchTerm = searchTerm, Latitude = latitude, Longitude = longitude, Radius = radius, Page = page, ItemsPerPage = itemsPerPage }; var url = apiUrl + "/api/event/calendar"; if (locationId > 0) { url = url + "/location/" + locationId; } url = url + "/" + date.Year + "/" + date.Month + "/" + date.Day + "?" + JsonConvert.SerializeObject(criteria); var httpResponse = await httpClient.GetAsync(new Uri(url)); string json = await httpResponse.Content.ReadAsStringAsync(); json = json.Replace("<br>", Environment.NewLine); events = JsonConvert.DeserializeObject<ObservableCollection<Event>>(json); } catch (Exception e) { } } return events; }
/// <summary> /// This method set the poster source for the MediaElement /// </summary> private async System.Threading.Tasks.Task<bool> SetPosterUrl(string PosterUrl) { if (IsPicture(PosterUrl)) { if (IsLocalFile(PosterUrl)) { try { Windows.Storage.StorageFile file = await GetFileFromLocalPathUrl(PosterUrl); if (file != null) { using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { if (fileStream != null) { Windows.UI.Xaml.Media.Imaging.BitmapImage b = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); if (b != null) { b.SetSource(fileStream); SetPictureSource(b); SetPictureElementSize(); return true; } } } } else LogMessage("Failed to load poster: " + PosterUrl); } catch (Exception e) { LogMessage("Exception while loading poster: " + PosterUrl + " - " + e.Message); } } else { try { // Load the bitmap image over http Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Storage.Streams.InMemoryRandomAccessStream ras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); using (var stream = await httpClient.GetInputStreamAsync(new Uri(PosterUrl))) { if (stream != null) { await stream.AsStreamForRead().CopyToAsync(ras.AsStreamForWrite()); ras.Seek(0); var b = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); if (b != null) { await b.SetSourceAsync(ras); SetPictureSource(b); SetPictureElementSize(); return true; } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: " + e.Message); } } } return false; }
/// <summary> /// Downloads a file from the specified address and returns the file. /// </summary> /// <param name="fileUri">The URI of the file.</param> /// <param name="folder">The folder to save the file to.</param> /// <param name="fileName">The file name to save the file as.</param> /// <param name="option"> /// A value that indicates what to do /// if the filename already exists in the current folder. /// </param> /// <remarks> /// If no file name is given - the method will try to find /// the suggested file name in the HTTP response /// based on the Content-Disposition HTTP header. /// </remarks> /// <returns></returns> public async Task <StorageFile> SaveAsyncWithBackgroundDownloaderAndProgress( Uri fileUri, IProgress <DownloadOperation> ProgressCallBack, StorageFolder folder = null, string fileName = null, NameCollisionOption option = NameCollisionOption.GenerateUniqueName) { Uri uri = new Uri("..."); try { Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(); var downloadTask = client.GetAsync(uri); downloadTask.Progress = (result, progress) => { Debug.WriteLine("===start==="); Debug.WriteLine(progress.BytesReceived); Debug.WriteLine(progress.TotalBytesToReceive); Debug.WriteLine("===end==="); }; var Downloadresult = await downloadTask; Debug.WriteLine("Done: " + Downloadresult.StatusCode.ToString()); } catch (Exception ex) { } if (folder == null) { folder = ApplicationData.Current.LocalFolder; } var file = await folder.CreateTempFileAsync(); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload( fileUri, file); var res = await download.StartAsync().AsTask(ProgressCallBack); if (string.IsNullOrEmpty(fileName)) { // Use temp file name by default fileName = file.Name; // Try to find a suggested file name in the http response headers // and rename the temp file before returning if the name is found. var info = res.GetResponseInformation(); if (info.Headers.ContainsKey("Content-Disposition")) { var cd = info.Headers["Content-Disposition"]; var regEx = new Regex("filename=\"(?<fileNameGroup>.+?)\""); var match = regEx.Match(cd); if (match.Success) { fileName = match.Groups["fileNameGroup"].Value; await file.RenameAsync(fileName, option); return(file); } } } await file.RenameAsync(fileName, option); return(file); }
private async Task <EmailStatus> GetEmails() { try { var mailstatus = new EmailStatus(); using (var httpRequest = new Windows.Web.Http.HttpRequestMessage()) { var client = new Windows.Web.Http.HttpClient(); //string mailListApi = $"https://www.googleapis.com/gmail/v1/users/{this.userId}/messages?q=is%3Aunread"; string mailListApi = $"https://www.googleapis.com/gmail/v1/users/me/messages?q=in%3Ainbox%20is%3Aunread%20-category%3A%7BCATEGORY_PERSONAL%7D"; httpRequest.Method = Windows.Web.Http.HttpMethod.Get; httpRequest.RequestUri = new Uri(mailListApi); httpRequest.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", this.accessToken); var response = await client.SendRequestAsync(httpRequest); if (response.IsSuccessStatusCode) { var jsonData = await response.Content.ReadAsStringAsync(); dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonData); var emailIds = jsonObject.messages; var counter = 0; foreach (dynamic emailId in emailIds) { if (counter > 10) { break; } counter++; string id = emailId.id; using (var innerHttpRequest = new Windows.Web.Http.HttpRequestMessage()) { var innerClient = new Windows.Web.Http.HttpClient(); //string mailApi = $"https://www.googleapis.com/gmail/v1/users/{this.userId}/messages/{id}"; string mailApi = $"https://www.googleapis.com/gmail/v1/users/me/messages/{id}"; innerHttpRequest.Method = Windows.Web.Http.HttpMethod.Get; innerHttpRequest.RequestUri = new Uri(mailApi); innerHttpRequest.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", this.accessToken); var innerResponse = await innerClient.SendRequestAsync(innerHttpRequest); if (innerResponse.IsSuccessStatusCode) { dynamic mailObject = Newtonsoft.Json.JsonConvert.DeserializeObject(innerResponse.Content.ToString()); dynamic payload = mailObject.payload; dynamic headers = payload.headers; var mailMessage = new EmailMessage(); mailMessage.Snippet = WebUtility.HtmlDecode(mailObject.snippet.Value.ToString()); foreach (dynamic header in headers) { if (header.name == "From") { var rawFrom = header.value.ToString(); mailMessage.From = this.CleanFromField(rawFrom); } if (header.name == "Subject") { mailMessage.Subject = header.value; } if (header.name == "Date") { try { mailMessage.TimeStamp = DateTime.Parse(header.value.ToString()); } catch (Exception) { } } } mailstatus.EmailMessages.Add(mailMessage); } } } } else { var errorRaw = await response.Content.ReadAsStringAsync(); dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(errorRaw); dynamic error = jsonObject.error; dynamic errors = error.errors; dynamic firstItem = errors[0]; dynamic reasonObject = firstItem.reason; string reason = reasonObject.Value; if (reason == "authError") { throw new Exception(); } } return(mailstatus); } } catch (Exception e) { Console.WriteLine(e); this.FailedToAuthenticate?.Invoke(this, null); throw; } }
private async Task<string> GetTwitterRequestTokenAsync() { // // Acquiring a request token // try { string TwitterUrl = "https://api.twitter.com/oauth/request_token"; string nonce = GetNonce(); string timeStamp = GetTimeStamp(); string SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString("http://MyW8appTwitterCallback.net"); SigBaseStringParams += "&" + "oauth_consumer_key=" + "ooWEcrlhooUKVOxSgsVNDJ1RK"; // CONSUMER KEY SigBaseStringParams += "&" + "oauth_nonce=" + nonce; SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1"; SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp; SigBaseStringParams += "&" + "oauth_version=1.0"; string SigBaseString = "GET&"; SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams); string Signature = GetSignature(SigBaseString, "BtLpq9ZlFzXrFklC2f1CXqy8EsSzgRRVPZrKVh0imI2TOrZAan"); // TWITTER SECRET CONSUMER KEY TwitterUrl += "?" + SigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(Signature); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); string GetResponse = await httpClient.GetStringAsync(new Uri(TwitterUrl)); string request_token = null; string oauth_token_secret = null; string[] keyValPairs = GetResponse.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_token_secret": oauth_token_secret = splits[1]; break; } } return request_token; } catch (Exception Error) { new MessageDialog("Erreur lors de la recuperation du profil Twitter").ShowAsync(); return null; } }
public static async Task SendGameConfigToServer(AppDataContext appDataContext) { GameDescription gameDescription = appDataContext.GetGameConfig().gameDescription; JsonObject json = WebService.ToJson(gameDescription, appDataContext.DeckRating.Value); string parameter = json.Stringify(); var fullUrl = new System.Text.StringBuilder(); fullUrl.Append(WebService.webUrl); fullUrl.Append("?action=RECORD&values="); fullUrl.Append(parameter.Replace(" ", "%20")); try { using (var client = new Windows.Web.Http.HttpClient()) using (var request = new Windows.Web.Http.HttpRequestMessage()) { request.RequestUri = new System.Uri(fullUrl.ToString()); using (Windows.Web.Http.HttpResponseMessage responseMessage = await client.SendRequestAsync(request).AsTask()) { if (responseMessage.IsSuccessStatusCode) { string strResult = await responseMessage.Content.ReadAsStringAsync().AsTask(); System.Diagnostics.Debug.WriteLine("RECORD Reponse from server:"); System.Diagnostics.Debug.WriteLine(strResult); } } } } catch (System.Exception) { } }
private static async Task<LocationResult> GetLocationsDataAsync(CancellationToken token, string searchTerm = "", double latitude = 0, double longitude = 0, int radius = 0, string workingOn = "", int page = 0, int itemsPerPage = 0) { var locationResult = new LocationResult(); using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = StorageService.LoadSetting("ApiKey"); var apiUrl = StorageService.LoadSetting("ApiUrl"); var channelId = int.Parse(StorageService.LoadSetting("ChannelId")); var countryId = int.Parse(StorageService.LoadSetting("CountryId")); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); try { var criteria = new LocationListCriteria { ChannelId = channelId, CountryId = countryId, ItemsPerPage = itemsPerPage, Latitude = latitude, Longitude = longitude, Page = page, Radius = radius, SearchTerm = searchTerm, WorkingOn = workingOn }; var url = apiUrl + "/api/locations/workspace?" + JsonConvert.SerializeObject(criteria); using (var httpResponse = await httpClient.GetAsync(new Uri(url)).AsTask(token)) { string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); if (string.IsNullOrEmpty(searchTerm)) { await FileHelper.SaveStringToLocalFile("locations.json", json); } locationResult = JsonConvert.DeserializeObject<LocationResult>(json); } } catch (Exception) { } } return locationResult; }
private async void ShareImageHandler(DataTransferManager sender, DataRequestedEventArgs e) { DataRequest request = e.Request; request.Data.Properties.Title = "Share Picture"; request.Data.Properties.Description = "Share picture more friend."; Uri uri = new Uri(item.urls.full); // Plain text request.Data.SetText("Unplash-" + rootObject.user.name); // Link request.Data.SetWebLink(uri); // HTML request.Data.SetHtmlFormat("<b>Bold Text</b>"); IRandomAccessStream stream; string filename = "shareimgCol.jpg"; using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient()) { try { Windows.Web.Http.HttpResponseMessage response = await client.GetAsync(uri); if (response != null && response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (stream = await imageFile.OpenAsync(FileAccessMode.ReadWrite)) { await response.Content.WriteToStreamAsync(stream); } } } catch { } RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(await ApplicationData.Current.LocalFolder.GetFileAsync(filename)); request.Data.SetBitmap(imageStreamRef); DataRequestDeferral deferral = request.GetDeferral(); // Make sure we always call Complete on the deferral. try { StorageFile thumbnail = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(thumbnail); StorageFile imageshare = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); // Bitmaps request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(imageshare)); } finally { deferral.Complete(); } } }
public DataServicecs(HttpClient client) { _client = client; }
private async void queryWeather(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { setWeatherText(); //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("https://www.sojson.com/open/api/weather/xml.shtml?city=" + Weather.Text); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); Debug.WriteLine(httpResponseBody); var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(httpResponseBody); XmlNodeList nodelist = xmlDoc.GetElementsByTagName("resp"); foreach (XmlNode node in nodelist) { updateTime.Text += node["updatetime"].InnerText; cityName.Text += node["city"].InnerText; template.Text += node["wendu"].InnerText + "℃"; wet.Text += node["shidu"].InnerText; sunrise.Text += node["sunrise_1"].InnerText; sunset.Text += node["sunset_1"].InnerText; windDirection.Text += node["fengxiang"].InnerText; } WeatherDetail.Visibility = Visibility.Visible; } catch (Exception ex) { await new MessageDialog("该城市不存在!请重新输入").ShowAsync(); WeatherDetail.Visibility = Visibility.Collapsed; httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } }
private async void tmp() { ApplicationData.Current.LocalSettings.Values["login"] = false; Uri urilogin = new Uri("http://222.30.32.10"); Windows.Web.Http.HttpClient conn = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpResponseMessage res = await conn.GetAsync(urilogin); Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); Windows.Web.Http.HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(urilogin); Windows.Web.Http.HttpCookie cookies = cookieCollection[0]; string cookie = cookies.ToString(); }
private async Task ClassifyAllFiles() { Debug.WriteLine("-- GETTING FILES"); StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFolder dataFolder = await appInstalledFolder.GetFolderAsync(GlobalData.dataFolder); IReadOnlyList <StorageFile> fileList = await dataFolder.GetFilesAsync(); var result = new ObservableCollection <BitmapImage>(); Speech.Speak("Processing of images for Invasive Ductal Carcinoma initiating"); Debug.WriteLine(" "); int received = 0; int counter = 0; int identified = 0; int incorrect = 0; int unsure = 0; int tns = 0; int fps = 0; int fns = 0; foreach (StorageFile file in fileList) { Debug.WriteLine(file.Name); IBuffer buffer = await FileIO.ReadBufferAsync(file); byte[] bytes = buffer.ToArray(); Stream streamer = new MemoryStream(bytes); Windows.Web.Http.HttpStreamContent streamContent = new Windows.Web.Http.HttpStreamContent(streamer.AsInputStream()); var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); myFilter.AllowUI = false; var client = new Windows.Web.Http.HttpClient(myFilter); Windows.Web.Http.HttpResponseMessage results = await client.PostAsync(new Uri(GlobalData.protocol + GlobalData.ip + ":" + GlobalData.port + GlobalData.endpointIDC), streamContent); string stringReadResult = await results.Content.ReadAsStringAsync(); Debug.WriteLine(stringReadResult); JToken token = JObject.Parse(stringReadResult); received = (int)token.SelectToken("Results"); double confidence = (double)token.SelectToken("Confidence"); string Response = (string)token.SelectToken("ResponseMessage"); if (received != 0) { if (file.Name.Contains("class1")) { if (confidence >= GlobalData.threshold) { Debug.WriteLine("CORRECT: IDC correctly detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); Debug.WriteLine(" "); identified = identified + 1; } else { Debug.WriteLine("UNSURE: IDC detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); unsure = unsure + 1; } } else { if (confidence >= GlobalData.threshold) { Debug.WriteLine("FALSE POSITIVE: IDC incorrectly detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); fps = fps + 1; incorrect = incorrect + 1; } else { Debug.WriteLine("UNSURE: IDC detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); unsure = unsure + 1; } } Speech.Speak("Processed image " + (counter + 1)); } else { if (file.Name.Contains("class0")) { Debug.WriteLine("CORRECT: IDC correctly not detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); tns = tns + 1; } else { if (confidence >= GlobalData.threshold) { Debug.WriteLine("FALSE NEGATIVE: IDC incorrectly not detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); fns = fns + 1; incorrect = incorrect + 1; } else { Debug.WriteLine("UNSURE: IDC not detected in image " + (counter + 1) + " " + file.Name + " with " + confidence + " confidence."); unsure = unsure + 1; } } Speech.Speak("Processed image " + (counter + 1)); Debug.WriteLine(" "); } counter++; if (counter == (GlobalData.expectedCount * 2)) { double actualIdentified = (double)identified; double accuracy = (((double)tns + actualIdentified) / (actualIdentified + (double)fps)) / ((double)counter - unsure); double precision = actualIdentified / (actualIdentified + (double)fps); double recall = actualIdentified / (actualIdentified + (double)fns); double fscore = 2 * ((double)precision * (double)recall / ((double)precision + (double)recall)); Speech.Speak(identified + " true positives, " + fps + " false positives, " + fns + " false negatives, " + unsure + " unsure, " + tns + " true negatives, " + incorrect + " incorrect examples classified, " + Math.Round(accuracy, 2) + " accuracy, " + Math.Round(precision, 2) + " precision, " + Math.Round(recall, 2) + " recall, " + Math.Round(fscore, 2) + " fscore"); Debug.WriteLine(" "); Debug.WriteLine("- " + identified + " true positives, " + fps + " false positives, " + fns + " false negatives, " + tns + " true negatives"); Debug.WriteLine("- " + unsure + " unsure"); Debug.WriteLine("- " + incorrect + " incorrect examples classified"); Debug.WriteLine("- " + Math.Round(accuracy, 2) + " accuracy"); Debug.WriteLine("- " + Math.Round(precision, 2) + " precision"); Debug.WriteLine("- " + Math.Round(recall, 2) + " recall"); Debug.WriteLine("- " + Math.Round(fscore, 2) + " fscore"); } System.Threading.Thread.Sleep(1000); } }
/// <summary> /// DownloadManifestAsync /// Downloads a manifest asynchronously. /// </summary> /// <param name="forceNewDownload">Specifies whether to force a new download and avoid cached results.</param> /// <returns>A byte array</returns> public async Task<byte[]> DownloadManifestAsync(bool forceNewDownload) { Uri manifestUri = this.ManifestUri; System.Diagnostics.Debug.WriteLine("Download Manifest: " + manifestUri.ToString() + " start at " + string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now)); var client = new Windows.Web.Http.HttpClient(); try { if (forceNewDownload) { string modifier = manifestUri.AbsoluteUri.Contains("?") ? "&" : "?"; string newUriString = string.Concat(manifestUri.AbsoluteUri, modifier, "ignore=", Guid.NewGuid()); manifestUri = new Uri(newUriString); } Windows.Web.Http.HttpResponseMessage response = await client.GetAsync(manifestUri, Windows.Web.Http.HttpCompletionOption.ResponseContentRead); response.EnsureSuccessStatusCode(); /* foreach ( var v in response.Content.Headers) { System.Diagnostics.Debug.WriteLine("Content Header key: " + v.Key + " value: " + v.Value.ToString()); } foreach (var v in response.Headers) { System.Diagnostics.Debug.WriteLine("Header key: " + v.Key + " value: " + v.Value.ToString()); } */ var buffer = await response.Content.ReadAsBufferAsync(); if (buffer != null) { if ((response.Headers.Location != null) && (response.Headers.Location != manifestUri)) { this.RedirectUri = response.Headers.Location; this.RedirectBaseUrl = GetBaseUri(RedirectUri.AbsoluteUri); } else { this.RedirectBaseUrl = string.Empty; this.RedirectUri = null; } this.BaseUrl = GetBaseUri(manifestUri.AbsoluteUri); uint val = buffer.Length; System.Diagnostics.Debug.WriteLine("Download " + val.ToString() + " Bytes Manifest: " + manifestUri.ToString() + " done at " + string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now)); return buffer.ToArray(); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: " + e.Message); } return null; }
private async void GetNews() { //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } String api = "http://api.avatardata.cn/TouTiao/Query"; String appkey = "2d408009841f439b864c3c00a3c0bdbe"; NewsBlock.Text = "正在加载新闻"; StringBuilder uriBuilder = new StringBuilder(); uriBuilder.Append(api).Append("?key=").Append(appkey).Append("&type=top"); //var i = new Windows.UI.Popups.MessageDialog(uriBuilder.ToString()).ShowAsync(); Uri requestUri = new Uri(uriBuilder.ToString()); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); //NewsBlock.Text = httpResponseBody; //用string初始化JsonObject JsonObject jsonObject = JsonObject.Parse(httpResponseBody); // JsonArray arr = jsonObject.GetNamedArray("result").GetArray(); JsonObject obj = jsonObject.GetNamedObject("result"); JsonArray arr = obj.GetNamedArray("data").GetArray(); StringBuilder s = new StringBuilder(); s.Append(arr[0].GetObject().GetNamedValue("title").GetString()); s.Append("。\n新闻来源于"); s.Append(arr[0].GetObject().GetNamedValue("url").GetString()); NewsBlock.Text = s.ToString(); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } }
public static async Task GetLocationRecommendationsAsync(CancellationToken token, ObservableCollection<Location> locationList, double latitude = 0, double longitude = 0, int radius = 0, string workingOn = "", int page = 0, int itemsPerPage = 0) { var locationResult = new LocationResult(); using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = StorageService.LoadSetting("ApiKey"); var apiUrl = StorageService.LoadSetting("ApiUrl"); var channelId = int.Parse(StorageService.LoadSetting("ChannelId")); var countryId = int.Parse(StorageService.LoadSetting("CountryId")); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); try { var criteria = new LocationListCriteria { ItemsPerPage = itemsPerPage, Latitude = latitude, Longitude = longitude, Page = page, Radius = radius, WorkingOn = workingOn }; var url = apiUrl + "/api/locations/recommendation?" + JsonConvert.SerializeObject(criteria); using (var httpResponse = await httpClient.GetAsync(new Uri(url)).AsTask(token)) { string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); locationResult = JsonConvert.DeserializeObject<LocationResult>(json); } } catch (Exception) { } } foreach (var location in locationResult.Results) { locationList.Add(location); } }
public async void StoreAll() { ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile(); if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess) { busyindicator.IsActive = true; //await LoadInAppPurchaseProxyFileAsync(); try { var client = new Windows.Web.Http.HttpClient(); string urlPath = "http://mhndt.com/newsstand/renungan-harian/callback/allWinItems"; var values = new List<KeyValuePair<string, string>> { //new KeyValuePair<string, string>("hal", "1"), //new KeyValuePair<string, string>("limit","300") }; var response = await client.PostAsync(new Uri(urlPath), new Windows.Web.Http.HttpFormUrlEncodedContent(values)); response.EnsureSuccessStatusCode(); if (!response.IsSuccessStatusCode) { RequestException(); } string jsonText = await response.Content.ReadAsStringAsync(); JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonData1 = jsonObject["data"].GetArray(); foreach (JsonValue groupValue in jsonData1) { JsonObject groupObject = groupValue.GetObject(); string bundleName = ""; string pathFile = ""; string nid = groupObject["sku"].GetString(); string title = groupObject["judul"].GetString(); string deskripsi = groupObject["deskripsi"].GetString(); string tanggal = groupObject["tgl"].GetString(); string tipe = groupObject["tipe"].GetString(); string namaTipe = groupObject["nama_tipe"].GetString(); string gratis = groupObject["gratis"].GetString(); string dataFile = groupObject["nfile"].GetString(); string harga = groupObject["hrg"].GetString(); var bundleObj = groupObject["bundle"]; BukuAudio file = new BukuAudio(); file.BundleName = new List<string>(); file.BundlePath = new List<string>(); if (bundleObj.ValueType == JsonValueType.Array) { JsonArray bundle = bundleObj.GetArray(); foreach (JsonValue groupValue1 in bundle) { JsonObject groupObject1 = groupValue1.GetObject(); bundleName = groupObject1["bundle_file"].GetString(); pathFile = groupObject1["path_file"].GetString(); file.BundleName.Add(bundleName); file.Tipe = tipe; if (file.Tipe == "0") { file.BundlePath.Add(pathFile + bundleName + ".pdf"); //file.BundlePath = pathFile + bundleName + ".pdf"; } else if (file.Tipe == "1") { file.BundlePath.Add(pathFile + bundleName); //file.BundlePath = pathFile + bundleName; } } } file.SKU = nid; file.Judul = title; file.Deskripsi = deskripsi; string[] formats = { "d MMMM yyyy" }; var dateTime = DateTime.ParseExact(tanggal, formats, new CultureInfo("id-ID"), DateTimeStyles.None); Int64 n = Int64.Parse(dateTime.ToString("yyyyMMdd")); file.Tanggal = n.ToString(); int tgl = Int32.Parse(file.Tanggal); //file.Tipe = tipe; file.NamaTipe = "Tipe: " + namaTipe; file.Gratis = gratis; file.File = "http://mhndt.com/newsstand/rh/item/" + dataFile; file.Cover = "http://mhndt.com/newsstand/rh/item/" + dataFile + ".jpg"; if (licenseInformation.ProductLicenses[file.SKU].IsActive) { file.Harga = "Purchased"; } else { if (file.Gratis == "1") { file.Harga = "Free"; } else { file.Harga = harga; } } if (bundleObj.ValueType == JsonValueType.Array && tgl >= 20150301 || file.Judul == "Renungan Harian Tahunan VII" || file.Judul == "Edisi Tahunan VI" || file.Judul == "RH Anak Volume 01 : Yesus Sahabatku") { datasource.Add(file); } } if (jsonData1.Count > 0) { itemGridView.ItemsSource = datasource; } else { MessageDialog messageDialog; messageDialog = new MessageDialog("Data kosong", "Buku atau Audio Tidak tersedia"); messageDialog.Commands.Add(new UICommand("Tutup", (command) => { this.Frame.Navigate(typeof(MainPage)); })); await messageDialog.ShowAsync(); } } catch (HttpRequestException ex) { RequestException(); busyindicator.IsActive = false; } } else { ConnectionException(); busyindicator.IsActive = false; } }
public static async Task<Location> GetLocationById(CancellationToken token, int locationId) { Location location = null; using (var httpClient = new Windows.Web.Http.HttpClient()) { var apiKey = StorageService.LoadSetting("ApiKey"); var apiUrl = StorageService.LoadSetting("ApiUrl"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); try { var url = apiUrl + "/api/locations/" + locationId; using (var httpResponse = await httpClient.GetAsync(new Uri(url)).AsTask(token)) { string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token); json = json.Replace("<br>", Environment.NewLine); location = JsonConvert.DeserializeObject<Location>(json); } } catch (Exception) { } } return location; }
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 static async Task<GameDescriptionAndRating> GetGameConfigFomServer(AppDataContext appDataContext) { JsonObject jsonParameter = ToJsonForGetExpansions(appDataContext); string parameter = jsonParameter.Stringify(); var fullUrl = new System.Text.StringBuilder(); fullUrl.Append(WebService.webUrl); fullUrl.Append("?action=GET&values="); fullUrl.Append(parameter.Replace(" ", "%20")); try { using (var client = new Windows.Web.Http.HttpClient()) using (var request = new Windows.Web.Http.HttpRequestMessage()) { request.RequestUri = new System.Uri(fullUrl.ToString()); using (Windows.Web.Http.HttpResponseMessage responseMessage = await client.SendRequestAsync(request).AsTask()) { if (responseMessage.IsSuccessStatusCode) { string strResult = await responseMessage.Content.ReadAsStringAsync().AsTask(); GameDescriptionAndRating description = WebService.GetGameDescriptionFromJson(strResult); System.Diagnostics.Debug.WriteLine("Get Response from server:"); System.Diagnostics.Debug.WriteLine(strResult); return description; } } } } catch (System.Exception) { } return null; }
private async Task BindMediaSourceAsync(MediaBinder sender, MediaBindingEventArgs args) { var deferal = args.GetDeferral(); // Get the track data var track = JsonConvert.DeserializeObject <BaseTrack>(args.MediaBinder.Token); try { // Only run if the track exists if (track != null) { switch (track.ServiceType) { case ServiceTypes.YouTube: var youTubeAudioUrl = await track.GetAudioStreamAsync(_youTubeClient); if (!string.IsNullOrEmpty(youTubeAudioUrl)) { if (track.IsLive) { var source = await AdaptiveMediaSource.CreateFromUriAsync(new Uri(youTubeAudioUrl)); if (source.Status == AdaptiveMediaSourceCreationStatus.Success) { args.SetAdaptiveMediaSource(source.MediaSource); } } else { args.SetUri(new Uri(youTubeAudioUrl)); } } break; case ServiceTypes.SoundCloud: case ServiceTypes.SoundCloudV2: // Build the url for soundcloud var soundcloudStreamUrl = await track.GetAudioStreamAsync(_youTubeClient); // SoundCloud now requires auth feeds var scConnected = SoundByteService.Current.IsServiceConnected(ServiceTypes.SoundCloud); if (!scConnected) { throw new Exception("You must be logged into your SoundCloud account to play music from SoundCloud!"); } // Get scheme and token var scheme = SoundByteService.Current.Services.FirstOrDefault(x => x.Service == ServiceTypes.SoundCloud)?.AuthenticationScheme; var token = SoundByteService.Current.Services.FirstOrDefault(x => x.Service == ServiceTypes.SoundCloud)?.UserToken?.AccessToken; // Client with Auth var client = new Windows.Web.Http.HttpClient(); client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue(scheme, token); var stream = await HttpRandomAccessStream.CreateAsync(client, new Uri(soundcloudStreamUrl)); args.SetStream(stream, stream.ContentType); break; case ServiceTypes.Local: var fileToken = track.CustomProperties["file_token"].ToString(); var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken); args.SetStorageFile(file); break; case ServiceTypes.ITunesPodcast: args.SetUri(new Uri(track.AudioStreamUrl)); break; default: // Get the audio stream url for this track var audioStreamUrl = await track.GetAudioStreamAsync(_youTubeClient); if (!string.IsNullOrEmpty(audioStreamUrl)) { // Set generic stream url. args.SetUri(new Uri(audioStreamUrl)); } break; } } } catch (Exception e) { // So we know an error has occured _telemetryService.TrackEvent("Media Item Load Fail", new Dictionary <string, string> { { "Message", e.Message }, { "Service Type", track.ServiceType.ToString() }, { "Item ID", track.TrackId } }); if (!(DeviceHelper.IsBackground || DeviceHelper.IsXbox)) { await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.NotificationManager?.Show("An error occurred while trying to play or preload the track '" + track?.Title + "' (" + track?.ServiceType + ").\n\nError message: " + e.Message, 6500); }); } } deferal.Complete(); }
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(); } }
private async Task<bool> GetMediaDataAsync(string path) { if (this._groups.Count != 0) return false; string jsonText = string.Empty; if (string.IsNullOrEmpty(path)) { // load the default data //If retrieving json from web failed then use embedded json data file. if (string.IsNullOrEmpty(jsonText)) { Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = "ms-appx:///DataModel/MediaData.json"; } } else { if (path.StartsWith("ms-appx://")) { Uri dataUri = new Uri(path); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = path; } else if (path.StartsWith("http://")) { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter); Uri httpUri = new Uri(MediaDataFile); jsonText = await http.GetStringAsync(httpUri); MediaDataPath = MediaDataFile; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } else { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; StorageFile file; file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path); if (file != null) { jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = MediaDataFile; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } } if (string.IsNullOrEmpty(jsonText)) return false; try { JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["Groups"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); MediaDataGroup group = new MediaDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString(), groupObject["Category"].GetString(), groupObject["ImagePath"].GetString(), groupObject["Description"].GetString()); foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); long timeValue = 0; group.Items.Add(new MediaItem(itemObject["UniqueId"].GetString(), itemObject["Comment"].GetString(), itemObject["Title"].GetString(), itemObject["ImagePath"].GetString(), itemObject["Description"].GetString(), itemObject["Content"].GetString(), itemObject["PosterContent"].GetString(), (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0), (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0), itemObject["PlayReadyUrl"].GetString(), itemObject["PlayReadyCustomData"].GetString(), itemObject["BackgroundAudio"].GetBoolean())); } this.Groups.Add(group); return true; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } return false; }
/// <summary> /// Called when the download of a DASH or HLS chunk is requested /// </summary> private async void AdaptiveMediaSource_DownloadRequested(Windows.Media.Streaming.Adaptive.AdaptiveMediaSource sender, Windows.Media.Streaming.Adaptive.AdaptiveMediaSourceDownloadRequestedEventArgs args) { // LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString()); var deferral = args.GetDeferral(); if (deferral != null) { args.Result.ResourceUri = args.ResourceUri; args.Result.ContentType = args.ResourceType.ToString(); var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache; using (var httpClient = new Windows.Web.Http.HttpClient(filter)) { try { Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, args.Result.ResourceUri); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request); // args.Result.ExtendedStatus = (uint)response.StatusCode; if (response.IsSuccessStatusCode) { //args.Result.ExtendedStatus = (uint)response.StatusCode; args.Result.InputStream = await response.Content.ReadAsInputStreamAsync(); } else LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " error: " + response.StatusCode.ToString()); } catch (Exception e) { LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " exception: " + e.Message); } // LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " done"); deferral.Complete(); } } }
static async Task<string> DownloadPageStringAsync(string url) { var client = new HttpClient(); var response = await client.GetAsync(new Uri(url)); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); }
public async Task <Boolean> getDataUser(String usernme, String pw) { Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } // Uri requestUri = new Uri("http://localhost:6796/RegistrovaniKorisniks/GetAccount?Username="******"&Password="******"https://vicinor.azurewebsites.net/RegistrovaniKorisniks/GetAccount?Username="******"&Password="******"http://localhost:6796/RegistrovaniKorisniks/GetAccount?Username=Masha&Password=sifraHaris"); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); RegistrovaniKorisnik korisnik = null; string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); string json = httpResponseBody; korisnik = JsonConvert.DeserializeObject <RegistrovaniKorisnik>(json); if (korisnik != null) { int a = korisnik.KorisnikId; usernameG = korisnik.Username; passwordG = korisnik.Password; regUserDaNe = true; regUser = korisnik; KORISNIK_ID = korisnik.KorisnikId; // samra ne diraj return(true); } else if (json == "") { regUserDaNe = false; usernameG = ""; passwordG = ""; return(false); } } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } return(true); /* * if(korisnik != null){ * int a = korisnik.KorisnikId; * usernameG = korisnik.Username; * passwordG = korisnik.Password; * KORISNIK_ID = korisnik.KorisnikId; * } * return false;*/ }
private async void queryIp(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { setIpText(); //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://ip-api.com/json/" + Ip.Text); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); //Debug.WriteLine(httpResponseBody); JsonObject info = JsonObject.Parse(httpResponseBody); //Debug.WriteLine(info); if (info["status"].GetString() == "success") { IpNum.Text += info["query"].GetString(); country.Text += info["country"].GetString(); regionName.Text += info["regionName"].GetString(); city.Text += info["city"].GetString(); Debug.WriteLine(info["lat"]); lat.Text += info["lat"].GetNumber().ToString(); lon.Text += info["lon"].GetNumber().ToString(); IpDetail.Visibility = Visibility.Visible; } else { await new MessageDialog(info["message"].GetString()).ShowAsync(); IpDetail.Visibility = Visibility.Collapsed; } } catch (Exception ex) { await new MessageDialog("出现错误!请重新输入").ShowAsync(); httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } }
private async Task GetSampleDataAsync() { if (this._groups.Count != 0) return; // Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json"); // StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); //string jsonText = await FileIO.ReadTextAsync(file); try { Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(); var jsonText = await client.GetStringAsync(new Uri("http://bits-oasis.org/2015/windows_json/")); JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["Groups"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString() //groupObject["Subtitle"].GetString(), // groupObject["ImagePath"].GetString(), // groupObject["Description"].GetString() ); int i = 0; foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(), itemObject["Title"].GetString(), itemObject["Subtitle"].GetString(), itemObject["ImagePath"].GetString(), // itemObject["Description"].GetString(), itemObject["Content"].GetString())); foreach (JsonValue subitemValue in itemObject["SubItems"].GetArray()) { JsonObject subitemObject = subitemValue.GetObject(); group.Items[i].SubItems.Add(new SampleDataSubItem(subitemObject["UniqueId"].GetString(), subitemObject["Title"].GetString(), subitemObject["Subtitle"].GetString(), subitemObject["ImagePath"].GetString(), // itemObject["Description"].GetString(), subitemObject["Content"].GetString())); } i++; } this.Groups.Add(group); } } catch { MessageDialog msgbox3 = new MessageDialog("Check Your Network Connection. Web Access is required to get data."); await msgbox3.ShowAsync(); } }
private async Task <bool> GetMediaDataAsync(string path) { if (this._groups.Count != 0) { return(false); } string jsonText = string.Empty; if (string.IsNullOrEmpty(path)) { // load the default data //If retrieving json from web failed then use embedded json data file. if (string.IsNullOrEmpty(jsonText)) { Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = "ms-appx:///DataModel/MediaData.json"; } } else { if (path.StartsWith("ms-appx://")) { Uri dataUri = new Uri(path); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = path; } else if (path.StartsWith("http://")) { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter); Uri httpUri = new Uri(MediaDataFile); jsonText = await http.GetStringAsync(httpUri); MediaDataPath = MediaDataFile; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } else { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; StorageFile file; file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path); if (file != null) { jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = MediaDataFile; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } } if (string.IsNullOrEmpty(jsonText)) { return(false); } try { JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["Groups"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); MediaDataGroup group = new MediaDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString(), groupObject["Category"].GetString(), groupObject["ImagePath"].GetString(), groupObject["Description"].GetString()); foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); long timeValue = 0; group.Items.Add(new MediaItem(itemObject["UniqueId"].GetString(), itemObject["Comment"].GetString(), itemObject["Title"].GetString(), itemObject["ImagePath"].GetString(), itemObject["Description"].GetString(), itemObject["Content"].GetString(), itemObject["PosterContent"].GetString(), (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0), (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0), itemObject["PlayReadyUrl"].GetString(), itemObject["PlayReadyCustomData"].GetString(), itemObject["BackgroundAudio"].GetBoolean())); } this.Groups.Add(group); return(true); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } return(false); }
private async void Button_Connecter(object sender, RoutedEventArgs e) { if (Email.Text != "" && Password.Password != "") { // recuperation des valeurs email et mdp email = Email.Text; password = Password.Password; //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://businesswallet.fr/Bmb/User_Connexion.php?email=" + email + "&password="******""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject <User>(httpResponseBody); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } if (!(user is null)) { App.globaluser = user; if (user.isparent == 0)// si un enfant se connecte { Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(MainPage), user); } else// si un parent se connecte { Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(MainParent), user); } } else { libelleErreur.Text = "Veuillez saisir le bon email et mot de passe : ce couple d'identifiant est inconnu"; } }
public virtual async System.Threading.Tasks.Task <IServiceResponse> PostAsyncWindowsWeb(Uri uri, byte[] audioBytes, apiArgs) { IServiceResponse response = new IServiceResponse(service); try { // Using HttpClient to grab chunked encoding (partial) responses. using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient()) { Log.WriteLine("before requestContent"); Log.WriteLine("after requestContent"); // rate must be specified but doesn't seem to need to be accurate. Windows.Web.Http.IHttpContent requestContent = null; if (Options.options.APIs.preferChunkedEncodedRequests) { // using chunked transfer requests Log.WriteLine("Using chunked encoding"); Windows.Storage.Streams.InMemoryRandomAccessStream contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); // TODO: obsolete to use DataWriter? use await Windows.Storage.FileIO.Write..(file); Windows.Storage.Streams.DataWriter dw = new Windows.Storage.Streams.DataWriter(contentStream); dw.WriteBytes(audioBytes); await dw.StoreAsync(); // GetInputStreamAt(0) forces chunked transfer (sort of undocumented behavior). requestContent = new Windows.Web.Http.HttpStreamContent(contentStream.GetInputStreamAt(0)); } else { requestContent = new Windows.Web.Http.HttpBufferContent(audioBytes.AsBuffer()); } requestContent.Headers.Add("Content-Type", "audio/l16; rate=" + sampleRate.ToString()); // must add header AFTER contents are initialized Log.WriteLine("Before Post: Elapsed milliseconds:" + stopWatch.ElapsedMilliseconds); response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds; using (Windows.Web.Http.HttpResponseMessage hrm = await httpClient.PostAsync(uri, requestContent)) { response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds - response.RequestElapsedMilliseconds; response.StatusCode = (int)hrm.StatusCode; Log.WriteLine("After Post: StatusCode:" + response.StatusCode + " Total milliseconds:" + stopWatch.ElapsedMilliseconds + " Request milliseconds:" + response.RequestElapsedMilliseconds); if (hrm.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { string responseContents = await hrm.Content.ReadAsStringAsync(); string[] responseJsons = responseContents.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string rj in responseJsons) { response.ResponseJson = rj; Newtonsoft.Json.Linq.JToken ResponseBodyToken = Newtonsoft.Json.Linq.JObject.Parse(response.ResponseJson); response.ResponseJsonFormatted = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseBodyToken, new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.Indented }); if (Options.options.debugLevel >= 4) { Log.WriteLine(response.ResponseJsonFormatted); } Newtonsoft.Json.Linq.JToken tokResult = ProcessResponse(ResponseBodyToken); if (tokResult == null || string.IsNullOrEmpty(tokResult.ToString())) { response.ResponseResult = Options.options.Services.APIs.SpeechToText.missingResponse; if (Options.options.debugLevel >= 3) { Log.WriteLine("ResponseResult:" + response.ResponseResult); } } else { response.ResponseResult = tokResult.ToString(); if (Options.options.debugLevel >= 3) { Log.WriteLine("ResponseResult:" + tokResult.Path + ": " + response.ResponseResult); } } } } else { response.ResponseResult = hrm.ReasonPhrase; Log.WriteLine("PostAsync Failed: StatusCode:" + hrm.ReasonPhrase + "(" + response.StatusCode.ToString() + ")"); } } } } catch (Exception ex) { Log.WriteLine("Exception:" + ex.Message); if (ex.InnerException != null) { Log.WriteLine("InnerException:" + ex.InnerException); } } return(response); }
async static Task <string> Download(Uri url) { var httpClient = new Windows.Web.Http.HttpClient(); return(await httpClient.GetStringAsync(url)); }
//</SnippetAMSDownloadRequested> private Task <IBuffer> CreateMyCustomManifest(Uri resourceUri) { httpClient = new Windows.Web.Http.HttpClient(); return(httpClient.GetBufferAsync(resourceUri).AsTask <IBuffer, Windows.Web.Http.HttpProgress>()); }
private async Task <bool> GetMediaDataAsync(string path) { //if (this._groups.Count != 0) // return false; string jsonText = string.Empty; if (string.IsNullOrEmpty(path)) { // load the default data //If retrieving json from web failed then use embedded json data file. if (string.IsNullOrEmpty(jsonText)) { Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = "ms-appx:///DataModel/MediaData.json"; } } else { if (path.StartsWith("ms-appx://")) { Uri dataUri = new Uri(path); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = path; } else if (path.StartsWith("https://")) { try { using (var client = new HttpClient()) { var response = await client.GetAsync(path); response.EnsureSuccessStatusCode(); jsonText = await response.Content.ReadAsStringAsync(); MediaDataPath = path; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } else if (path.StartsWith("http://")) { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter); Uri httpUri = new Uri(path); jsonText = await http.GetStringAsync(httpUri); MediaDataPath = path; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } else { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; StorageFile file; file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path); if (file != null) { jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = MediaDataFile; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } } if (string.IsNullOrEmpty(jsonText)) { return(false); } try { JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["Groups"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); MediaDataGroup group = new MediaDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString(), groupObject["Category"].GetString(), groupObject["ImagePath"].GetString(), groupObject["Description"].GetString()); foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); long timeValue = 0; if (!itemObject.ContainsKey("Title")) { var id = itemObject["UniqueId"].GetString().GetHashCode().ToString(); var videoPath = _localVideoReady.ContainsKey(id) ? ApplicationData.Current.LocalFolder.Path + "/" + _localVideoReady[id] : itemObject["Content"].GetString(); group.Items.Add(new MediaItem(id, "", "", "ms-appx:///Assets/SMOOTH.png", "", videoPath, "", 0, 0, "", "", "", false)); } else { var id = itemObject["UniqueId"].GetString().GetHashCode().ToString(); var videoPath = _localVideoReady.ContainsKey(id) ? ApplicationData.Current.LocalFolder.Path + "/" + _localVideoReady[id] : itemObject["Content"].GetString(); group.Items.Add(new MediaItem(id, itemObject["Comment"].GetString(), itemObject["Title"].GetString(), itemObject["ImagePath"].GetString(), itemObject["Description"].GetString(), videoPath, itemObject["PosterContent"].GetString(), (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0), (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0), (itemObject.ContainsKey("HttpHeaders") ? itemObject["HttpHeaders"].GetString() : ""), itemObject["PlayReadyUrl"].GetString(), itemObject["PlayReadyCustomData"].GetString(), itemObject["BackgroundAudio"].GetBoolean())); } } if (Groups.Any(g => g.UniqueId == group.UniqueId)) { var currentGroup = Groups.First(g => g.UniqueId == group.UniqueId); currentGroup.Items.Where(item => group.Items.All(i => i.UniqueId != item.UniqueId) || item.Content.Contains("http")).ToList() .ForEach(item => currentGroup.Items.Remove(item)); foreach (var item in group.Items) { if (currentGroup.Items.All(i => i.UniqueId != item.UniqueId)) { currentGroup.Items.Add(item); } } } else { Groups.Add(group); } foreach (var item in group.Items) { if (!_localVideoReady.ContainsKey(item.UniqueId) && !_toDownload.Exists(x => x.Id == item.UniqueId)) { _toDownload.Add(new Video { Id = item.UniqueId, Url = item.Content }); } } var itemReady = new List <Video>(); foreach (var item in _toDownload) { try { var fileName = string.Format(@"{0}.mp4", Guid.NewGuid()); // create the blank file in specified folder var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); // create the downloader instance and prepare for downloading the file var downloadOperation = new BackgroundDownloader().CreateDownload(new Uri(item.Url), file); // start the download operation asynchronously await downloadOperation.StartAsync(); _localVideoReady[item.Id] = fileName; itemReady.Add(item); await SaveVideos(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while Downloading: " + item.Url + " Exception: " + e.Message); } } itemReady.ForEach(x => _toDownload.Remove(x)); return(true); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } return(false); }
/// <summary> /// Takes a photo to a StorageFile and adds rotation metadata to it /// </summary> /// <returns></returns> private async Task TakePhotoAsync() { // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported; // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0; var stream = new InMemoryRandomAccessStream(); Debug.WriteLine("Taking photo..."); Speech.Speak("Thank you, authenticating you now."); await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); try { string datetime = DateTime.Now.ToString("yy-MM-dd") + "-" + DateTime.Now.ToString("hh-mm-ss") + ".jpg"; var file = await _captureFolder.CreateFileAsync(datetime, CreationCollisionOption.GenerateUniqueName); Debug.WriteLine("Photo taken! Saving to " + file.Path); var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation()); await ReencodeAndSavePhotoAsync(stream, file, photoOrientation); Debug.WriteLine("Photo saved!"); IStorageFile storageFile = await StorageFile.GetFileFromPathAsync(file.Path); IBuffer buffer = await FileIO.ReadBufferAsync(storageFile); byte[] bytes = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(buffer); Stream streamer = new MemoryStream(bytes); Windows.Web.Http.HttpStreamContent streamContent = new Windows.Web.Http.HttpStreamContent(streamer.AsInputStream()); var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); myFilter.AllowUI = false; var client = new Windows.Web.Http.HttpClient(myFilter); Windows.Web.Http.HttpResponseMessage result = await client.PostAsync(new Uri(GlobalData.protocol + GlobalData.ip + ":" + GlobalData.port + GlobalData.endpoint), streamContent); string stringReadResult = await result.Content.ReadAsStringAsync(); Debug.WriteLine(stringReadResult); JToken token = JObject.Parse(stringReadResult); int identified = (int)token.SelectToken("Results"); string Response = (string)token.SelectToken("ResponseMessage"); if (identified != 0) { Debug.WriteLine("Identified " + identified); this.Frame.Navigate(typeof(AppHome)); } else { Speech.Speak("Sorry we cannot authorise your request"); } } catch (Exception ex) { // File I/O errors are reported as exceptions Debug.WriteLine("Exception when taking a photo: " + ex.ToString()); } // Done taking a photo, so re-enable the button VideoButton.IsEnabled = true; VideoButton.Opacity = 1; }