private async Task <int?> GetAccessToken()
        {
            OAuthToken oAuthToken = new OAuthToken();

            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            var urlEncodedSecret = System.Net.WebUtility.UrlEncode(secret);
            var urlEncodedSid    = System.Net.WebUtility.UrlEncode(sid);
            var body             =
                String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);
            Uri requestUri         = new Uri("https://login.live.com/accesstoken.srf");
            HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), requestUri);

            msg.Content = new HttpStringContent(body);
            msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
            HttpResponseMessage HttpResponseMessage = await httpClient.SendRequestAsync(msg).AsTask();

            if (HttpResponseMessage.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
            {
                var resultsss = await HttpResponseMessage.Content.ReadAsStringAsync();

                oAuthToken        = GetOAuthTokenFromJson(resultsss);
                currentOAuthToken = oAuthToken.AccessToken;
            }
            return(await Task.FromResult(1));
        }
        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;
        }
示例#3
0
        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 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);
        }
        /// <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);
            }
        }
        private async Task <int?> PostToWns(string uri, string AccessToken, string xml, string notificationType, string contentType)
        {
            try
            {
                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
                Uri requestUri         = new Uri(uri);
                HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), requestUri);
                msg.Content = new HttpStringContent(CreateXMLtemplet(xml));
                msg.Headers.Add("X-WNS-Type", notificationType);
                msg.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken));
                msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/xml");
                HttpResponseMessage HttpResponseMessage = await httpClient.SendRequestAsync(msg).AsTask();

                if (HttpResponseMessage.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                {
                    var resultsss = await HttpResponseMessage.Content.ReadAsStringAsync();

                    return(await Task.FromResult(1));
                }
                else
                {
                    return(await Task.FromResult(0));
                }
            }
            catch (Exception ex)
            {
                return(await Task.FromResult(0));
            }
        }
        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;
        }
示例#8
0
        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);
            }
        }
        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);
                }
        }
示例#10
0
        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;
        }
示例#11
0
        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();
            }
        }
示例#12
0
        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);
        }
示例#13
0
        public static async Task <HtmlDocument> GetHtmlDoc(string relativeUri)
        {
            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            Windows.Web.Http.HttpClient httpClient         = new Windows.Web.Http.HttpClient();
            HttpRequestMessage          HttpRequestMessage =
                new HttpRequestMessage(HttpMethod.Get,
                                       new Uri(DataSource.requestUri, relativeUri));

            HttpRequestMessage.Headers.Add("User-Agent", DataSource.CustomUserAgent);
            try
            {
                //Send the GET request
                httpResponse = await httpClient.SendRequestAsync(HttpRequestMessage);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            var htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(httpResponseBody);
            return(htmlDoc);
        }
        /// <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
            });
        }
        public static async void SendOneWayMessage(SimpleRestClient simpleClient, SimpleMessage simpleMessage)
        {
            Web.HttpClient httpClient = new Web.HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage requestMessage = await BuildHttpRequestMessage(simpleClient, simpleMessage);

            httpClient.SendRequestAsync(requestMessage);
        }
        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;
        }
示例#17
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            CheckDisposed();

            var rtMessage = await ConvertHttpRequestMessaageToRt(request, cancellationToken).ConfigureAwait(false);

            var resp = await _client.SendRequestAsync(rtMessage).AsTask(cancellationToken).ConfigureAwait(false);

            var netResp = await ConvertRtResponseMessageToNet(resp, cancellationToken).ConfigureAwait(false);

            return(netResp);
        }
示例#18
0
        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);
        }
        /// <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};
        }
        public static async Task <SimpleResponse <T> > SendMessage <T>(SimpleRestClient simpleClient, SimpleMessage simpleMessage)
        {
            SimpleResponse <T> toReturn = new SimpleResponse <T>();

            Web.HttpClient httpClient = new Web.HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage requestMessage = await BuildHttpRequestMessage(simpleClient, simpleMessage);

            HttpResponseMessage response = await httpClient.SendRequestAsync(requestMessage);

            toReturn.DataRaw       = response.Content;
            toReturn.DataConverted = JsonConvert.DeserializeObject <T>(response.Content.ToString());

            return(toReturn);
        }
示例#21
0
        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);
            }
        }
        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 <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);
        }
示例#24
0
        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));
                    }
                }
            }
        }
示例#25
0
        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();
            }
        }
示例#26
0
        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:GetAvailableServices xmls =\"\"><arg0><biFromPlace><placeCode>AMD</placeCode><placeID>208</placeID><placeName>AHMEDABAD</placeName></biFromPlace><biToPlace><placeCode>SRT</placeCode><placeID>317</placeID><placeName>SURAT</placeName></biToPlace><journeyDate>29/04/2015</journeyDate><wsUser><franchUserID>?</franchUserID><password>biteam</password><userID>474</userID><userKey>?</userKey><userName>[email protected]</userName><userRole>?</userRole><userStatus>?</userStatus><userType>101</userType></wsUser></arg0></com:GetAvailableServices></soapenv:Body></soapenv:Envelope>";
            //  string stringXml=  Path.Combine(Package.Current.InstalledLocation.Path, "Test.xml");
            // XDocument xmlDoc = XDocument.Load("Test.xml");

            StorageFolder storageFolder = Package.Current.InstalledLocation;
            StorageFile   storageFile   = await storageFolder.GetFileAsync("Test.xml");

            string stringXml;

            stringXml = await FileIO.ReadTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);


            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(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);
        }
示例#27
0
        public async Task PutFileOnServer()
        {
            Uri requestUri = new Uri("https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json");

            Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.AllowUI = false;

            // Set credentials that will be sent to the server.
            filter.ServerCredential =
                new Windows.Security.Credentials.PasswordCredential(
                    "https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json",
                    "*****@*****.**",
                    "Pr0digal1!");


            //string content = @"{ deviceId:'newdevice'}";
            fileOpenPicker.FileTypeFilter.Add(".json");
            fileOpenPicker.FileTypeFilter.Add(".txt");
            IStorageFile jsonFile = await fileOpenPicker.PickSingleFileAsync();

            IRandomAccessStream stream = await jsonFile.OpenAsync(FileAccessMode.Read);

            //Windows.Web.Http.HttpStringContent requestBody = new HttpStringContent(content, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            Windows.Web.Http.HttpStreamContent requestContent = new HttpStreamContent(stream);

            Windows.Web.Http.HttpRequestMessage message = new Windows.Web.Http.HttpRequestMessage();
            message.RequestUri = requestUri;
            message.Method     = Windows.Web.Http.HttpMethod.Put;
            message.Content    = requestContent;

            Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(filter);

            Windows.Web.Http.HttpResponseMessage response = await client.SendRequestAsync(message);


            Debug.WriteLine(response);
        }
示例#28
0
        private static async Task GetECookie(string username, string password)
        {
            string requestBody = $"UserName={username}&PassWord={password}&CookieDate=1";

            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://forums.e-hentai.org/index.php?act=Login&CODE=01"))
            {
                Content = new HttpStringContent(requestBody)
            };

            message.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
            var response = await httpClient.SendRequestAsync(message);

            string eCookie = response.Headers["Set-Cookie"];

            if (eCookie.IndexOf("expires=") >= 0)
            {
                var start = eCookie.IndexOf("expires=") + ("expires=".Length);
                var end   = eCookie.IndexOf(";", start);
                var s     = eCookie.Substring(start, end - start);
                try
                {
                    ExSettings.Current.ECookieExpire = DateTimeOffset.Parse(s).ToUniversalTime().DateTime;
                }
                catch (Exception ex)
                {
                }
                ExSettings.Current.ECookie = eCookie;
            }
            else
            {
                throw new Exception("Cannot login");
            }
        }
        // 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();
           
        }
示例#30
0
        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;
        }
示例#31
0
            public async Task <SystemNetHttpRequestResult> SendRequestAsync(string url, HttpMethod method, string contentType, string requestBody, byte[] requestBytes, Dictionary <string, string> headers, NetworkCredential credentials)
            {
                var filter = new HttpBaseProtocolFilter
                {
                    AutomaticDecompression = true,
                    AllowAutoRedirect      = true,
                    AllowUI = false
                };

                if (filter.IgnorableServerCertificateErrors != null)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                }

                // use this to make sure we don't have weird behavior where the app caches credentials for way too long
                // the real fix seems to be using a new API introduced in 14295 but that's not the version that is targeted today
                // see: http://stackoverflow.com/questions/30731424/how-to-stop-credential-caching-on-windows-web-http-httpclient
                filter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;

                if (credentials != null)
                {
                    filter.ServerCredential = new PasswordCredential("2Day", credentials.UserName, credentials.Password);
                }
                else
                {
                    filter.ServerCredential = null;
                }

                var client = new HttpClient(filter);

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                var request = new Windows.Web.Http.HttpRequestMessage(method.ToWindowsHttp(), SafeUri.Get(url));
                HttpRequestMessage systemNetRequest = request.ToSystemHttp();

                if (requestBody != null)
                {
                    if (method != HttpMethod.Post)
                    {
                        throw new NotSupportedException("Request body must use POST method");
                    }

                    var arrayContent = new HttpBufferContent(requestBytes.AsBuffer());

                    if (!string.IsNullOrWhiteSpace(contentType))
                    {
                        arrayContent.Headers.ContentType = new HttpMediaTypeHeaderValue(contentType);
                    }

                    if (method == HttpMethod.Post)
                    {
                        request.Content = arrayContent;
                    }
                }

                WebRequestBuilder.TraceRequest(systemNetRequest, requestBody);
                CancellationTokenSource timeoutCancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(30));

                Windows.Web.Http.HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(timeoutCancellationToken.Token);

                client.Dispose();

                HttpResponseMessage systemNetResponse = await response.ToWindowsHttp(systemNetRequest);

                return(new SystemNetHttpRequestResult
                {
                    Request = systemNetRequest,
                    Response = systemNetResponse
                });
            }
        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);

                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 static async Task <RestaurantAvail> GetRestaurantTimes(Restaurant restaurant, string searchDate, string searchTime, int partySize)
        {
            RestaurantAvail returnValue = new RestaurantAvail()
            {
                Restaurant = restaurant
            };

            var pep_csft = await GetPep_CSRF(restaurant);

            var uri     = "https://disneyworld.disney.go.com/finder/dining-availability/";
            var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, 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");
            client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");

            client.DefaultRequestHeaders.Accept.ParseAdd("application/json, text/javascript, */*; q = 0.01");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("Host", "disneyworld.disney.go.com");
            request.Headers.Add("Origin", "https://disneyworld.disney.go.com");
            // request.Headers.Add("Referer", "https://disneyworld.disney.go.com/dining/animal-kingdom-lodge/boma-flavors-of-africa/");
            request.Headers.Add("Referer", restaurant.Url);


            var values = new List <KeyValuePair <string, string> >();

            values.Add(new KeyValuePair <string, string>("pep_csrf", pep_csft));
            values.Add(new KeyValuePair <string, string>("searchDate", searchDate));          //"2018-06-13"));
            values.Add(new KeyValuePair <string, string>("skipPricing", "true"));
            values.Add(new KeyValuePair <string, string>("searchTime", searchTime));          //, "18:30"));
            values.Add(new KeyValuePair <string, string>("partySize", partySize.ToString())); // "2"));
            values.Add(new KeyValuePair <string, string>("id", $"{restaurant.EntityId};entityType={restaurant.EntityType}"));
            values.Add(new KeyValuePair <string, string>("type", "dining"));

            request.Content = new Windows.Web.Http.HttpFormUrlEncodedContent(values);


            try
            {
                var test = await client.SendRequestAsync(request);

                var content = test.Content.ToString();

                var hasAvailabilityPattern = "data-hasavailability=\"(.*)\"";
                var hasAvailabilityRegex   = new Regex(hasAvailabilityPattern, RegexOptions.IgnoreCase);
                var hasAvailabiltyResult   = hasAvailabilityRegex.Matches(content)[0].Groups[1].Value;


                var infoTextPattern = "diningReservationInfoText.*?\">\\n*?(.*?)\\n*<";
                var infoTextRegex   = new Regex(infoTextPattern, RegexOptions.IgnoreCase);
                var infoTextResult  = infoTextRegex.Matches(content)[0].Groups[1].Value;
                returnValue.InfoText = infoTextResult;

                var infoTitlePattern = "diningReservationInfoTitle\\snotAvailable\">\\n*(.*?)\\n*?<";
                var infoTitelRegex   = new Regex(infoTitlePattern, RegexOptions.IgnoreCase);
                var infoTitleMatches = infoTitelRegex.Matches(content);
                if (infoTitleMatches.Count > 0)
                {
                    returnValue.InfoTitle = infoTitleMatches[0].Groups[1].Value;
                }

                if (hasAvailabiltyResult == "1")
                {
                    var pattern = ".*?href=\"(.*\\/)\">.*\\s.*\\s.*>(.*)<";

                    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                    MatchCollection matches = rgx.Matches(content);
                    foreach (var eachTime in matches.OfType <Match>())
                    {
                        returnValue.TimesAvailabile.Add(new TimesAvail()
                        {
                            URL  = eachTime.Groups[1].Value,
                            Time = eachTime.Groups[2].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(returnValue);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchDate">Date in yyyy-MM-dd format</param>
        /// <param name="searchTime">Time in HH:mm military format</param>
        /// <param name="partySize">Size of the party</param>
        /// <returns></returns>
        public static async Task <Availability[]> GetTimesAsync(string searchDate, string searchTime, int partySize)
        {
            try
            {
                var token = await GetAccessToken();

                var uri     = $"https://disneyworld.disney.go.com/api/wdpro/explorer-service/public/finder/dining-availability/80007798;entityType=destination?searchDate={searchDate}&partySize={partySize}&searchTime={searchTime}";//22%3A00";
                var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, new Uri(uri));
                request.Headers.Add("Authorization", "BEARER " + token.access_token);
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                request.Headers.Add("Referer", "https://disneyworld.disney.go.com/dining/");
                request.Headers.Add("type", "dining");

                var agentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";

                var client = new Windows.Web.Http.HttpClient();
                client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
                client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
                client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");
                client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-us");
                client.DefaultRequestHeaders.UserAgent.ParseAdd(agentString);
                try
                {
                    var test = await client.SendRequestAsync(request);

                    var content = test.Content.ToString();


                    var avail = (from each in JObject.Parse(content)["availability"]
                                 where ((JProperty)each).Name.Contains("rest") || ((JProperty)each).Name.Contains("Dining-Event")
                                 orderby((JProperty)each).Name ascending
                                 select new Availability
                    {
                        Restaurant = RestaurantList.FirstOrDefault(x => x.EntityId == int.Parse(((JProperty)each).Name.Split(';')[0])),
                        Offers = (from eachAvail in each.Values("availableTimes")
                                  from eachOffer in eachAvail.Values("offers").Values()
                                  select new Offer
                        {
                            TimeString = eachOffer["time"].Value <string>(),
                            DateAndTime = eachOffer["dateTime"].Value <DateTime>(),
                        }).ToList(),
                    }).OrderBy(x => x.Restaurant?.Name).ToArray();

                    var unknownRestaurants = (from each in JObject.Parse(content)["availability"]
                                              where ((JProperty)each).Name.Contains("rest") || ((JProperty)each).Name.Contains("Dining-Event")
                                              orderby((JProperty)each).Name ascending
                                              select new Availability
                    {
                        RestaurantId = int.Parse(((JProperty)each).Name.Split(';')[0]),
                        Restaurant = RestaurantList.FirstOrDefault(x => x.EntityId == int.Parse(((JProperty)each).Name.Split(';')[0])),
                        Offers = (from eachAvail in each.Values("availableTimes")
                                  from eachOffer in eachAvail.Values("offers").Values()
                                  select new Offer
                        {
                            TimeString = eachOffer["time"].Value <string>(),
                            DateAndTime = eachOffer["dateTime"].Value <DateTime>(),
                        }).ToList(),
                    }).Where(x => x.Restaurant == null).ToArray();

                    return(avail);
                }
                //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);
            }
            catch (Exception ex)
            {
                var xxxx = 1;
                throw;
            }
        }
        private async Task <string> SetToastNotification(string message)
        {
            try
            {
                try
                {
                    string secret = "J82cI9OC/my9+a1vw2MmGrAj87YB6nwK";
                    string sid    = "ms-app://s-1-15-2-4128186160-1681326203-2788279282-2432225568-1896386270-4060788042-1141638401";
                    if (tokenaccess == "")
                    {
                        OAuthToken oAuthToken = new OAuthToken();
                        Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
                        var urlEncodedSecret = System.Net.WebUtility.UrlEncode(secret);
                        var urlEncodedSid    = System.Net.WebUtility.UrlEncode(sid);
                        var body             =
                            String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);
                        Uri requestUri         = new Uri("https://login.live.com/accesstoken.srf");
                        HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), requestUri);
                        msg.Content = new HttpStringContent(body);
                        msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
                        HttpResponseMessage HttpResponseMessage = await httpClient.SendRequestAsync(msg).AsTask();

                        if (HttpResponseMessage.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                        {
                            var resultsss = await HttpResponseMessage.Content.ReadAsStringAsync();

                            oAuthToken  = GetOAuthTokenFromJson(resultsss);
                            tokenaccess = oAuthToken.AccessToken;
                        }
                    }
                    await PostToWns(channel.Uri, tokenaccess, "Push Notification: " + message + ", " + DateTime.Now.ToString(), "wns/toast", "text/xml");

                    return(await Task.FromResult("true"));

                    //Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
                    ////https://{namespace}.servicebus.windows.net/{NotificationHub}/messages/?api-version=2015-01
                    //Uri requestUri = new Uri("https://tomtestnotification.servicebus.windows.net/" + hub.Path + "/messages/?api-version=2015-01");
                    //HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), requestUri);
                    //string templateBodyWNS = "<?xml version=\"1.0\" encoding=\"utf - 8\"?><toast> <visual lang = \"en-US\"><binding template = \"ToastText01\"><text id = \"1\"> This is my toast message for UWP!</text ></binding></visual></toast>";
                    //msg.Content = new HttpStringContent(templateBodyWNS);
                    //msg.Headers.Add("ServiceBusNotification-Format", "windows");
                    //msg.Headers.Add("Authorization", String.Format("Bearer {0}", hub.AccessToken));
                    //msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/xml");
                    //HttpResponseMessage HttpResponseMessage = await httpClient.SendRequestAsync(msg).AsTask();
                    //if (HttpResponseMessage.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                    //{
                    //    var resultsss = await HttpResponseMessage.Content.ReadAsStringAsync();
                    //    return await Task.FromResult("true");
                    //}
                    //else
                    //{
                    //    return await Task.FromResult("false");
                    //}
                }
                catch
                {
                    return(await Task.FromResult("false"));
                }
            }
            catch (Exception ex)
            {
                return(await Task.FromResult("false"));
            }
        }
        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 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(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");
            }          
          
        }
        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();
        }
示例#42
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        ///

        public async void postXMLData1()
        {
            string uri          = "http://111.93.131.112/biws/buswebservice"; // some xml string
            Uri    _url         = new Uri(uri, UriKind.RelativeOrAbsolute);
            string franchUserID = "?";
            string password     = "******";
            int    userID       = 474;
            string userKey      = "?";
            string username     = "******";
            string userRole     = "?";
            string userStatus   = "?";
            int    usertype     = 101;

            string FromplaceName = txtBFromLocationT.Text;
            string ToplaceName   = txtBToLocationT.Text;
            string placeIDFrom   = txtBFromID.Text;
            string placeCodeFrom = txtBFromCode.Text;
            string placeIDTo     = txtBToID.Text;
            string placeCodeTo   = txtBToCode.Text;

            string d = txtBDateTab.Text;

            System.DateTime dt = System.DateTime.ParseExact(d, "dd MMM yyyy", CultureInfo.InvariantCulture);
            txtBDateTab.Text = dt.ToString("dd/MM/yyyy");

            string Date = txtBDateTab.Text;

            WebServiceClassLiberary.Class1 listings = new WebServiceClassLiberary.Class1();
            XDocument element    = listings.getservice(franchUserID, password, userID, userKey, username, userRole, userStatus, usertype, placeIDFrom, placeCodeFrom, FromplaceName, placeIDTo, placeCodeTo, ToplaceName, Date);
            string    stringXml  = 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(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);

            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").Attribute("placeID").Value,
                //placeIDto = x.Element("biToPlace").Attribute("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,
                stuID          = x.Element("stuID").Value,
                tripCode       = x.Element("tripCode").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.stuID           = item.stuID;
                gas.tripCode        = item.tripCode;
                gas.viaPlaces       = item.viaPlaces;
                availableservice.Add(gas);
            }
            ListMenuItems.ItemsSource = sdata;
        }
        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;           
        }
        /// <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;
            }
        }