public async Task <bool> SendMessage(string body) { var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); // webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/json;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); // Debug.WriteLine("Success/Error msg: {0}", nowait.StatusCode); return(nowait.IsSuccessStatusCode); }
public async Task <RestResponse> Execute(RestRequest request) { var requestUri = new UriBuilder(BaseUrl) { Path = request.Resource }; if (request.QueryParameters.Count > 0) { requestUri.Query = request.QueryParameters.AsQueryString(); } HttpRequestMessage message = new HttpRequestMessage(); if (UserAgent.Length > 0) { message.Headers.Add("User-Agent", UserAgent); } if (Authorization.Length > 0) { message.Headers.Add("Authorization", Authorization); } message.Headers.Add("Accept", "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml"); message.Headers.Add("Accept-Encoding", "gzip, deflate"); message.RequestUri = requestUri.Uri; message.Method = request.Method; if (request.Parameters.Count > 0) { message.Content = new HttpFormUrlEncodedContent(request.Parameters); } var response = await _client.SendRequestAsync(message); return(new RestResponse(response)); }
public async static Task <bool> SendMessage(string body) { // Namespace info. //var serviceNamespace = "sudhesh"; //var hubName = "test"; //var deviceName = "tisensortag"; //var sharedAccessPolicyName = "all"; //var sharedAccessKey = "ZcfdxuLADoYv3zQycbpddoelgBvogPxnqM7/dfMdU2k="; var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); return(nowait.IsSuccessStatusCode); }
public async Task <HttpResponseMessage> SendAsync(CancellationToken token = default(CancellationToken), Progress <HttpProgress> progressCallback = null) { using (var request = new HttpRequestMessage(_method, _requestUrl)) using (_contentStream) { request.Headers.Connection.Add(new HttpConnectionOptionHeaderValue("Keep-Alive")); request.Headers.UserAgent.Add(HttpProductInfoHeaderValue.Parse("Mozilla/5.0")); if (_customHeaders != null) { foreach (var header in _customHeaders) { request.Headers.Add(header); } } if (_method.Method == "PROPFIND") { request.Content = new HttpStringContent(PropfindContent, UnicodeEncoding.Utf8); } else if (_contentStream != null) { request.Content = new HttpStreamContent(_contentStream.AsInputStream()); } HttpResponseMessage response = await _httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead).AsTask(token, progressCallback); return(response); } }
public async Task<bool> SendMessage(string body) { var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); // webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/json;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); // Debug.WriteLine("Success/Error msg: {0}", nowait.StatusCode); return nowait.IsSuccessStatusCode; }
/// <summary> /// Load the Settings from the backend. /// </summary> /// <returns>Returns a JSON formated string.</returns> public async Task <string> LoadSettings() { try { Logger.Trace("LoadSettings"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(string.Format(Configuration.SettingsUri, Configuration.ApiKey)); HttpClient httpClient = new HttpClient(baseProtocolFilter); var responseMessage = await httpClient.SendRequestAsync(requestMessage); Logger.Trace("LoadSettings HTTPCode: {0}", responseMessage.StatusCode); LastCallResult = responseMessage.IsSuccessStatusCode ? NetworkResult.Success : NetworkResult.UnknownError; return(responseMessage?.Content.ToString()); } catch (Exception ex) { Logger.Error("LoadSettings Error", ex); LastCallResult = NetworkResult.NetworkError; return(null); } }
public static async Task <string> CookiedPostForm(string url, string referrer, KeyValuePair <string, string>[] keyValues) { //HttpResponseMessage response = null; try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); HttpFormUrlEncodedContent cont = new HttpFormUrlEncodedContent(keyValues); req.Content = cont; req.Headers.Referer = new Uri(referrer); HttpResponseMessage hc = await client.SendRequestAsync(req); //await ShowMessageDialog("响应", hc.Content.ToString()); req.Dispose(); return(hc.Content.ToString()); } catch (COMException e) { return("Cannot get response"); } }
public void LoadUrl(string url) { Uri uri = new Uri(url, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = new Uri(LocalScheme + url, UriKind.RelativeOrAbsolute); } if (Element.Cookies?.Count > 0) { //Set the Cookies... var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); foreach (Cookie cookie in Element.Cookies.GetCookies(uri)) { HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Domain, cookie.Path); httpCookie.Value = cookie.Value; filter.CookieManager.SetCookie(httpCookie, false); } var httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri); Control.NavigateWithHttpRequestMessage(httpRequestMessage); } else { //No Cookies so just navigate... Control.Source = uri; } }
public async static Task<bool> SendMessage(string body) { // Namespace info. //var serviceNamespace = "sudhesh"; //var hubName = "test"; //var deviceName = "tisensortag"; //var sharedAccessPolicyName = "all"; //var sharedAccessKey = "ZcfdxuLADoYv3zQycbpddoelgBvogPxnqM7/dfMdU2k="; var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceNamespace, hubName, deviceName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceNamespace, hubName, deviceName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(body) }; //request.Headers.Add("Authorization", sas); //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); var nowait = await webClient.SendRequestAsync(request); return nowait.IsSuccessStatusCode; }
public static async Task <string> sendDataToServer(string aUrl, string json) { string result = ""; var httpClient = new HttpClient(); // Always catch network exceptions for async methods try { httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpRequestMessage msg = new Windows.Web.Http.HttpRequestMessage(new Windows.Web.Http.HttpMethod("POST"), new Uri(aUrl)); msg.Content = new HttpStringContent((json)); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); var response = await httpClient.SendRequestAsync(msg).AsTask(); var statusCode = response.StatusCode; if (statusCode == HttpStatusCode.Ok) { result = await response.Content.ReadAsStringAsync(); } } catch { // Details in ex.Message and ex.HResult. } // Once your app is done using the HttpClient object call dispose to // free up system resources (the underlying socket and memory used for the object) httpClient.Dispose(); return(result); }
public static async Task <bool> Isfavourite(int imgid, string username, string userpass, string host) { bool isfavourite = false; try { string request = $"login={username}&password_hash={userpass}&id={imgid }"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var requestMessage = new Windows.Web.Http.HttpRequestMessage(new Windows.Web.Http.HttpMethod("POST"), new Uri($"{host}post/vote.xml")) { Content = new HttpStringContent(request) }; requestMessage.Headers["Accept-Encoding"] = "gzip, deflate, br"; requestMessage.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); var res = await httpClient.SendRequestAsync(requestMessage); var response = await res.Content.ReadAsStringAsync(); isfavourite = response.Contains("3") ? true : false; //if (response.Contains("3")) // isfavourite = true; //else // isfavourite = false; return(isfavourite); } catch { return(false); } }
void NavigateWithHttpRequest(Uri uri) { if (Element == null || Control == null) { return; } var requestMsg = new HttpRequestMessage(HttpMethod.Get, uri); // Add Local Headers foreach (var header in Element.LocalRegisteredHeaders) { if (!requestMsg.Headers.ContainsKey(header.Key)) { requestMsg.Headers.Add(header.Key, header.Value); } } // Add Global Headers if (Element.EnableGlobalHeaders) { foreach (var header in FormsWebView.GlobalRegisteredHeaders) { if (!requestMsg.Headers.ContainsKey(header.Key)) { requestMsg.Headers.Add(header.Key, header.Value); } } } // Navigate Control.NavigateWithHttpRequestMessage(requestMsg); }
private async void ButtonWindowsWebHttp_OnClick(object sender, RoutedEventArgs e) { var httpBaseProtocolFilter = new HttpBaseProtocolFilter { AllowUI = true, CacheControl = { ReadBehavior = HttpCacheReadBehavior.NoCache, WriteBehavior = HttpCacheWriteBehavior.NoCache } }; HttpCookieManager cookieManager = httpBaseProtocolFilter.CookieManager; List <HttpCookie> cookies = cookieManager.GetCookies(_uri).ToList(); using (var httpClient = new HttpClient(httpBaseProtocolFilter)) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, _uri); Request.Text = new StringBuilder().AppendLine(requestMessage.ToString()) .AppendLine(requestMessage.Headers.ToString()) .AppendLine(string.Join("\n", cookies)).ToString(); HttpResponseMessage responseMessage = await httpClient.SendRequestAsync(requestMessage); Request1.Text = new StringBuilder().AppendLine(responseMessage.RequestMessage.ToString()) .AppendLine(string.Join(" - ", cookies)).ToString(); Response.Text = responseMessage.ToString(); } }
public async Task<bool> SendMessage(EventHubSensorMessage message) { // get a hold of the current application app = App.Current as SensorTagReader.App; string json = JsonConvert.SerializeObject(message, new JsonSerializerSettings() { Culture = new CultureInfo("en-US") }); var resourceUri = String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}", serviceBusNamespace, eventHubName, message.SensorName); var sas = ServiceBusSASAuthentication(sharedAccessPolicyName, sharedAccessPolicyKey, resourceUri); var uri = new Uri(String.Format("https://{0}.servicebus.windows.net/{1}/publishers/{2}/messages?api-version=2014-05", serviceBusNamespace, eventHubName, message.SensorName)); var webClient = new Windows.Web.Http.HttpClient(); webClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("SharedAccessSignature", sas); webClient.DefaultRequestHeaders.TryAppendWithoutValidation("Content-Type", "application/atom+xml;type=entry;charset=utf-8"); // display the message that we are going to send app.Messages = "sending..." + json; var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri) { Content = new HttpStringContent(json) }; var nowait = await webClient.SendRequestAsync(request); return nowait.IsSuccessStatusCode; }
/// <summary> /// Sends a layout request to server and returns the HTTP response, if any. /// </summary> /// <param name="apiId">optional api id, overrides the given id by SDKData.</param> /// <returns>A HttpResponseMessage containing the server response or null in case of an error.</returns> public async Task <ResponseMessage> RetrieveLayoutResponse(string apiId) { Logger.Trace("RetrieveLayoutResponse"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(Configuration.LayoutUri); HttpClient apiConnection = new HttpClient(baseProtocolFilter); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, string.IsNullOrEmpty(apiId) ? Configuration.ApiKey : apiId); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); string geoHash = await ServiceManager.LocationService.GetGeoHashedLocation(); if (!string.IsNullOrEmpty(geoHash)) { apiConnection.DefaultRequestHeaders.Add(Constants.Xgeo, geoHash); } apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(SdkData.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : SdkData.UserId); HttpResponseMessage responseMessage; try { responseMessage = await apiConnection.SendRequestAsync(requestMessage); } catch (Exception ex) { LastCallResult = NetworkResult.NetworkError; System.Diagnostics.Debug.WriteLine("LayoutManager.RetrieveLayoutResponseAsync(): Failed to send HTTP request: " + ex.Message); return(new ResponseMessage() { IsSuccess = false }); } Logger.Trace("RetrieveLayoutResponse HTTPCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return(new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }); } LastCallResult = NetworkResult.UnknownError; return(new ResponseMessage() { StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }); }
private void NavigateWithHeader(Uri uri) { var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri); requestMsg.Headers.Add("User-Name", "Franklin Chen"); wb.NavigateWithHttpRequestMessage(requestMsg); wb.NavigationStarting += Wb_NavigationStarting; }
private void NavigateWithHeader(Uri uri) { var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri); requestMsg.Headers.Add("User-Agent", User_Agent); lp.webView.NavigateWithHttpRequestMessage(requestMsg); lp.webView.NavigationStarting += Web_NavigationStarting; }
private void NavigateWithHeader(Uri uri) { var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri); requestMsg.Headers.Add("User-Name", "Franklin Chen"); wb.NavigateWithHttpRequestMessage(requestMsg); wb.NavigationStarting += Wb_NavigationStarting; }
public static async Task <bool> CookiedGetReward(string queryId) { if (isCookieValid == false) { await ShowMessageDialog("领取功能需要设置Cookie", "领取操作不仅需要悬赏令ID, 还需要您的BDUSS. 请先设置Cookie."); return(false); } HttpResponseMessage response = null; try { string url = "https://jingyan.baidu.com/patchapi/claimQuery?queryId=" + queryId + "&token=" + newMainBdStoken + "×tamp=" + newMainBdstt; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); req.Headers.Referer = new Uri("https://jingyan.baidu.com/patch"); // ----- not working ----- //KeyValuePair<string, string>[] urlParams = { // new KeyValuePair<string, string>("queryId", queryId), // new KeyValuePair<string, string>("token", newMainBdStoken), // new KeyValuePair<string, string>("timestamp", newMainBdstt) //}; //req.Content = new FormUrlEncodedContent(urlParams) as IHttpContent; response = await client.SendRequestAsync(req); string respstr = response.Content.ToString().Replace(" ", ""); bool isGetSucceed = false; if (respstr.IndexOf("\"errno\":0") >= 0) { respstr = "成功领取。请在 个人中心->悬赏经验->已领取 查看。"; isGetSucceed = true; } else if (respstr.IndexOf("\"errno\":302") >= 0) { respstr = "你可能已经领取过经验。领取不成功(302)。"; //isGetSucceed = true; } else if (respstr.IndexOf("\"errno\":2") >= 0) { respstr = "身份验证失败,如果确定Cookie设定有效,可告知开发者 wang1223989563。错误码:2"; } else { respstr = "未知错误类型 (非302或2错误。可告知开发者 wang1223989563) \n错误信息: " + respstr; } await ShowMessageDialog("领取结果", respstr); req.Dispose(); return(isGetSucceed); } catch (COMException e) { await ShowDetailedError("领取未成功", e); return(false); } }
public async void postXMLData1() { string uri = "http://111.93.131.112/biws/buswebservice"; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); //string stringXml = "<soapenv:Envelope xmlns:com=\"com.busindia.webservices\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body><com:GetPlaceList xmls =\"\"><arg0><franchUserID>?</franchUserID><password>biteam</password><userID>474</userID><userKey>?</userKey><userName>[email protected]</userName><userRole>?</userRole><userStatus>?</userStatus><userType>101</userType></arg0></com:GetPlaceList></soapenv:Body></soapenv:Envelope>"; string franchUserID = "?"; string password = "******"; int userID = 474; string userKey = "?"; string username = "******"; string userRole = "?"; string userStatus = "?"; int usertype = 101; WebServiceClassLiberary.Class1 listings = new WebServiceClassLiberary.Class1(); XDocument element = listings.getList(franchUserID, password, userID, userKey, username, userRole, userStatus, usertype); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = "biwstest:biwstest"; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(strXmlReturned); XDocument loadedData = XDocument.Parse(strXmlReturned); var sdata = loadedData.Descendants("PlaceList"). Select(x => new PlaceList { PlaceID = x.Element("placeID").Value, PlaceCode = x.Element("placeCode").Value, PlaceName = x.Element("placeName").Value }); foreach (var item in sdata) { PlaceList pl = new PlaceList(); pl.PlaceID = item.PlaceID; pl.PlaceName = item.PlaceName; pl.PlaceCode = item.PlaceCode; CityList.Add(pl); } ListMenuItems.ItemsSource = sdata; }
public static HttpRequestMessage GetSignedRequest(Uri uri, string payload) { var signature = $"SIGNATURE.{payload}"; var fields = new Dictionary <string, string> { { "signed_body", signature } }; var request = new HttpRequestMessage(HttpMethod.Post, uri); request.Content = new HttpFormUrlEncodedContent(fields); request.Properties.Add("signed_body", signature); request.Properties.Add("ig_sig_key_version", "4"); return(request); }
/// <summary> /// Sends a layout request to server and returns the HTTP response, if any. /// </summary> /// <param name="apiId">optional api id, overrides the given id by SDKData.</param> /// <returns>A HttpResponseMessage containing the server response or null in case of an error.</returns> public async Task<ResponseMessage> RetrieveLayoutResponse(string apiId) { Logger.Trace("RetrieveLayoutResponse"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(Configuration.LayoutUri); HttpClient apiConnection = new HttpClient(baseProtocolFilter); apiConnection.DefaultRequestHeaders.Add(Constants.XApiKey, string.IsNullOrEmpty(apiId) ? Configuration.ApiKey : apiId); apiConnection.DefaultRequestHeaders.Add(Constants.Xiid, SdkData.DeviceId); string geoHash = await ServiceManager.LocationService.GetGeoHashedLocation(); if (!string.IsNullOrEmpty(geoHash)) { apiConnection.DefaultRequestHeaders.Add(Constants.Xgeo, geoHash); } apiConnection.DefaultRequestHeaders.Add(Constants.AdvertisementIdentifierHeader, string.IsNullOrEmpty(SdkData.UserId) ? Windows.System.UserProfile.AdvertisingManager.AdvertisingId : SdkData.UserId); HttpResponseMessage responseMessage; try { responseMessage = await apiConnection.SendRequestAsync(requestMessage); } catch (Exception ex) { LastCallResult = NetworkResult.NetworkError; System.Diagnostics.Debug.WriteLine("LayoutManager.RetrieveLayoutResponseAsync(): Failed to send HTTP request: " + ex.Message); return new ResponseMessage() {IsSuccess = false}; } Logger.Trace("RetrieveLayoutResponse HTTPCode: {0}", responseMessage.StatusCode); if (responseMessage.IsSuccessStatusCode) { LastCallResult = NetworkResult.Success; return new ResponseMessage() { Content = responseMessage.Content.ToString(), Header = responseMessage.Headers.ToString(), StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode }; } LastCallResult = NetworkResult.UnknownError; return new ResponseMessage() {StatusCode = responseMessage.StatusCode, IsSuccess = responseMessage.IsSuccessStatusCode}; }
internal static async Task<rt.HttpRequestMessage> ConvertHttpRequestMessaageToRt(HttpRequestMessage message, CancellationToken token) { var rt = new rt.HttpRequestMessage() { Method = new rt.HttpMethod(message.Method.Method), Content = await GetContentFromNet(message.Content).ConfigureAwait(false), RequestUri = message.RequestUri, }; CopyHeaders(message.Headers, rt.Headers); foreach (var prop in message.Properties) rt.Properties.Add(prop); return rt; }
public static async Task <AccessToken> GetAccessToken() { var uri = "https://disneyworld.disney.go.com/authentication/get-client-token/"; var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, new Uri(uri)); var client = new Windows.Web.Http.HttpClient(); //'Accept-Encoding: gzip, deflate, br' //'Accept-Language: en-US,en;q=0.9' //'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' //'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' //'Accept: application/json, text/javascript, */*; q = 0.01' //'Referer: https://disneyworld.disney.go.com/dining/' //'X-Requested-With: XMLHttpRequest' //'Connection: keep-alive' client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br"); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9"); client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"); // Cannot find Content-Type header, it bombs out client.DefaultRequestHeaders.Accept.ParseAdd("application/json, text/javascript, */*; q = 0.01"); request.Headers.Add("Referer", "https://disneyworld.disney.go.com/dining/"); request.Headers.Add("X-Requested-With", "XMLHttpRequest"); client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive"); try { var test = await client.SendRequestAsync(request); var content = test.Content.ToString(); dynamic test1 = JsonConvert.DeserializeObject <dynamic>(content); var testString = "{\"access_token\":\"2a8fa91da07b4798adf3e3b4ea6bca1a\",\"expires_in\":518}"; Console.WriteLine(testString); var token = JsonConvert.DeserializeObject <AccessToken>(content); return(token); } //Catch exception if trying to add a restricted header. catch (ArgumentException e1) { // Console.WriteLine(e.Message); } catch (Exception e1) { // Console.WriteLine("Exception is thrown. Message is :" + e.Message); } return(null); }
public static async Task <bool> SignInAsync(string userName, string password) { try { string id = null; var token = await GetAuthenticityToken(); string requestBody = $"authenticity_token={token}&url=&user%5Bname%5D={userName}&user%5Bpassword%5D={password}&commit=Login"; var httpClient = new Windows.Web.Http.HttpClient(new HttpBaseProtocolFilter()); var message = new Windows.Web.Http.HttpRequestMessage( new Windows.Web.Http.HttpMethod("POST"), new Uri($"https://yande.re/user/authenticate")) { Content = new HttpStringContent(requestBody) }; message.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); var response = await httpClient.SendRequestAsync(message); var responseString = await response.Content.ReadAsStringAsync(); var start = responseString.IndexOf("/user/show/") + "/user/show/".Length; if (start < 11) { YandeSettings.Current.UserID = id; YandeSettings.Current.UserName = userName; YandeSettings.Current.PasswordHash = HashPassword(password); return(false); } var end = responseString.IndexOf("\">My Profile<", start); id = responseString.Substring(start, end - start); YandeSettings.Current.UserID = id; YandeSettings.Current.UserName = userName; YandeSettings.Current.PasswordHash = HashPassword(password); return(true); } catch (Exception ex) { return(false); } }
internal static async Task <rt.HttpRequestMessage> ConvertHttpRequestMessaageToRt(HttpRequestMessage message, CancellationToken token) { var rt = new rt.HttpRequestMessage() { Method = new rt.HttpMethod(message.Method.Method), Content = await GetContentFromNet(message.Content).ConfigureAwait(false), RequestUri = message.RequestUri, }; CopyHeaders(message.Headers, rt.Headers); foreach (var prop in message.Properties) { rt.Properties.Add(prop); } return(rt); }
public void LoadUrl(string url) { Uri uri = new Uri(url, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = new Uri(LocalScheme + url, UriKind.RelativeOrAbsolute); } if (Element.Cookies?.Count > 0) { //Set the Cookies... var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); foreach (Cookie cookie in Element.Cookies.GetCookies(uri)) { HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Domain, cookie.Path); httpCookie.Value = cookie.Value; filter.CookieManager.SetCookie(httpCookie, false); } try { var httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri); Control.NavigateWithHttpRequestMessage(httpRequestMessage); } catch (System.Exception exc) { Internals.Log.Warning(nameof(WebViewRenderer), $"Failed to load: {uri} {exc}"); } } else { try { //No Cookies so just navigate... Control.Source = uri; } catch (System.Exception exc) { Internals.Log.Warning(nameof(WebViewRenderer), $"Failed to load: {uri} {exc}"); } } }
private void NavigateWithCustomUserAgent(WebViewNavigationStartingEventArgs args, string userAgent) { try { // Create new request with custom user agent var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, args.Uri); requestMsg.Headers.Add("User-Agent", userAgent); Control.NavigateWithHttpRequestMessage(requestMsg); } catch (Exception e) { throw; } finally { // Re-subscribe after navigating Control.NavigationStarting += OnNavigationStarting; } }
public async Task PostCommentAsync(string comment) { var requestBody = $"commenttext={WebUtility.UrlEncode(comment)}&postcomment=Post+Comment"; var httpClient = new Windows.Web.Http.HttpClient(new HttpBaseProtocolFilter()); var message = new Windows.Web.Http.HttpRequestMessage( new Windows.Web.Http.HttpMethod("POST"), new Uri(this.Link)) { Content = new HttpStringContent(requestBody) }; message.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); message.Headers["Cookie"] = await ExClient.GetExCookieAsync(""); var response = await httpClient.SendRequestAsync(message); var responseString = await response.Content.ReadAsStringAsync(); // Handle error page returned from server if (true) // sccuess { // Refresh the commenet list HtmlDocument htmlDocument = new HtmlDocument() { OptionFixNestedTags = true }; htmlDocument.LoadHtml(responseString); this.Comments.Clear(); HtmlNodeCollection commentNodes = htmlDocument.DocumentNode.SelectNodes("//div[@class='c1']"); if (commentNodes != null) { foreach (var node in commentNodes) { this.Comments.Add(ExComment.FromNode(node)); } } } }
public static async Task <string> GetPep_CSRF(Restaurant restaurant) { var returnString = string.Empty; var uri = restaurant.Url; var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, new Uri(uri)); var client = new Windows.Web.Http.HttpClient(); client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br"); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9"); client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"); // Cannot find Content-Type header, it bombs out client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); request.Headers.Add("Referer", "https://disneyworld.disney.go.com/dining/"); //request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.Headers.Add("Host", "disneyworld.disney.go.com"); client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive"); try { var test = await client.SendRequestAsync(request); var content = test.Content.ToString(); var pattern = "name=\"pep_csrf\" id=\"pep_csrf\" value=\"(.*)\">"; Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = rgx.Matches(content); returnString = matches[0].Groups[1].Value; } //Catch exception if trying to add a restricted header. catch (ArgumentException e1) { // Console.WriteLine(e.Message); } catch (Exception e1) { // Console.WriteLine("Exception is thrown. Message is :" + e.Message); } return(returnString); }
public static async Task Setfavourite(int imgid, string username, string userpass, int vote, string host) { try { string request = $"login={username}&password_hash={userpass}&id={imgid }&score={vote}"; Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var requestMessage = new Windows.Web.Http.HttpRequestMessage(new Windows.Web.Http.HttpMethod("POST"), new Uri($"{host}post/vote.xml")) { Content = new HttpStringContent(request) }; requestMessage.Headers["Accept-Encoding"] = "gzip, deflate, br"; requestMessage.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); var res = await httpClient.SendRequestAsync(requestMessage); var response = await res.Content.ReadAsStringAsync(); } catch (Exception ex) { await new MessageDialog(ex.ToString()).ShowAsync(); } }
internal static async Task <HttpRequestMessage> ConvertRtRequestMessageToNet(rt.HttpRequestMessage message, CancellationToken token) { var req = new HttpRequestMessage() { Method = new HttpMethod(message.Method.Method), RequestUri = message.RequestUri, Content = await GetNetContentFromRt(message.Content, token).ConfigureAwait(false), }; foreach (var header in message.Headers) { req.Headers.TryAddWithoutValidation(header.Key, header.Value); } foreach (var prop in message.Properties) { req.Properties.Add(prop); } return(req); }
private async void Upload_Click(object sender, RoutedEventArgs e) { FileOpenPicker open = new FileOpenPicker(); open.SuggestedStartLocation = PickerLocationId.PicturesLibrary; open.ViewMode = PickerViewMode.Thumbnail; // Filter to include a sample subset of file types open.FileTypeFilter.Clear(); open.FileTypeFilter.Add(".bmp"); open.FileTypeFilter.Add(".png"); open.FileTypeFilter.Add(".jpeg"); open.FileTypeFilter.Add(".jpg"); // Open a stream for the selected file StorageFile file = await open.PickSingleFileAsync(); // Ensure a file was selected if (file != null) { // Ensure the stream is disposed once the image is loaded using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); fileStream.AsStream().CopyTo(stream); //img.Source = bitmapImage; } } Uri uri = new Uri(serverAddressField.Text); Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri); request.Content = streamContent; Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, streamContent).AsTask(cts.Token); }
private static async Task <BitmapImage> GetMainSubStep_CookielessGetPic(string picUrl) { Uri myUri = new Uri(picUrl); HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, myUri); req.Headers.Host = new HostName(myUri.Host); req.Headers.Cookie.Clear(); HttpResponseMessage response = await client.SendRequestAsync(req); if (response == null) { return(null); } //HttpResponseMessage response if (response.StatusCode != HttpStatusCode.Ok) { return(null); } IHttpContent icont = response.Content; IBuffer buffer = await icont.ReadAsBufferAsync(); IRandomAccessStream irStream = new InMemoryRandomAccessStream(); BitmapImage img = new BitmapImage(); await irStream.WriteAsync(buffer); irStream.Seek(0); await img.SetSourceAsync(irStream); irStream.Dispose(); icont.Dispose(); response.Dispose(); req.Dispose(); return(img); }
public void LoadUrl(string url) { Uri uri = new Uri(url, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = new Uri(LocalScheme + url, UriKind.RelativeOrAbsolute); } var cookies = Element.Cookies?.GetCookies(uri); if (cookies != null) { SyncNativeCookies(url); try { var httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri); Control.NavigateWithHttpRequestMessage(httpRequestMessage); } catch (System.Exception exc) { Internals.Log.Warning(nameof(WebViewRenderer), $"Failed to load: {uri} {exc}"); } } else { try { //No Cookies so just navigate... Control.Source = uri; } catch (System.Exception exc) { Internals.Log.Warning(nameof(WebViewRenderer), $"Failed to load: {uri} {exc}"); } } }
public async Task <string> Login(string login, string password) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri("http://mangachan.ru/")) { Content = new HttpStringContent($"login=submit&login_name={login}&login_password={password}") }; httpRequestMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded"); _wv.NavigateWithHttpRequestMessage(httpRequestMessage); var ss = await WaitForMessageSent(); if (ss.IsSuccess) { _content = await _wv.InvokeScriptAsync("eval", new[] { "document.documentElement.outerHTML;" }); } if (IsLogout(_content)) { return(null); } return(_content); }
public void postXMLData1(GetAvailableService Get) { try { var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { string uri = AppStatic.WebServiceBaseURL; Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); GetSeatlayoutRequest _objSLR = new GetSeatlayoutRequest(); _objSLR.franchUserID = AppStatic.franchUserID; _objSLR.password = AppStatic.password; _objSLR.userID = AppStatic.userID; _objSLR.userKey = AppStatic.userKey; _objSLR.userName = AppStatic.userName; _objSLR.userRole = AppStatic.userRole; _objSLR.userStatus = AppStatic.userStatus; _objSLR.userType = AppStatic.userType; _objSLR.placeIDFrom = Get.placeIDFrom; _objSLR.placeCodeFrom = Get.placeCodeFrom; _objSLR.placeNameFrom = Get.placeNameFrom; _objSLR.placeIDto = Get.placeIDto; _objSLR.placeCodeTo = Get.placeCodeTo; _objSLR.placeNameTo = Get.placeNameTo; _objSLR.journeyDate = Get.journeyDate; _objSLR.classID = Get.classID; _objSLR.classLayoutID = Get.classLayoutID; _objSLR.serviceID = Get.serviceID; _objSLR.placeCodestuFromPlace = txthplaceCodeStatusFrm.Text; _objSLR.placeCodestuToPlace = txthplaceCodeStatusTo.Text; _objSLR.placeIDstuFromPlace = txthplaceIDStatusFrm.Text; _objSLR.placeIDstuToPlace = txthplaceIDStatusTo.Text; _objSLR.placeNamestuFromPlace = txthplaceNameStatusFrm.Text; _objSLR.placeNamestuToPlace = txthplaceNameStatusTo.Text; _objSLR.studID = Get.studID; _objSLR.totalPassengers = "?"; xmlUtility listings = new xmlUtility(); XDocument element = listings.getlayout(_objSLR); string stringXml = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(stringXml, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(strXmlReturned); XDocument loadedData = XDocument.Parse(strXmlReturned); List<XElement> _listResponse = (from t1 in loadedData.Descendants("wsResponse") select t1).ToList(); List<getSeatlayout> responsList = new List<getSeatlayout>(); string _msg = ""; if (_listResponse != null) { foreach (XElement _elemet in _listResponse) { getSeatlayout _obj = new getSeatlayout(); _obj.message = _elemet.Element("message").Value.ToString(); responsList.Add(_obj); } _msg = responsList.FirstOrDefault().message.ToString(); } if (_msg != "FAILURE") { var sdata = loadedData.Descendants("Seatlayout"). Select(x => new getSeatlayout { availableSeatNos = x.Element("availableSeatNos").Value, bookedSeatNos = x.Element("bookedSeatNos").Value, conductorSeatNo = x.Element("conductorSeatNo").Value, ladiesAvailableSeatNos = x.Element("ladiesAvailableSeatNos").Value, ladiesBookedSeatNos = x.Element("ladiesBookedSeatNos").Value, maxColCount = x.Element("maxColCount").Value, maxRowCount = x.Element("maxRowCount").Value, column = x.Element("seatDetails").Element("seats").Element("column").Value, quota = x.Element("seatDetails").Element("seats").Element("quota").Value, row = x.Element("seatDetails").Element("seats").Element("row").Value, seatNo = x.Element("seatDetails").Element("seats").Element("seatNo").Value, seatStatus = x.Element("seatDetails").Element("seats").Element("seatStatus").Value, type = x.Element("seatDetails").Element("seats").Element("type").Value, busID = x.Element("service").Element("busID").Value, distance = x.Element("service").Element("distance").Value, endPoint = x.Element("service").Element("endPoint").Value, startPoint = x.Element("service").Element("startPoint").Value, placeCodestuFromPlace = x.Element("stuFromPlace").Element("placeCode").Value, placeIDstuFromPlace = x.Element("stuFromPlace").Element("placeID").Value, placeNamestuFromPlace = x.Element("stuFromPlace").Element("placeName").Value, placeCodestuToPlace = x.Element("stuToPlace").Element("placeCode").Value, placeIDstuToPlace = x.Element("stuToPlace").Element("placeID").Value, placeNamestuToPlace = x.Element("stuToPlace").Element("placeName").Value, totalSeats = x.Element("totalSeats").Value, message = x.Element("wsResponse").Element("message").Value, statusCode = x.Element("wsResponse").Element("statusCode").Value }); foreach (var item in sdata) { _objS.placeCodestuFromPlace = item.placeCodestuFromPlace; _objS.placeIDstuFromPlace = item.placeIDstuFromPlace; _objS.placeNamestuFromPlace = item.placeNamestuFromPlace; _objS.placeCodestuToPlace = item.placeCodestuToPlace; _objS.placeIDstuToPlace = item.placeIDstuToPlace; _objS.placeNamestuToPlace = item.placeNamestuToPlace; _getStudDetails.Add(_objS); break; } int maxrowCount; int maxcolcount; var _listCol = (from t1 in loadedData.Descendants("maxColCount") select t1).FirstOrDefault(); var _listRow = (from t1 in loadedData.Descendants("maxRowCount") select t1).FirstOrDefault(); maxcolcount = Convert.ToInt32(_listCol.Value.ToString()); maxrowCount = Convert.ToInt32(_listRow.Value.ToString()); int b = maxrowCount; int a = maxcolcount; for (int r = 0; r <= a; r++) { Mygrid.RowDefinitions.Add(new RowDefinition()); } for (int c = 0; c < b; c++) { Mygrid.ColumnDefinitions.Add(new ColumnDefinition()); } List<XElement> _srow = (from t1 in loadedData.Descendants("seats") select t1).ToList(); List<getSeatlayout> srow = new List<getSeatlayout>(); foreach (XElement _elemetsr in _srow) { Image img = new Image(); TextBlock txtSeatnumber = new TextBlock(); TextBlock txtType = new TextBlock(); txtSeatnumber.Visibility = Visibility.Visible; getSeatlayout _objsr = new getSeatlayout(); _objsr.row = _elemetsr.Element("row").Value.ToString(); _objsr.column = _elemetsr.Element("column").Value.ToString(); _objsr.seatNo = _elemetsr.Element("seatNo").Value.ToString(); _objsr.type = _elemetsr.Element("type").Value.ToString(); _objsr.quota = _elemetsr.Element("quota").Value.ToString(); _objsr.seatStatus = _elemetsr.Element("seatStatus").Value.ToString(); srow.Add(_objsr); c = Convert.ToInt32(srow.LastOrDefault().row.ToString()); r = Convert.ToInt32(srow.LastOrDefault().column.ToString()); s = Convert.ToInt32(srow.LastOrDefault().seatNo.ToString()); t = srow.LastOrDefault().type.ToString(); q = srow.LastOrDefault().quota.ToString(); SeatS = srow.LastOrDefault().seatStatus.ToString(); int nn = -(r - (a + 1)); img.SetValue(Grid.ColumnProperty, c - 1); img.SetValue(Grid.RowProperty, nn - 1); txtSeatnumber.SetValue(Grid.ColumnProperty, c - 1); txtSeatnumber.SetValue(Grid.RowProperty, nn - 1); txtType.SetValue(Grid.ColumnProperty, c - 1); txtType.SetValue(Grid.RowProperty, nn - 1); txtType.FontSize = 12; txtType.Text = t.ToString(); txtType.Foreground = new SolidColorBrush(Colors.Black); txtType.Margin = new Thickness { Left = 20, Top = 95, Right = 0, Bottom = 0 }; txtSeatnumber.FontSize = 12; txtSeatnumber.Text = s.ToString(); txtSeatnumber.Foreground = new SolidColorBrush(Colors.Black); txtSeatnumber.Margin = new Thickness { Left = 5, Top = 95, Right = 0, Bottom = 0 }; img.Height = 40; img.Width = 40; img.Margin = new Thickness { Left = 0, Top = 40, Right = 0, Bottom = 0 }; if (SeatS == "AVAILABLE") { img.Name = txtSeatnumber.Text + txtType.Text; img.Source = new BitmapImage(new System.Uri("ms-appx:///Assets/Seats/ss_empty_seat.png")); img.Tapped += img_Tapped; } else { img.Source = new BitmapImage(new System.Uri("ms-appx:///Assets/Seats/ss_booked_seat.png")); } for (int row = 0; row < Mygrid.RowDefinitions.Count; row++) { for (int column = 0; column < Mygrid.ColumnDefinitions.Count; column++) { if (nn == row && c == column) { txtSeatnumber.Visibility = Visibility.Visible; txtType.Visibility = Visibility.Visible; img.Visibility = Visibility.Visible; Mygrid.Children.Add(txtSeatnumber); Mygrid.Children.Add(img); Mygrid.Children.Add(txtType); } } } } LoderPopup.Visibility = Visibility.Collapsed; } else { LoderPopup.Visibility = Visibility.Collapsed; } }).AsTask(); } catch (Exception e) { var messagedialog = new Windows.UI.Popups.MessageDialog("There is service not available"); } }
/// <summary> /// Load the Settings from the backend. /// </summary> /// <returns>Returns a JSON formated string.</returns> public async Task<string> LoadSettings() { try { Logger.Trace("LoadSettings"); HttpRequestMessage requestMessage = new HttpRequestMessage(); HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; requestMessage.Method = HttpMethod.Get; requestMessage.RequestUri = new Uri(string.Format(Configuration.SettingsUri, Configuration.ApiKey)); HttpClient httpClient = new HttpClient(baseProtocolFilter); var responseMessage = await httpClient.SendRequestAsync(requestMessage); Logger.Trace("LoadSettings HTTPCode: {0}", responseMessage.StatusCode); LastCallResult = responseMessage.IsSuccessStatusCode ? NetworkResult.Success : NetworkResult.UnknownError; return responseMessage?.Content.ToString(); } catch (Exception ex) { Logger.Error("LoadSettings Error", ex); LastCallResult = NetworkResult.NetworkError; return null; } }
public async Task<string> UploadImage2(byte[] image, string url) { Stream stream = new System.IO.MemoryStream(image); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); Uri resourceAddress = null; Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress); Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress); request.Content = streamContent; var httpClient = new Windows.Web.Http.HttpClient(); var cts = new CancellationTokenSource(); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); response.EnsureSuccessStatusCode(); string result =await response.Content.ReadAsStringAsync(); return result; }
private async void Button_Click1(object sender, RoutedEventArgs e) { string apiUrl = "http://mobiledatawebapi.azurewebsites.net/api/MobileData"; Uri apiUrl2 = new Uri("http://mobiledatawebapi.azurewebsites.net/api/MobileData"); var locationInfo = new LocationInfo() { Id = Guid.NewGuid(), Latitude = _latitude, Longitude = _longitude, County = _region }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(locationInfo); HttpClient httpClient = new HttpClient(); HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), new Uri(apiUrl)); msg.Content = new HttpStringContent(json); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); HttpResponseMessage response1 = await httpClient.GetAsync(apiUrl2).AsTask(); var content = response1.Content; var t = content.ReadAsStringAsync().GetResults(); if (locationInfo.County != null) { if (content != null) { if (content.ReadAsStringAsync().GetResults().Contains(locationInfo.County)) { statustxt.Text = "County Already Set"; } else { HttpResponseMessage response = await httpClient.SendRequestAsync(msg).AsTask(); btnSend.Visibility = Visibility.Collapsed; statustxt.Text = "Sent Successfully!"; } } } }
public async void postXMLData1() { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); xmlUtility listings = new xmlUtility(); getPlaceListRequest _objgetPlaceListRequest = listings.GetUserRequestParameters(); XDocument element = listings.getList(_objgetPlaceListRequest); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(strXmlReturned); StorageFile files = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("PlaceNames.xml", CreationCollisionOption.ReplaceExisting); String historyTestContent = await FileIO.ReadTextAsync(files); using (var stream = await files.OpenStreamForWriteAsync()) { stream.Write(fileBytes, 0, fileBytes.Length); } LoderPopup.Visibility = Visibility.Collapsed; } catch (Exception ex) { LoderPopup.Visibility = Visibility.Collapsed; ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }
public async void postXMLData1() { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); getBoardingPointsRequest _objBPR = new getBoardingPointsRequest(); _objBPR.franchUserID = AppStatic.franchUserID; _objBPR.password = AppStatic.password; _objBPR.userID = AppStatic.userID; _objBPR.userKey = AppStatic.userKey; _objBPR.userName = AppStatic.userName; _objBPR.userRole = AppStatic.userRole; _objBPR.userStatus = AppStatic.userStatus; _objBPR.userType = AppStatic.userType; _objBPR.placeIDFrom = pickDropHelper.objGetAvailableService.placeIDFrom; _objBPR.placeCodeFrom = pickDropHelper.objGetAvailableService.placeCodeFrom; _objBPR.placeNameFrom = pickDropHelper.objGetAvailableService.placeNameFrom; _objBPR.placeIDto = pickDropHelper.objGetAvailableService.placeIDto; _objBPR.placeCodeTo = pickDropHelper.objGetAvailableService.placeCodeTo; _objBPR.placeNameTo = pickDropHelper.objGetAvailableService.placeNameTo; _objBPR.journeyDate = pickDropHelper.objGetAvailableService.journeyDate; _objBPR.serviceID = pickDropHelper.objGetAvailableService.serviceID; _objBPR.placeCodestuFromPlace = pickDropHelper.objGetSeatLayout.placeCodestuFromPlace; _objBPR.placeCodestuToPlace = pickDropHelper.objGetSeatLayout.placeCodestuToPlace; _objBPR.placeIDstuFromPlace = pickDropHelper.objGetSeatLayout.placeIDstuFromPlace; _objBPR.placeIDstuToPlace = pickDropHelper.objGetSeatLayout.placeIDstuToPlace; _objBPR.placeNamestuFromPlace = pickDropHelper.objGetSeatLayout.placeNamestuFromPlace; _objBPR.placeNamestuToPlace = pickDropHelper.objGetSeatLayout.placeNamestuToPlace; _objBPR.stulID = pickDropHelper.objGetAvailableService.studID; xmlUtility listings = new xmlUtility(); XDocument element = listings.getBoardingPoint(_objBPR); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(strXmlReturned); XDocument loadedData = XDocument.Parse(strXmlReturned); List<getBoardingPoints> sdata = loadedData.Descendants("boardingPoints").Where(c => c.Element("type").Value == "DROPOFF POINT").Select(c => new getBoardingPoints() { platformNo = c.Element("platformNo").Value, pointID = c.Element("pointID").Value, Time = c.Element("time").Value, Type = c.Element("type").Value, pointName = c.Element("pointName").Value }).ToList(); foreach (var item in sdata) { _obj.platformNo = item.platformNo; _obj.pointID = item.pointID; _obj.pointName = item.pointName; _obj.Time = item.Time; _obj.Type = item.Type; _getBoardingPoints.Add(_obj); } ListMenuItems.ItemsSource = sdata; LoaderPopDropoff.Visibility = Visibility.Collapsed; } catch (Exception ex) { } }
public async void postXMLData1() { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); xmlUtility listings = new xmlUtility(); getPlaceListRequest _objgetPlaceListRequest = listings.GetUserRequestParameters(); XDocument element = listings.getList(_objgetPlaceListRequest); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(strXmlReturned); XDocument loadedData = XDocument.Parse(strXmlReturned); var PlaceList = loadedData.Descendants("PlaceList"). Select(x => new PlaceList { PlaceID = x.Element("placeID").Value, PlaceCode = x.Element("placeCode").Value, PlaceName = x.Element("placeName").Value }); } catch (Exception ex) { ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }
public void postXMLData1() { var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); xmlUtility listings = new xmlUtility(); getPlaceListRequest _objgetPlaceListRequest = listings.GetUserRequestParameters(); XDocument element = listings.getList(_objgetPlaceListRequest); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); //StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("PlaceNames.xml"); //String timestamp = await FileIO.ReadTextAsync(sampleFile); //XDocument loadedData = XDocument.Parse(timestamp); XDocument loadedData = XDocument.Parse(strXmlReturned); var PlaceList = loadedData.Descendants("PlaceList"). Select(x => new PlaceList { PlaceID = x.Element("placeID").Value, PlaceCode = x.Element("placeCode").Value, PlaceName = x.Element("placeName").Value }); foreach (var item in PlaceList) { PlaceList pl = new PlaceList(); pl.PlaceID = item.PlaceID; pl.PlaceName = item.PlaceName; pl.PlaceCode = item.PlaceCode; CityList.Add(pl); } ListMenuItems.ItemsSource = PlaceList; LoderPopup.Visibility = Visibility.Collapsed; } catch (Exception ex) { PopupError.Visibility = Visibility.Visible; LoderPopup.Visibility = Visibility.Collapsed; ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }).AsTask(); }
public void postXMLData1() { var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); GetAvailableServicesRequest _objAGR = new GetAvailableServicesRequest(); _objAGR.franchUserID = AppStatic.franchUserID; _objAGR.password = AppStatic.password; _objAGR.userID = AppStatic.userID; _objAGR.userKey = AppStatic.userKey; _objAGR.userName = AppStatic.userName; _objAGR.userRole = AppStatic.userRole; _objAGR.userStatus = AppStatic.userStatus; _objAGR.userType = AppStatic.userType; _objAGR.placeNameFrom = txtBFromLocationT.Text; _objAGR.placeNameTo = txtBToLocationT.Text; _objAGR.placeIDFrom = txtBFromID.Text; _objAGR.placeIDto = txtBToID.Text; _objAGR.placeCodeFrom = txtBFromCode.Text; _objAGR.placeCodeTo = txtBToCode.Text; string d = txtBDateTab.Text; System.DateTime dt = System.DateTime.ParseExact(d, "dd MMM yyyy", CultureInfo.InvariantCulture); string Date = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); _objAGR.journeyDate = Date; xmlUtility listings = new xmlUtility(); XDocument element = listings.getservice(_objAGR); string stringXml = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(stringXml, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); XDocument loadedData = XDocument.Parse(strXmlReturned); XDocument element1 = listings.getAvailableServicelayout(_objAGR); string stringXml1 = element1.ToString(); byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(stringXml1.ToString()); StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("HistoryTest1.xml", CreationCollisionOption.OpenIfExists); String historyTestContent = await FileIO.ReadTextAsync(file); using (var stream = await file.OpenStreamForWriteAsync()) { stream.Seek(0, SeekOrigin.End); stream.Write(fileBytes, 0, fileBytes.Length); } List<XElement> _list = (from t1 in loadedData.Descendants("wsResponse") select t1).ToList(); List<PlaceList> seatsList = new List<PlaceList>(); string _msg = ""; if (_list != null) { foreach (XElement _elemet in _list) { PlaceList _obj = new PlaceList(); _obj.message = _elemet.Element("message").Value.ToString(); seatsList.Add(_obj); } _msg = seatsList.FirstOrDefault().message.ToString(); } if (_msg != "FAILURE") { var sdata = loadedData.Descendants("service"). Select(x => new GetAvailableService { arrivalDate = x.Element("arrivalDate").Value, arrivalTime = x.Element("arrivalTime").Value, classID = x.Element("classID").Value, classLayoutID = x.Element("classLayoutID").Value, className = x.Element("className").Value, corpCode = x.Element("corpCode").Value, departureTime = x.Element("departureTime").Value, destination = x.Element("destination").Value, fare = x.Element("fare").Value, journeyDate = x.Element("journeyDate").Value, journeyHours = x.Element("journeyHours").Value, maxSeatsAllowed = x.Element("maxSeatsAllowed").Value, origin = x.Element("origin").Value, placeIDFrom = x.Element("biFromPlace").Element("placeID").Value, placeIDto = x.Element("biToPlace").Element("placeID").Value, refundStatus = x.Element("refundStatus").Value, routeNo = x.Element("routeNo").Value, seatsAvailable = x.Element("seatsAvailable").Value, seatStatus = x.Element("seatStatus").Value, serviceID = x.Element("serviceID").Value, startPoint = x.Element("startPoint").Value, studID = x.Element("stuID").Value, tripCode = x.Element("tripCode").Value, viaPlaces = x.Element("viaPlaces").Value }); foreach (var item in sdata) { GetAvailableService gas = new GetAvailableService(); gas.arrivalDate = item.arrivalDate; gas.arrivalTime = item.arrivalTime; gas.classID = item.classID; gas.classLayoutID = item.classLayoutID; gas.className = item.className; gas.corpCode = item.corpCode; gas.departureTime = item.departureTime; gas.destination = item.destination; gas.fare = item.fare; gas.journeyDate = item.journeyDate; gas.journeyHours = item.journeyHours; gas.maxSeatsAllowed = item.maxSeatsAllowed; gas.origin = item.origin; gas.placeIDFrom = item.placeIDFrom; gas.placeIDto = item.placeIDto; gas.refundStatus = item.refundStatus; gas.routeNo = item.routeNo; gas.seatsAvailable = item.seatsAvailable; gas.seatStatus = item.seatStatus; gas.serviceID = item.serviceID; gas.startPoint = item.startPoint; gas.studID = item.studID; gas.tripCode = item.tripCode; gas.viaPlaces = item.viaPlaces; availableservice.Add(gas); } ListMenuItems.ItemsSource = sdata; string MaxPriceresult = sdata.OrderByDescending(x => x.fare).Select(x => x.fare).FirstOrDefault().ToString(); if (MaxPriceresult != null) { txtBMaxPriceCurrent.Text = MaxPriceresult; txtBMaxPrice.Text = MaxPriceresult; maxPrice = Convert.ToInt32(MaxPriceresult); MaxPrice = Convert.ToInt32(MaxPriceresult); Thumb2PositionPrice = Convert.ToInt32(MaxPriceresult); } string MinPriceresult = sdata.OrderBy(x => x.fare).Select(x => x.fare).FirstOrDefault().ToString(); if (MinPriceresult != null) { txtBMinPrice.Text = MinPriceresult; txtBMinPriceCurrent.Text = MinPriceresult; minPrice = Convert.ToInt32(MinPriceresult); MinPrice = Convert.ToInt32(MinPriceresult); Thumb1PositionPrice = Convert.ToInt32(MinPriceresult); } ListMenuItemsFilterCorp.ItemsSource = sdata.Select(x => x.corpCode).Distinct().ToList(); ListMenuItemsFilterBusType.ItemsSource = sdata.Select(x => x.className).Distinct().ToList(); FilterFunVisible(); } else { FilterFunCollapsed(); } } catch (Exception ex) { LoaderPop.Visibility = Visibility.Collapsed; ErrorpopUp.Visibility = Visibility.Visible; ExceptionLog obj = new ExceptionLog(); Error objError = new Error(); objError.ErrorEx = ex.Message; obj.CreateLogFile(objError); } }).AsTask(); }
public async Task<string> Generatehash512(string test) { string uri = "http://demo.mapsearch360.com/WSFacilities.svc/Generatehash512/?text=" + test; Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(httpRequestMessage); string data = await response.Content.ReadAsStringAsync(); string encryptedstring = (data.Split(new char[] { ':' }))[1].Trim(new char[] { '\\', '"', '}' }); return encryptedstring; }
// Get all IDProofs option from web services public async void postXMLData1() { string uri = AppStatic.WebServiceBaseURL; // some xml string Uri _url = new Uri(uri, UriKind.RelativeOrAbsolute); getIDProofsRequest _objeIDProof = new getIDProofsRequest(); _objeIDProof.franchUserID = AppStatic.franchUserID; _objeIDProof.password = AppStatic.password; _objeIDProof.userID = AppStatic.userID; _objeIDProof.userKey = AppStatic.userKey; _objeIDProof.userName = AppStatic.userName; _objeIDProof.userRole = AppStatic.userRole; _objeIDProof.userStatus = AppStatic.userStatus; _objeIDProof.userType = AppStatic.userType; _objeIDProof.studID = pickDropHelper.objGetAvailableService.studID; xmlUtility listings = new xmlUtility(); XDocument element = listings.getIDProof(_objeIDProof); string file = element.ToString(); var httpClient = new Windows.Web.Http.HttpClient(); var info = AppStatic.WebServiceAuthentication; var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(info)); httpClient.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", token); httpClient.DefaultRequestHeaders.Add("SOAPAction", ""); Windows.Web.Http.HttpRequestMessage httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, _url); httpRequestMessage.Headers.UserAgent.TryParseAdd("Mozilla/4.0"); IHttpContent content = new HttpStringContent(file, Windows.Storage.Streams.UnicodeEncoding.Utf8); httpRequestMessage.Content = content; Windows.Web.Http.HttpResponseMessage httpResponseMessage = await httpClient.SendRequestAsync(httpRequestMessage); string strXmlReturned = await httpResponseMessage.Content.ReadAsStringAsync(); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(strXmlReturned); XDocument loadedData = XDocument.Parse(strXmlReturned); var sdata = loadedData.Descendants("idProofs"). Select(x => new getIDProofs { idProofID = x.Element("idProofID").Value, idProofName = x.Element("idProofName").Value, }).ToList(); foreach (var item in sdata) { getIDProofs pl = new getIDProofs(); pl.idProofID = item.idProofID; pl.idProofName = item.idProofName; _getIDProofs.Add(pl); } ListMenuItemsIDPRoof.ItemsSource = sdata; getIDProofs pls = new getIDProofs(); }