Beispiel #1
1
		static public async Task<string> SendGetRequest ( string address )
		{
			var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter ();
			httpFilter.CacheControl.ReadBehavior =
				Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
			httpClient = new HttpClient ( httpFilter );
			response = new HttpResponseMessage ();
			string responseText = "";

			//check address
			Uri resourceUri;
			if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
			{
				return "Invalid URI, please re-enter a valid URI";
			}
			if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
			{
				return "Only 'http' and 'https' schemes supported. Please re-enter URI";
			}

			//get
			try
			{
				response = await httpClient.GetAsync ( resourceUri );
				response.EnsureSuccessStatusCode ();
				responseText = await response.Content.ReadAsStringAsync ();
			}
			catch ( Exception ex )
			{
				// Need to convert int HResult to hex string
				responseText = "Error = " + ex.HResult.ToString ( "X" ) + "  Message: " + ex.Message;
			}
			httpClient.Dispose ();
			return responseText;
		}
Beispiel #2
0
        /// <summary>
        ///     Downloads songs from local storage
        /// </summary>
        /// <param name="localIp">IP of the local machine</param>
        async void DownloadFromLocalhost()
        {
            var i = 1;
            // Whatever the localhost ip is
            var    localIp  = "http://192.168.178.18:8888";
            string audioURL = localIp + "/music/" + i + ".mp3";

            while (this.URLExists(audioURL))
            {
                var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                myFilter.AllowUI = false;
                Windows.Web.Http.HttpClient          client = new Windows.Web.Http.HttpClient(myFilter);
                Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(audioURL));

                // Saving a file with the number
                var file = await KnownFolders.MusicLibrary.CreateFileAsync(i + " song.mp3", CreationCollisionOption.ReplaceExisting);

                using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await result.Content.WriteToStreamAsync(filestream);

                    await filestream.FlushAsync();
                }

                i++;
                audioURL = localIp + "/music/" + i + ".mp3";  //"http://docs.google.com/uc?export=download&id=0B6u8YFm5Y0GeLXRtd2Z6X0RjNTA";
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Gets the web based configuration info and returns it
        /// </summary>
        /// <returns>WebConfiguration info</returns>
        public static async Task <WebConfigurationInfo> GetWebConfiguration()
        {
            try
            {
                var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                httpFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;

                //download webconfiguration info
                using (var client = new HttpClient(httpFilter))
                {
                    using (var response = await client.GetAsync(new Uri(WebConfigurationFileUrl), HttpCompletionOption.ResponseContentRead))
                    {
                        string json = await response.Content.ReadAsStringAsync();

                        if (WebConfigurationInfo.SetInstance(json))
                        {
                            return(WebConfigurationInfo.Instance);
                        }
                    }
                }

                return(null);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #4
0
        public HttpClientHandler()
        {
            _rtFilter        = new RTHttpBaseProtocolFilter();
            _handlerToFilter = new HttpHandlerToFilter(_rtFilter);
            _handlerToFilter.RequestMessageLookupKey             = RequestMessageLookupKey;
            _handlerToFilter.SavedExceptionDispatchInfoLookupKey = SavedExceptionDispatchInfoLookupKey;
            _diagnosticsPipeline = new DiagnosticsHandler(_handlerToFilter);

            _clientCertificateOptions = ClientCertificateOption.Manual;

            // Always turn off WinRT cookie processing if the WinRT API supports turning it off.
            // Use .NET CookieContainer handling only.
            if (RTCookieUsageBehaviorSupported)
            {
                _rtFilter.CookieUsageBehavior = RTHttpCookieUsageBehavior.NoCookies;
            }

            _useCookies      = true;                  // deal with cookies by default.
            _cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.

            // Managed at this layer for granularity, but uses the desktop default.
            _rtFilter.AutomaticDecompression = false;
            _automaticDecompression          = DecompressionMethods.None;

            // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
            _rtFilter.AllowUI = false;

            // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
            // To preserve app-compat, we turn off caching in the WinRT HttpClient APIs.
            _rtFilter.CacheControl.ReadBehavior = RTNoCacheSupported ?
                                                  RTHttpCacheReadBehavior.NoCache : RTHttpCacheReadBehavior.MostRecent;
            _rtFilter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
        }
Beispiel #5
0
        public static async Task <ObservableCollection <WebResult> > GetResultsForQuery(string query)
        {
            string queryParams = "Web?Query=%27" + query + "%27&$format=json";
            string searchUri   = BING_SEARCH_URI + queryParams;
            var    filter      = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            filter.AllowUI          = false;
            filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(searchUri, "empty", BING_SEARCH_API_KEY);
            JsonArray jsonResults;

            using (var client = new HttpClient(filter))
            {
                string response = await client.GetStringAsync(new Uri(searchUri));

                JsonObject obj = JsonObject.Parse(response);
                jsonResults = obj.GetNamedObject("d").GetNamedArray("results");
            }

            var results = new ObservableCollection <WebResult>();

            for (var i = 0; i < jsonResults.Count; i++)
            {
                var    obj         = jsonResults.GetObjectAt((uint)i);
                string articleText = "";
                results.Add(new WebResult(
                                obj.GetNamedString("ID"),
                                obj.GetNamedString("Title"),
                                obj.GetNamedString("Description"),
                                obj.GetNamedString("Url"),
                                articleText
                                ));
            }

            return(results);
        }
Beispiel #6
0
        public HttpClientHandler()
        {
            _rtFilter            = new RTHttpBaseProtocolFilter();
            _handlerToFilter     = new HttpHandlerToFilter(_rtFilter);
            _diagnosticsPipeline = new DiagnosticsHandler(_handlerToFilter);

            _clientCertificateOptions = ClientCertificateOption.Manual;

            InitRTCookieUsageBehavior();

            _useCookies      = true;                  // deal with cookies by default.
            _cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.

            // Managed at this layer for granularity, but uses the desktop default.
            _rtFilter.AutomaticDecompression = false;
            _automaticDecompression          = DecompressionMethods.None;

            // Set initial proxy credentials based on default system proxy.
            SetProxyCredential(null);

            // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
            _rtFilter.AllowUI = false;

            // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
            // To preserve app-compat, we turn off caching (as much as possible) in the WinRT HttpClient APIs.
            // TODO (#7877): use RTHttpCacheReadBehavior.NoCache when available in the next version of WinRT HttpClient API.
            _rtFilter.CacheControl.ReadBehavior  = RTHttpCacheReadBehavior.MostRecent;
            _rtFilter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
        }
Beispiel #7
0
        private HttpCookieCollection GetSavedCookiesInWebView()
        {
            Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookies = filter.CookieManager.GetCookies(new System.Uri("http://www.dailymotion.com"));

            return(cookies);
        }
Beispiel #8
0
        public async static Task <HttpResponseMessage> SendHeadRequestAsync(Uri url)
        {
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            using (var httpClient = new HttpClient(filter))
            {
                try
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);

                    HttpResponseMessage response = await httpClient.SendRequestAsync(request);

#if DEBUG
                    Logger.Log("Sending head request with: " + url);
#endif
                    return(response);
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + e.HResult.ToString("x"));
#endif
                    return(null);
                }
            }
        }
Beispiel #9
0
        public async static System.Threading.Tasks.Task <IBuffer> DownloadBufferAsync(Uri url)
        {
            //Turn off cache for live playback
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            using (var httpClient = new HttpClient(filter))
            {
                try
                {
                    var buffer = await httpClient.GetBufferAsync(url);

#if DEBUG
                    Logger.Log("GetBufferAsync suceeded for url: " + url);
#endif
                    return(buffer);
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + e.HResult.ToString("x"));
#endif
                    return(null);
                }
            }
        }
        public void LoadUrl(string url)
        {
            Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);

            if (!uri.IsAbsoluteUri)
            {
                uri = new Uri(LocalScheme + url, UriKind.RelativeOrAbsolute);
            }

            if (Element.Cookies?.Count > 0)
            {
                //Set the Cookies...
                var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                foreach (Cookie cookie in Element.Cookies.GetCookies(uri))
                {
                    HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Domain, cookie.Path);
                    httpCookie.Value = cookie.Value;
                    filter.CookieManager.SetCookie(httpCookie, false);
                }
                var httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri);
                Control.NavigateWithHttpRequestMessage(httpRequestMessage);
            }
            else
            {
                //No Cookies so just navigate...
                Control.Source = uri;
            }
        }
Beispiel #11
0
        private void getMode()
        {
            //string query = "if(document.cookie.match('(^|;)\\s*night_mode\\s*=\\s*([^;]+)')){NotifyApp.getMode(document.cookie.match('(^|;)\\s*night_mode\\s*=\\s*([^;]+)').pop())}";
            //string query = "var dkmd = document.cookie.match('(^|;)\\s*night_mode\\s*=\\s*([^;]+)').pop();NotifyApp.getMode(dkmd)";
            //webView.InvokeScriptAsync("eval", new[] { query });
            var htt = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cm  = htt.CookieManager;
            var cc  = cm.GetCookies(new Uri("https://mobile.twitter.com"));

            foreach (var c in cc)
            {
                if (c.Name == "night_mode")
                {
                    if (c.Value == "1")
                    {
                        if (((Frame)Window.Current.Content).RequestedTheme != ElementTheme.Dark)
                        {
                            ((Frame)Window.Current.Content).RequestedTheme = ElementTheme.Dark;
                        }
                    }
                    else
                    {
                        if (((Frame)Window.Current.Content).RequestedTheme == ElementTheme.Dark)
                        {
                            ((Frame)Window.Current.Content).RequestedTheme = ElementTheme.Light;
                        }
                    }
                }
            }
        }
Beispiel #12
0
        public static async Task <ObservableCollection <SynonymResult> > GetResultsForQuery(string query)
        {
            string queryParams = "GetSynonyms?Query=%27" + query + "%27&$format=json";
            string searchUri   = API_URI + queryParams;
            var    filter      = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            filter.AllowUI          = false;
            filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(searchUri, "empty", API_KEY);
            JsonArray jsonResults;

            using (var client = new HttpClient(filter))
            {
                string response = await client.GetStringAsync(new Uri(searchUri));

                JsonObject obj = JsonObject.Parse(response);
                jsonResults = obj.GetNamedObject("d").GetNamedArray("results");
            }

            var results = new ObservableCollection <SynonymResult>();

            for (uint i = 0; i < jsonResults.Count; i++)
            {
                var obj = jsonResults.GetObjectAt(i);
                results.Add(new SynonymResult(obj.GetNamedString("Synonym")));
            }
            return(results);
        }
        private RTHttpBaseProtocolFilter CreateFilter()
        {
            var filter = new RTHttpBaseProtocolFilter();

            // Always turn off WinRT cookie processing if the WinRT API supports turning it off.
            // Use .NET CookieContainer handling only.
            if (RTCookieUsageBehaviorSupported)
            {
                filter.CookieUsageBehavior = RTHttpCookieUsageBehavior.NoCookies;
            }

            // Handle redirections at the .NET layer so that we can see cookies on redirect responses
            // and have control of the number of redirections allowed.
            filter.AllowAutoRedirect = false;

            filter.AutomaticDecompression = false;

            // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
            filter.AllowUI = false;

            // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
            // To preserve app-compat, we turn off caching in the WinRT HttpClient APIs.
            filter.CacheControl.ReadBehavior = RTNoCacheSupported ?
                                               RTHttpCacheReadBehavior.NoCache : RTHttpCacheReadBehavior.MostRecent;
            filter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;

            return(filter);
        }
Beispiel #14
0
        public async static Task<HttpResponseMessage> SendHeadRequestAsync(Uri url)
        {
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            using (var httpClient = new HttpClient(filter))
            {
                try
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);

                    HttpResponseMessage response = await httpClient.SendRequestAsync(request);
#if DEBUG
                    Logger.Log("Sending head request with: " + url);
#endif
                    return response;
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + e.HResult.ToString("x"));
#endif
                    return null;
                }
            }
        }
Beispiel #15
0
        public async static System.Threading.Tasks.Task <IBuffer> DownloadBufferAsync(Uri url)
        {
            //Turn off cache for live playback
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            using (var httpClient = new HttpClient(filter))
            {
                HttpGetBufferResult result = await httpClient.TryGetBufferAsync(url);

                if (result.Succeeded)
                {
#if DEBUG
                    Logger.Log("GetBufferAsync suceeded for url: " + url);
#endif
                    return(result.Value);
                }
                else
                {
#if DEBUG
                    Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + result.ExtendedError.HResult.ToString("x"));
#endif
                    return(null);
                }
            }
        }
Beispiel #16
0
        public async static Task <HttpResponseMessage> SendHeadRequestAsync(Uri url)
        {
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            using (var httpClient = new HttpClient(filter))
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);

                HttpRequestResult result = await httpClient.TrySendRequestAsync(request);

                if (result.Succeeded)
                {
#if DEBUG
                    Logger.Log("Sending head request with: " + url);
#endif
                    return(result.ResponseMessage);
                }
                else
                {
#if DEBUG
                    Logger.Log("SendHeadRequestAsync exception for url: " + url + " HRESULT 0x" + result.ExtendedError.HResult.ToString("x"));
#endif
                    return(null);
                }
            }
        }
        private static async Task <string> GetHtmlFromUri(Uri uri)
        {
            string html;

            Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.CacheControl.ReadBehavior =
                Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;


            using (var client = new HttpClient(filter))
            {
                using (var res = await client.GetAsync(uri))
                {
                    if (res.IsSuccessStatusCode)
                    {
                        html = await ParseHTML(res);
                    }
                    else
                    {
                        throw new Exception(res.StatusCode + ":" + res.ReasonPhrase);
                    }
                }
            }

            return(html);
        }
Beispiel #18
0
        public static async Task<ObservableCollection<WebResult>> GetResultsForQuery(string query) {
            string queryParams = "Web?Query=%27" + query + "%27&$format=json";
            string searchUri = BING_SEARCH_URI + queryParams;
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.AllowUI = false;
            filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(searchUri, "empty", BING_SEARCH_API_KEY);
            JsonArray jsonResults;
            using (var client = new HttpClient(filter))
            {
                string response = await client.GetStringAsync(new Uri(searchUri));
                JsonObject obj = JsonObject.Parse(response);
                jsonResults = obj.GetNamedObject("d").GetNamedArray("results");
            }

            var results = new ObservableCollection<WebResult>();
            for (var i = 0; i < jsonResults.Count; i++) {
                var obj = jsonResults.GetObjectAt((uint)i);
                string articleText = "";
                results.Add(new WebResult(
                    obj.GetNamedString("ID"),
                    obj.GetNamedString("Title"),
                    obj.GetNamedString("Description"),
                    obj.GetNamedString("Url"),
                    articleText
                ));
            }

            return results;
        }
Beispiel #19
0
        private async Task <string> AttemptLogin()
        {
            var filter        = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookieManager = filter.CookieManager;

            client = new HttpClient(filter);

            Uri loginUri = new Uri(roamingSettings.Values["panelurl"] + "/auth");
            Dictionary <string, string> pairs = new Dictionary <string, string>();

            pairs.Add("username", (string)roamingSettings.Values["username"]);

            pairs.Add("password", (string)roamingSettings.Values["password"]);

            HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
            HttpResponseMessage       response    = await client.PostAsync(loginUri, formContent);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                var responseCookies = cookieManager.GetCookies(loginUri);

                foreach (HttpCookie cookie in responseCookies)
                {
                    if (cookie.Name == "loggedin")
                    {
                        return(cookie.Value);
                    }
                }
            }
            return("");
        }
Beispiel #20
0
        private RTHttpBaseProtocolFilter InitFilterWithNoCredentials()
        {
            RTHttpBaseProtocolFilter filter = new RTHttpBaseProtocolFilter();

            filter.AllowAutoRedirect          = _filter.AllowAutoRedirect;
            filter.AllowUI                    = _filter.AllowUI;
            filter.AutomaticDecompression     = _filter.AutomaticDecompression;
            filter.CacheControl.ReadBehavior  = _filter.CacheControl.ReadBehavior;
            filter.CacheControl.WriteBehavior = _filter.CacheControl.WriteBehavior;

            if (HttpClientHandler.RTCookieUsageBehaviorSupported)
            {
                filter.CookieUsageBehavior = _filter.CookieUsageBehavior;
            }

            filter.MaxConnectionsPerServer = _filter.MaxConnectionsPerServer;
            filter.MaxVersion = _filter.MaxVersion;
            filter.UseProxy   = _filter.UseProxy;

            if (_handler.ServerCertificateCustomValidationCallback != null)
            {
                foreach (RTChainValidationResult error in _filter.IgnorableServerCertificateErrors)
                {
                    filter.IgnorableServerCertificateErrors.Add(error);
                }

                filter.ServerCustomValidationRequested += _handler.RTServerCertificateCallback;
            }

            return(filter);
        }
        public RTHttpClientHandler()
        {
            _rtFilter        = new RTHttpBaseProtocolFilter();
            _handlerToFilter = new RTHttpHandlerToFilter(_rtFilter);
            InnerHandler     = _handlerToFilter;

            // TODO: Fix up client certificate options
            _clientCertificates = new X509Certificate2Collection();

            InitRTCookieUsageBehavior();

            _useCookies      = true;                  // deal with cookies by default.
            _cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.

            // Managed at this layer for granularity, but uses the desktop default.
            _rtFilter.AutomaticDecompression = false;
            _automaticDecompression          = DecompressionMethods.None;

            // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
            _rtFilter.AllowUI = false;

            // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
            // To preserve app-compat, we turn off caching (as much as possible) in the WinRT HttpClient APIs.
            _rtFilter.CacheControl.ReadBehavior  = RTHttpCacheReadBehavior.MostRecent;
            _rtFilter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
        }
Beispiel #22
0
        public PivotPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            this.navigationHelper            = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            _syncContext = SynchronizationContext.Current;

            var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            httpFilter.CacheControl.ReadBehavior =
                Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;

            client = new HttpClient(httpFilter);

            fireflies = new FireflyCollection();
            //addSampleFireflies();
            lstFireflies.ItemsSource = fireflies;

            nodes = new NodeCollection();
            lstNodes.ItemsSource = nodes;

            getMonitorIPAddress();

            monitorUri = "http://" + monitorIPAddress + ":" + monitorPort + "/";

            //getFirefliesFromMonitor();
            //getNodesFromMonitor();
        }
Beispiel #23
0
        public async Task<Tuple<bool, DateTime?>> SetSessionCookie(string login, string password)
        {
            HttpResponseMessage response = null;
            HttpRequestMessage request = null;

            using (var httpClient = new HttpClient())
            {
                request = new HttpRequestMessage(HttpMethod.Post, new Uri(Const.UrlLogin));
                request.Content = new HttpFormUrlEncodedContent(new[] {
                    new KeyValuePair<string, string>("what", "login"),
                    new KeyValuePair<string, string>("login", login),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("persistent", "true"),
                });

                try
                {
                    response = await httpClient.SendRequestAsync(request);
                }
                catch (Exception)
                {
                    return new Tuple<bool, DateTime?>(false, null);
                }
            }

            var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var expireDate = httpFilter.CookieManager.GetCookies(new Uri(Const.UrlFullAddress)).First().Expires ?? DateTime.Now;

            return new Tuple<bool, DateTime?>(response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok, expireDate.DateTime);
        }
Beispiel #24
0
        private HttpCookieCollection GetBrowserCookie(Uri targetUri)
        {
            var httpBaseProtocolFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookieManager          = httpBaseProtocolFilter.CookieManager;
            var cookieCollection       = cookieManager.GetCookies(targetUri);

            return(cookieCollection);
        }
 public void ClearCookies()
 {
     var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
     var cookies = filter.CookieManager;
     var jar = cookies.GetCookies(new Uri("https://www.facebook.com"));
     foreach (var c in jar)
         cookies.DeleteCookie(c);
 }
Beispiel #26
0
        /// <summary>
        /// setting a cookie in our webview
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private void SetCookieInWebView(string key, string value)
        {
            Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            Windows.Web.Http.HttpCookie cookie = new Windows.Web.Http.HttpCookie(key, ".dailymotion.com", "/");
            cookie.Value = value;

            filter.CookieManager.SetCookie(cookie, false);
        }
Beispiel #27
0
        HttpCookieCollection GetCookiesFromNativeStore(string url)
        {
            var             uri             = CreateUriForCookies(url);
            CookieContainer existingCookies = new CookieContainer();
            var             filter          = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var             nativeCookies   = filter.CookieManager.GetCookies(uri);

            return(nativeCookies);
        }
Beispiel #28
0
        private async void loginButton_Click(object sender, RoutedEventArgs e)
        {
            var        filter        = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var        cookieManager = filter.CookieManager;
            HttpClient loginClient   = new HttpClient(filter);

            Uri loginUri = new Uri(panelUrl + "/auth");
            Dictionary <string, string> pairs = new Dictionary <string, string>();

            pairs.Add("username", loginUser.Text);
            pairs.Add("password", loginPass.Password);

            HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);

            try
            {
                HttpResponseMessage response = await loginClient.PostAsync(loginUri, formContent);

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    if (content.Contains("SUCCESS"))
                    {
                        roamingSettings.Values["username"]    = loginUser.Text;
                        roamingSettings.Values["password"]    = loginPass.Password;
                        roamingSettings.Values["panelurl"]    = panelUrl.ToString();
                        roamingSettings.Values["domain"]      = panelUrl.Host;
                        roamingSettings.Values["ssl"]         = sslSwitch.IsOn;
                        roamingSettings.Values["hasloggedin"] = true;

                        var dialog = new MessageDialog("Logged into the panel!");
                        await dialog.ShowAsync();

                        if (Frame.CanGoBack)
                        {
                            Frame.GoBack();
                        }
                    }
                    else if (content.Contains("FAIL"))
                    {
                        var dialog = new MessageDialog(content);
                        await dialog.ShowAsync();
                    }
                    else
                    {
                        var dialog = new MessageDialog("We couldn't find a panel to log into");
                        await dialog.ShowAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                ShowToast(ContentRoot, "Unknown error when logging in.");
            }
        }
        private void CleanDataButton_Click(object sender, RoutedEventArgs e)
        {
            ApplicationData.Current.LocalSettings.Values.Clear();
            var cookieManager = new Windows.Web.Http.Filters.HttpBaseProtocolFilter().CookieManager;

            foreach (var item in cookieManager.GetCookies(new Uri("http://account.coolapk.com")))
            {
                cookieManager.DeleteCookie(item);
            }
        }
        internal HttpHandlerToFilter(RTHttpBaseProtocolFilter filter)
        {
            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            _next = filter;
            _filterMaxVersionSet = 0;
        }
Beispiel #31
0
        internal RTHttpHandlerToFilter(RTHttpBaseProtocolFilter filter)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("filter");
            }

            _next = filter;
            _filterMaxVersionSet = 0;
        }
Beispiel #32
0
        public void DeleteSessionCookie()
        {
            var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();

            httpFilter.CookieManager.DeleteCookie(new HttpCookie(Const.CookieSessionName, Const.UrlDomain, "/"));
            httpFilter.CookieManager.DeleteCookie(new HttpCookie(Const.CookieSessionName2, Const.UrlDomain, "/"));

            httpFilter.CookieManager.DeleteCookie(new HttpCookie(Const.CookieSessionName, Const.UrlDomain2, "/"));
            httpFilter.CookieManager.DeleteCookie(new HttpCookie(Const.CookieSessionName2, Const.UrlDomain2, "/"));

        }
Beispiel #33
0
        public void ClearCookie()
        {
            Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookieManager = myFilter.CookieManager;
            HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("https://login.live.com"));

            foreach (HttpCookie cookie in myCookieJar)
            {
                cookieManager.DeleteCookie(cookie);
            }
        }
Beispiel #34
0
        public static void Logout()
        {
            var cookieManager = new Windows.Web.Http.Filters.HttpBaseProtocolFilter().CookieManager;

            foreach (var item in cookieManager.GetCookies(new Uri("http://coolapk.com")))
            {
                cookieManager.DeleteCookie(item);
            }
            Set(Uid, string.Empty);
            UIHelper.NotificationNums.ClearNums();
        }
Beispiel #35
0
        public static void Logout()
        {
            var cookieManager = new Windows.Web.Http.Filters.HttpBaseProtocolFilter().CookieManager;

            foreach (var item in cookieManager.GetCookies(new Uri("http://coolapk.com")))
            {
                cookieManager.DeleteCookie(item);
            }
            Set("Uid", string.Empty);
            Tools.mainPage.UserAvatar = null;
        }
Beispiel #36
0
        public static void ClearCookiesFor(Uri uri)
        {
            var httpFilter    = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookieManager = httpFilter.CookieManager;
            var myCookieJar   = cookieManager.GetCookies(uri);

            foreach (var cookie in myCookieJar)
            {
                cookieManager.DeleteCookie(cookie);
            }
        }
Beispiel #37
0
        public void ClearCookies()
        {
            var filter  = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookies = filter.CookieManager;
            var jar     = cookies.GetCookies(new Uri("https://www.facebook.com"));

            foreach (var c in jar)
            {
                cookies.DeleteCookie(c);
            }
        }
Beispiel #38
0
 //Utils
 static void cleanCookies()
 {
     //Remove cookies before anything
     Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
     var cookieManager = myFilter.CookieManager;
     Windows.Web.Http.HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("http://forum.hardware.fr"));
     foreach (Windows.Web.Http.HttpCookie cookie in myCookieJar)
     {
         cookieManager.DeleteCookie(cookie);
     }
     //--
 }
        protected async void UpdateIfUriIsInCache(Uri uri, TextBlock cacheStatusTextBlock)
        {
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.OnlyFromCache;

            var httpClient = new Windows.Web.Http.HttpClient(filter);
            var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri);

            try
            {
                await httpClient.SendRequestAsync(request);
                cacheStatusTextBlock.Text = "Yes";
                cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Green);
            }
            catch
            {
                cacheStatusTextBlock.Text = "No";
                cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red); 
            }
        }
Beispiel #40
0
        public async static System.Threading.Tasks.Task<IBuffer> DownloadBufferAsync(Uri url)
        {
            //Turn off cache for live playback
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
            using (var httpClient = new HttpClient(filter))
            {
                try
                {
                    var buffer = await httpClient.GetBufferAsync(url);
#if DEBUG
                    Logger.Log("GetBufferAsync suceeded for url: " + url);
#endif
                    return buffer;
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + e.HResult.ToString("x"));
#endif
                    return null;
                }
            }
        }
Beispiel #41
0
        public static void ClearCookies()
        {
#if SILVERLIGHT

            var webBrowser = new WebBrowser();

            webBrowser.ClearCookiesAsync();

#else

            Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookieManager = myFilter.CookieManager;
            HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("https://vk.com"));
            foreach (HttpCookie cookie in myCookieJar)
            {
                cookieManager.DeleteCookie(cookie);
            }

            myCookieJar = cookieManager.GetCookies(new Uri("https://login.vk.com"));
            foreach (HttpCookie cookie in myCookieJar)
            {
                cookieManager.DeleteCookie(cookie);
            }
#endif
        }
Beispiel #42
0
        private OAuth2Client GetHttpClient(bool useSecureLogin)
        {
            var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
            filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);

            UriBuilder uriBuilder = new UriBuilder(this.TokenEndpointAddress);
            if (useSecureLogin)
            {
                if (string.Compare(uriBuilder.Scheme, "http", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    uriBuilder.Scheme = "https";
                    uriBuilder.Port = 443;
                }
            }

            return new OAuth2Client(
                uriBuilder.Uri,
                "BSEtunes",
                OAuthClientSercret,
                new WindowsRuntime.HttpClientFilters.WinRtHttpClientHandler(filter));
        }
Beispiel #43
0
        public static Task<bool> BeginAuthentication(this Account account, bool firstConnection)
        {
            Debug.WriteLine("Begin connection");
            var tcs = new TaskCompletionSource<bool>();

            //Remove cookies before anything
            Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var cookieManager = myFilter.CookieManager;
            Windows.Web.Http.HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("http://forum.hardware.fr"));
            foreach (Windows.Web.Http.HttpCookie cookie in myCookieJar)
            {
                cookieManager.DeleteCookie(cookie);
            }
            //--

            var pseudo = account.Pseudo;
            var pseudoEncoded = WebUtility.UrlEncode(pseudo);
            var password = account.Password;
            var cookieContainer = new CookieContainer();

#warning "this must be rewritten using HttpClientHelper"

            var request = WebRequest.CreateHttp(HFRUrl.ForumUrl + HFRUrl.ConnectUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.CookieContainer = cookieContainer;
            request.BeginGetRequestStream(ar =>
            {
                try
                {
                    var postStream = request.EndGetRequestStream(ar);
                    var postData = "&pseudo=" + pseudoEncoded + "&password="******"cookieCount :"+ cookieContainer.Count);

                        switch (cookieContainer.Count)
                        {
                            case 0:
                                #warning "no UI feedback to warn user that something went wrong"
                                tcs.SetResult(false);
                                break;

                            case 3:
                                Debug.WriteLine("Connection succeed");
                                account.CookieContainer = JsonConvert.SerializeObject(cookieContainer.GetCookies(new Uri("http://forum.hardware.fr")).OfType<Cookie>().ToList());
                                
                                if (firstConnection)
                                    await GetAvatar(account);
                                tcs.SetResult(true);
                                break;
                        }
                    }, request);
                }
                catch (WebException exception)
                {
                    Debug.WriteLine("Failed to connect. WebException error");
                    tcs.SetResult(false);
                }
            }, request);
            return tcs.Task;
        }
        private HttpRequestMessage GetMessageForUrl(string url)
        {
            CookieContainer cookies = new CookieContainer();
            account.Session.AddCookies(cookies);

            Uri baseUri = new Uri(url);
            Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            foreach (Cookie c in cookies.GetCookies(SteamWeb.uri))
            {
                Windows.Web.Http.HttpCookie cookie = new Windows.Web.Http.HttpCookie(c.Name, c.Domain, c.Path);
                cookie.Value = c.Value;
                filter.CookieManager.SetCookie(cookie, false);
            }

            return new HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, baseUri);
        }
Beispiel #45
0
        private async Task<bool> GetMediaDataAsync(string path)
        {
            if (this._groups.Count != 0)
                return false;
            string jsonText = string.Empty;

            if (string.IsNullOrEmpty(path))
            {
                // load the default data
                //If retrieving json from web failed then use embedded json data file.
                if (string.IsNullOrEmpty(jsonText))
                {
                    Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json");

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
                    jsonText = await FileIO.ReadTextAsync(file);
                    MediaDataPath = "ms-appx:///DataModel/MediaData.json";
                }
            }
            else
            {
                if (path.StartsWith("ms-appx://"))
                {
                    Uri dataUri = new Uri(path);

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
                    jsonText = await FileIO.ReadTextAsync(file);
                    MediaDataPath = path;
                }
                else if (path.StartsWith("http://"))
                {
                    try
                    {
                        //Download the json file from the server to configure what content will be dislayed.
                        //You can also modify the local MediaData.json file and delete this code block to test
                        //the local json file
                        string MediaDataFile = path;
                        Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                        filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
                        Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter);
                        Uri httpUri = new Uri(MediaDataFile);
                        jsonText = await http.GetStringAsync(httpUri);
                        MediaDataPath = MediaDataFile;
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
                else
                {
                    try
                    {
                        //Download the json file from the server to configure what content will be dislayed.
                        //You can also modify the local MediaData.json file and delete this code block to test
                        //the local json file
                        string MediaDataFile = path;
                        StorageFile file;
                        file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
                        if (file != null)
                        {
                            jsonText = await FileIO.ReadTextAsync(file);
                            MediaDataPath = MediaDataFile;
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
            }

            if (string.IsNullOrEmpty(jsonText))
                return false;

            try
            {

                JsonObject jsonObject = JsonObject.Parse(jsonText);
                JsonArray jsonArray = jsonObject["Groups"].GetArray();

                foreach (JsonValue groupValue in jsonArray)
                {
                    JsonObject groupObject = groupValue.GetObject();
                    MediaDataGroup group = new MediaDataGroup(groupObject["UniqueId"].GetString(),
                                                                groupObject["Title"].GetString(),
                                                                groupObject["Category"].GetString(),
                                                                groupObject["ImagePath"].GetString(),
                                                                groupObject["Description"].GetString());

                    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                    {
                        JsonObject itemObject = itemValue.GetObject();
                        long timeValue = 0;
                        group.Items.Add(new MediaItem(itemObject["UniqueId"].GetString(),
                                                           itemObject["Comment"].GetString(),
                                                           itemObject["Title"].GetString(),
                                                           itemObject["ImagePath"].GetString(),
                                                           itemObject["Description"].GetString(),
                                                           itemObject["Content"].GetString(),
                                                           itemObject["PosterContent"].GetString(),
                                                           (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0),
                                                           (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0),
                                                           itemObject["PlayReadyUrl"].GetString(),
                                                           itemObject["PlayReadyCustomData"].GetString(),
                                                           itemObject["BackgroundAudio"].GetBoolean()));
                    }
                    this.Groups.Add(group);
                    return true;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
            }
            return false;
        }
Beispiel #46
0
		private async void tmp()
		{
			ApplicationData.Current.LocalSettings.Values["login"] = false;
			Uri urilogin = new Uri("http://222.30.32.10");
			Windows.Web.Http.HttpClient conn = new Windows.Web.Http.HttpClient();
			Windows.Web.Http.HttpResponseMessage res = await conn.GetAsync(urilogin);
			Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
			Windows.Web.Http.HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(urilogin);
			Windows.Web.Http.HttpCookie cookies = cookieCollection[0];
			string cookie = cookies.ToString();
		}
Beispiel #47
0
        public RTHttpClientHandler()
        {
            _rtFilter = new RTHttpBaseProtocolFilter();
            _handlerToFilter = new RTHttpHandlerToFilter(_rtFilter);
            InnerHandler = _handlerToFilter;

            // TODO: Fix up client certificate options
            _clientCertificates = new X509Certificate2Collection();

            InitRTCookieUsageBehavior();

            _useCookies = true; // deal with cookies by default.
            _cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.

            // Managed at this layer for granularity, but uses the desktop default.
            _rtFilter.AutomaticDecompression = false;
            _automaticDecompression = DecompressionMethods.None;

            // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
            _rtFilter.AllowUI = false;

            // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
            // To preserve app-compat, we turn off caching (as much as possible) in the WinRT HttpClient APIs.
            _rtFilter.CacheControl.ReadBehavior = RTHttpCacheReadBehavior.MostRecent;
            _rtFilter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
        }
Beispiel #48
0
        public HttpClientHandler()
        {
            this.rtFilter = new RTHttpBaseProtocolFilter();
            this.handlerToFilter = new HttpHandlerToFilter(this.rtFilter);

            this.clientCertificateOptions = ClientCertificateOption.Manual;

            InitRTCookieUsageBehavior();

            this.useCookies = true; // deal with cookies by default.
            this.cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.

            // Managed at this layer for granularity, but uses the desktop default.
            this.rtFilter.AutomaticDecompression = false;
            this.automaticDecompression = DecompressionMethods.None;

            // Set initial proxy credentials based on default system proxy.
            SetProxyCredential(null);

            // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses.
            this.rtFilter.AllowUI = false;
            
            // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default.
            // To preserve app-compat, we turn off caching (as much as possible) in the WinRT HttpClient APIs.
            // TODO (#7877): use RTHttpCacheReadBehavior.NoCache when available in the next version of WinRT HttpClient API.
            this.rtFilter.CacheControl.ReadBehavior = RTHttpCacheReadBehavior.MostRecent; 
            this.rtFilter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache;
        }
Beispiel #49
0
		static public async Task<string> SendPutRequest ( object data , string address )
		{
			string json = JsonConvert.SerializeObject ( data );
			//string tokenJson = JsonConvert.SerializeObject ( UserData.token );
			//create dictionary
			var dict = new Dictionary<string , string> ();
			dict["data"] = json;

			var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter ();
			httpFilter.CacheControl.ReadBehavior =
				Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
			httpClient = new HttpClient ( httpFilter );
			response = new HttpResponseMessage ();
			string responseText = "";

			//check address
			Uri resourceUri;
			if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
			{
				return "Invalid URI, please re-enter a valid URI";
			}
			if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
			{
				return "Only 'http' and 'https' schemes supported. Please re-enter URI";
			}

			//post
			try
			{
				response = await httpClient.PutAsync ( resourceUri , new HttpFormUrlEncodedContent ( dict ) );
				response.EnsureSuccessStatusCode ();
				responseText = await response.Content.ReadAsStringAsync ();
			}
			catch ( Exception ex )
			{
				// Need to convert int HResult to hex string
				responseText = "Error = " + ex.HResult.ToString ( "X" ) + "  Message: " + ex.Message;
			}
			httpClient.Dispose ();
			return responseText;
		}
 public async static void ClearCookies(LoginOptions loginOptions)
 {
     Frame frame = Window.Current.Content as Frame;
     if (frame != null)
     {
         await frame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
         {
             Uri loginUri = new Uri(ComputeAuthorizationUrl(loginOptions));
             WebView web = new WebView();
             Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
             var cookieManager = myFilter.CookieManager;
             Windows.Web.Http.HttpCookieCollection cookies = cookieManager.GetCookies(loginUri);
             foreach (Windows.Web.Http.HttpCookie cookie in cookies)
             {
                 cookieManager.DeleteCookie(cookie);
             }
         });
     }
 }
Beispiel #51
0
        /// <summary>
        /// Called when the download of a DASH or HLS chunk is requested
        /// </summary>

        private async void AdaptiveMediaSource_DownloadRequested(Windows.Media.Streaming.Adaptive.AdaptiveMediaSource sender, Windows.Media.Streaming.Adaptive.AdaptiveMediaSourceDownloadRequestedEventArgs args)
        {
//            LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString());
            
            var deferral = args.GetDeferral();
            if (deferral != null)
            {
                args.Result.ResourceUri = args.ResourceUri;
                args.Result.ContentType = args.ResourceType.ToString();
                var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
                using (var httpClient = new Windows.Web.Http.HttpClient(filter))
                {
                    try
                    {
                        Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, args.Result.ResourceUri);
                        Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request);
                       // args.Result.ExtendedStatus = (uint)response.StatusCode;
                        if (response.IsSuccessStatusCode)
                        {
                            //args.Result.ExtendedStatus = (uint)response.StatusCode;
                            args.Result.InputStream = await response.Content.ReadAsInputStreamAsync();

                        }
                        else
                            LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " error: " + response.StatusCode.ToString());
                    }
                    catch (Exception e)
                    {
                        LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " exception: " + e.Message);

                    }
//                    LogMessage("DownloadRequested for uri: " + args.ResourceUri.ToString() + " done");
                    deferral.Complete();
                }
            }
            
        }