Inheritance: IWwwFormUrlDecoderRuntimeClass
        /// <summary>
        /// Performs the first step in the OAuth2 workflow and retreives the auth code
        /// </summary>
        /// <param name="authCodeUri">The box api uri to retrieve the auth code. BoxConfig.AuthCodeUri should be used for this field</param>
        /// <param name="redirectUri">The redirect uri that the page will navigate to after granting the auth code</param>
        /// <returns></returns>
        public static async Task<string> GetAuthCode(Uri authCodeUri, Uri redirectUri = null)
        {
            Uri callbackUri = redirectUri == null ? 
                WebAuthenticationBroker.GetCurrentApplicationCallbackUri() :
                redirectUri;

            WebAuthenticationResult war = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                authCodeUri,
                callbackUri);

            switch (war.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                        // grab auth code
                        var response = war.ResponseData;
                        WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(new Uri(response).Query);
                        return decoder.GetFirstValueByName("code");
                case WebAuthenticationStatus.UserCancel:
                        throw new Exception("User Canceled Login");
                case WebAuthenticationStatus.ErrorHttp:
                default:
                    throw new Exception("Error returned by GetAuthCode() : " + war.ResponseStatus.ToString());
            }
        }
        private static IEnumerable<Uri> ExtractDownloadUrls(string source)
        {
            #if NETFX_CORE
            string urlMap = new WwwFormUrlDecoder(source).GetFirstValueByName("url_encoded_fmt_stream_map");
            #else
            string urlMap = HttpUtility.ParseQueryString(source).Get("url_encoded_fmt_stream_map");
            #endif

            string[] splitByUrls = urlMap.Split(',');

            foreach (string s in splitByUrls)
            {
            #if NETFX_CORE
                var decoder = new WwwFormUrlDecoder(s);
                string url = string.Format("{0}&fallback_host={1}&signature={2}",
                    decoder.GetFirstValueByName("url"),
                    decoder.GetFirstValueByName("fallback_host"),
                    decoder.GetFirstValueByName("sig"));

                url = WebUtility.UrlDecode(url);
                url = WebUtility.UrlDecode(url);

            #else
                var queries = HttpUtility.ParseQueryString(s);
                string url = string.Format("{0}&fallback_host={1}&signature={2}", queries["url"], queries["fallback_host"], queries["sig"]);

                url = HttpUtility.UrlDecode(url);
                url = HttpUtility.UrlDecode(url);
            #endif
                yield return new Uri(url);
            }
        }
        private async void WebViewer_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            // Check if new location is redirect uri
            if (args.Uri.AbsoluteUri.IndexOf(App.RedirectUri) == 0)
            {
                // Get parameters
                var encoder = new WwwFormUrlDecoder(args.Uri.AbsoluteUri.Replace('#', '&')); // Replacing # with ? to make GetFirstValueByName() work
                var accessToken = encoder.GetFirstValueByName("access_token");
                var expires = encoder.GetFirstValueByName("expires");
                if (!String.IsNullOrEmpty(accessToken))
                {
                    // Success
                    App.AccessToken = accessToken;
                    App.Expires = expires;

                    Frame.GoBack();
                    var successDialog = new MessageDialog("Successfully logged in.", "Success!");
                    await successDialog.ShowAsync();
                    return;
                }

                // Show error message, if something went wrong
                var errorDialog = new MessageDialog("Whoops, we could not log you in successfully. Sorry for that!", "Something went wrong...");
                await errorDialog.ShowAsync();
                Frame.GoBack();
            }
        }
Exemplo n.º 4
0
 public async Task<bool> Login()
 {
     var url = "https://github.com/login/oauth/authorize?client_id=" + Uri.EscapeDataString(ClientId) + "&redirect_uri=" + Uri.EscapeDataString(RedirectUri) + "&scope=repo&display=popup&response_type=token";
     var startUri = new Uri(url);
     var endUri = new Uri(RedirectUri);
     var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);
     string code = "";
     switch (webAuthenticationResult.ResponseStatus)
     {
         case WebAuthenticationStatus.Success:
             var decoder = new WwwFormUrlDecoder(webAuthenticationResult.ResponseData.Replace(RedirectUri + "/?", ""));
             code = decoder.First(x => x.Name == "code").Value;
             break;
         case WebAuthenticationStatus.ErrorHttp:
             return false;
             break;
         default:
             return false;
             break;
     }
     var c = new HttpClient();
     var data = new Dictionary<string, string>
                    {
                        {"client_id", ClientId},
                        {"client_secret", ClientSecret},
                        {"code", code}
                    };
     var content = new FormUrlEncodedContent(data);
     var request = await c.PostAsync(Accesstokenuri, content);
     var result = await request.Content.ReadAsStringAsync();
     _accessToken = new WwwFormUrlDecoder(result).GetFirstValueByName("access_token");
     return true;
 }
        private async Task<Token> GetAccessToken()
        {
            var token = new Token();

            var startUrl = Common.FormatAuthUrl(AuthorizationEndpointUrl, ResponseTypes.Token, ConsumerKey,
                WebUtility.UrlEncode(CallbackUrl), DisplayTypes.Popup);
            var startUri = new Uri(startUrl);
            var endUri = new Uri(CallbackUrl);

            var webAuthenticationResult =
                await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync(
                    Windows.Security.Authentication.Web.WebAuthenticationOptions.None,
                    startUri,
                    endUri);

            switch (webAuthenticationResult.ResponseStatus)
            {
                case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
                    var responseData = webAuthenticationResult.ResponseData;
                    var responseUri = new Uri(responseData);
                    var decoder = new WwwFormUrlDecoder(responseUri.Fragment.Replace("#", "?"));

                    token.AccessToken = decoder.GetFirstValueByName("access_token");
                    token.RefreshToken = decoder.GetFirstValueByName("refresh_token");
                    token.InstanceUrl = WebUtility.UrlDecode(decoder.GetFirstValueByName("instance_url"));

                    return token;

                case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
                    throw new Exception(webAuthenticationResult.ResponseErrorDetail.ToString());

                default:
                    throw new Exception(webAuthenticationResult.ResponseData);
            }
        }
Exemplo n.º 6
0
 private bool TryGetCode(string query, out string code)
 {
     var decoder = new WwwFormUrlDecoder(query);
     var entry = decoder.FirstOrDefault(e => e.Name == "code");
     code = entry?.Value;
     return entry != null;
 }
Exemplo n.º 7
0
        private string ExtractCode(string redirectedUrl)
        {
            var url = new Uri(redirectedUrl);
            var decoder = new WwwFormUrlDecoder(url.Query);

            return decoder.GetFirstValueByName("code");
        }
Exemplo n.º 8
0
        public MainWindow()
        {
            InitializeComponent();

            var args = Environment.GetCommandLineArgs();

            if (args.Length > 1)
            {
                Uri argUri;
                if (Uri.TryCreate(args[1], UriKind.Absolute, out argUri))
                {
                    var decoder = new WwwFormUrlDecoder(argUri.Query);
                    if (decoder.Any())
                    {
                        InputUrI.Text = string.Empty;

                        foreach (var entry in decoder)
                        {
                            InputUrI.Text += entry.Name + "=" + entry.Value + ",";
                            inputs[entry.Name] = entry.Value;
                        }

                        InputUrI.Text = InputUrI.Text.Remove(InputUrI.Text.Length - 1);
                    }
                }
            }
        }
Exemplo n.º 9
0
        public static async Task<string> GetAccessToken(string username, string password)
        {
            try
            {
                var handler = new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip,
                    AllowAutoRedirect = false
                };

                using (var tempHttpClient = new HttpClient(handler))
                {
                    //Get session cookie
                    var sessionResp = await tempHttpClient.GetAsync(Resources.PtcLoginUrl);
                    var data = await sessionResp.Content.ReadAsStringAsync();
                    var lt = JsonHelper.GetValue(data, "lt");
                    var executionId = JsonHelper.GetValue(data, "execution");

                    //Login
                    var loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl,
                        new FormUrlEncodedContent(
                            new[]
                            {
                                new KeyValuePair<string, string>("lt", lt),
                                new KeyValuePair<string, string>("execution", executionId),
                                new KeyValuePair<string, string>("_eventId", "submit"),
                                new KeyValuePair<string, string>("username", username),
                                new KeyValuePair<string, string>("password", password)
                            }));

                    var decoder = new WwwFormUrlDecoder(loginResp.Headers.Location.Query);
                    var ticketId = decoder.GetFirstValueByName("ticket");
                    if (string.IsNullOrEmpty(ticketId))
                        throw new PtcOfflineException();

                    //Get tokenvar 
                    var tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth,
                        new FormUrlEncodedContent(
                            new[]
                            {
                                new KeyValuePair<string, string>("client_id", "mobile-app_pokemon-go"),
                                new KeyValuePair<string, string>("redirect_uri",
                                    "https://www.nianticlabs.com/pokemongo/error"),
                                new KeyValuePair<string, string>("client_secret",
                                    "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR"),
                                new KeyValuePair<string, string>("grant_type", "refresh_token"),
                                new KeyValuePair<string, string>("code", ticketId)
                            }));

                    var tokenData = await tokenResp.Content.ReadAsStringAsync();
                    decoder = new WwwFormUrlDecoder(tokenData);
                    return decoder.GetFirstValueByName("access_token");
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
Exemplo n.º 10
0
 public static string GetQueryParameter(this Uri uri, string parameterName)
 {
     string query = uri.Query;
     if (query.Length <= 1)
     {
         return null;
     }
     WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(query);
     return decoder.GetFirstValueByName(parameterName);
 }
Exemplo n.º 11
0
        private async Task<string> GetTokenFromCode(string code)
        {
            var uri = $"{TokenUri}?client_id={Credentials.AppId}&client_secret={Credentials.AppSecret}&code={code}";
            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(uri, null);
                var query = await response.Content.ReadAsStringAsync();

                var decoder = new WwwFormUrlDecoder(query);
                return decoder.GetFirstValueByName("access_token");
            }
        }
Exemplo n.º 12
0
        private static string ExtracktTicketFromResponse(HttpResponseMessage loginResp)
        {
            var location = loginResp.Headers.Location;
            if (location == null)
                throw new LoginFailedException(loginResp);

            var decoder = new WwwFormUrlDecoder(loginResp.Headers.Location.Query);
            var ticketId = decoder.GetFirstValueByName("ticket");

            if (ticketId == null)
                throw new PtcOfflineException();

            return ticketId;
        }
Exemplo n.º 13
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter != null)
            {
                var args = e.Parameter as ProtocolActivatedEventArgs;
                Uri uri = args.Uri;
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.ToString());
                string customer = decoder[0].Value;
                string price = decoder[1].Value;

                Customer.Text = customer;
                Price.Text = price;
            }
        }
Exemplo n.º 14
0
 public Splash(ProtocolActivatedEventArgs args)
     : this(args.SplashScreen)
 {
     var _Decoder = new WwwFormUrlDecoder(args.Uri.Query);
     var _Id = _Decoder.Where(q => q.Name.ToLower() == "module").Select(q => q.Value).FirstOrDefault();
     if (string.IsNullOrWhiteSpace(_Id))
         _Decoder.Where(q => q.Name.ToLower() == "episode").Select(q => q.Value).FirstOrDefault();
     if (string.IsNullOrWhiteSpace(_Id))
     {
         Services.Navigation.GotoFail("The Uri specified was incorrect.");
         return;
     }
     AllowResume = false;
     GotoType = typeof(Views.Detail);
     GotoParam = _Id;
 }
 public static async Task<ExternalLoginResult> GetExternalAccessTokenAsync(string externalLoginUri, bool silentMode = false)
 {
     Uri authorizationRequestUri = new Uri(new Uri(ClientFactory.BaseAddress), externalLoginUri);
     WebAuthenticationOptions webAuthenticationOptions = silentMode ? WebAuthenticationOptions.SilentMode : WebAuthenticationOptions.None;
     WebAuthenticationResult authenticationResult = await WebAuthenticationBroker.AuthenticateAsync(webAuthenticationOptions, authorizationRequestUri);
     ExternalLoginResult loginExternalResult = new ExternalLoginResult() { WebAuthenticationResult = authenticationResult };
     if (authenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
     {
         Uri responseDataUri = new Uri(authenticationResult.ResponseData);
         string fragment = responseDataUri.Fragment;
         if (fragment != null && fragment.Length > 0)
         {
             WwwFormUrlDecoder wwwFormUrlDecoder = new WwwFormUrlDecoder(fragment.Substring(1));
             loginExternalResult.AccessToken = wwwFormUrlDecoder.GetFirstValueByName("access_token");
         }
     }
     return loginExternalResult;
 }
Exemplo n.º 16
0
        public async Task<bool> CompleteOAuthFlowAsync(string responseData)
        {
            // responseData value eg http://example.com/path?code=4cba03187d6cd6720217&state=6dfa60685ac94a29bdde2d9f3cbdce0e
            var responseUri = new Uri(responseData);
            var decoder = new WwwFormUrlDecoder(responseUri.Query);
            var code = decoder.GetFirstValueByName("code");
            var state = decoder.GetFirstValueByName("state");

            string storedState = VaultManager.GetPassword(VaultStateResourceKey, VaultDefaultUnusedUserName);
            if (storedState != state)
                return false;

            // We are storing the code to later be able to refresh the access token
            VaultManager.Save(VaultTokenCodeResourceKey, VaultDefaultUnusedUserName, code);

            bool ok = await AcquireAccessTokenAsync(code, state).ConfigureAwait(false); ;
            return ok;
        }
Exemplo n.º 17
0
        public static async Task<bool> authenticateUser()
        {

            String WordpressURL = "https://public-api.wordpress.com/oauth2/authorize?client_id=428&redirect_uri=http://127.0.0.1&response_type=code";


            System.Uri StartUri = new Uri(WordpressURL, UriKind.RelativeOrAbsolute);
            System.Uri EndUri = new Uri("http://127.0.0.1", UriKind.RelativeOrAbsolute);



            WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(WebAuthenticationResult.ResponseData.ToString());
                string authtoken = decoder.First().Value;
                string post_string = FormatPostRequest(authtoken);
                var content = new StringContent(post_string);
                var client = new System.Net.Http.HttpClient();
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                var responseTask = client.PostAsync("https://public-api.wordpress.com/oauth2/token", content);
                var response = await responseTask;
                string jsonresponse = await response.Content.ReadAsStringAsync();
                user = JsonConvert.DeserializeObject<AuthenticatedUser>(jsonresponse);
       
               ApplicationData.Current.LocalSettings.Values["AuthUser"] = Authenticator.user.access_token;

               postStatus(user.access_token);
               displayname = await userInfo(user.access_token);
               Authenticator.displayname = displayname;
               return true;
               


            }
            else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                return false;
            }
            else
            {
                return false;
            }
        }
Exemplo n.º 18
0
        public static Uri AddOrUpdateQuery(this Uri uri, string parameterName, string parameterValue)
        {
            List<KeyValuePair<string, string>> nameValueCollection = new List<KeyValuePair<string, string>>();

            string query = uri.Query;
            if (query == "?")
            {
                query = string.Empty;
            }
            if (query.Length > 0)
            {
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(query);
                foreach (var nameValue in decoder)
                {
                    nameValueCollection.Add(new KeyValuePair<string, string>(nameValue.Name, nameValue.Value));
                }
            }

            parameterName = WebUtility.UrlEncode(parameterName);
            parameterValue = WebUtility.UrlEncode(parameterValue);

            bool exist = false;
            for (int i = 0; i < nameValueCollection.Count; i++)
            {
                if (nameValueCollection[i].Key == parameterName)
                {
                    nameValueCollection[i] = new KeyValuePair<string, string>(parameterName, parameterValue);
                    exist = true;
                    break;
                }
            }
            if (exist == false)
            {
                nameValueCollection.Add(new KeyValuePair<string, string>(parameterName, parameterValue));
            }

            query = string.Join("&", nameValueCollection.Select(temp => temp.Key + "=" + temp.Value));

            return new UriBuilder(uri)
            {
                Query = query
            }.Uri;
        }
        /// <summary>
        /// Gets a list of <see cref="VideoInfo"/>s for the specified URL.
        /// </summary>
        /// <param name="videoUrl">The URL of the YouTube video.</param>
        /// <returns>A list of <see cref="VideoInfo"/>s that can be used to download the video.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="videoUrl"/> parameter is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">The <paramref name="videoUrl"/> parameter is not a valid YouTube URL.</exception>
        /// <exception cref="VideoNotAvailableException">The video is not available.</exception>
        /// <exception cref="WebException">An error occurred while downloading the YouTube page html.</exception>
        /// <exception cref="YoutubeParseException">The Youtube page could not be parsed.</exception>
        public static IEnumerable<VideoInfo> GetDownloadUrls(string videoUrl,System.Net.WebProxy proxy, System.Text.Encoding enc)
        {
            if (videoUrl == null)
                throw new ArgumentNullException("videoUrl");

            videoUrl = NormalizeYoutubeUrl(videoUrl);

            string pageSource = GetPageSource(videoUrl,proxy, enc);
            string videoTitle = GetVideoTitle(pageSource);
            string thumnailUrl = GetThumnailUrl(pageSource);

            #if NETFX_CORE
            string id = new WwwFormUrlDecoder(videoUrl).GetFirstValueByName("v");
            #else
            string id = HttpUtility.ParseQueryString(new Uri(videoUrl).Query)["v"];
            #endif

            string requestUrl = String.Format("http://www.youtube.com/get_video_info?&video_id={0}&el=detailpage&ps=default&eurl=&gl=US&hl=en", id);

            string source = GetPageSource(requestUrl,proxy, enc);

            try
            {
                IEnumerable<Uri> downloadUrls = ExtractDownloadUrls(source);

                return GetVideoInfos(downloadUrls, videoTitle, thumnailUrl);
            }

            catch (Exception ex)
            {
                ThrowYoutubeParseException(ex);
            }

            if (IsVideoUnavailable(pageSource))
            {
                throw new VideoNotAvailableException();
            }

            // If everything else fails, throw a generic YoutubeParseException
            ThrowYoutubeParseException(null);

            return null; // Will never happen, but the compiler requires it
        }
Exemplo n.º 20
0
        private void webView_LoadCompleted(object sender, NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("access_token")) {
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(e.Uri.AbsoluteUri);

                long uID = 0;
                long.TryParse(decoder.GetFirstValueByName("user_id"), out uID);

                storage.SetToken(
                    decoder.GetFirstValueByName(Constants.TokenMarker));

                storage.SetCurrUserID(uID);

                this.Frame.Navigate(typeof(MyProfile));
            }
            else {
                progressRing.IsActive = false;
                webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
        }
Exemplo n.º 21
0
        protected override void OnActivated(IActivatedEventArgs args)
        {
            if (args.Kind == ActivationKind.Protocol)
            {
                var commandArgs = args as ProtocolActivatedEventArgs;
                Windows.Foundation.WwwFormUrlDecoder decoder =
                    new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query);
                var destination = decoder.GetFirstValueByName("LaunchContext");

                string uriToLaunch = destination;
                var    uri         = new Uri(uriToLaunch);

                var success = Windows.System.Launcher.LaunchUriAsync(uri);

                Application.Current.Exit();

                // this.Suspending += OnSuspending;
            }

            //  base.OnActivated(args);
        }
Exemplo n.º 22
0
 private void TopicWebView_OnNavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
 {
     if (args.Uri != null && args.Uri.AbsoluteUri.StartsWith(Strings.LocalUriPrefix))
     {
         args.Cancel = true;
         if (args.Uri.AbsoluteUri.Contains("quote"))
         {
             var decoder = new WwwFormUrlDecoder(args.Uri.Query);
             var postId = decoder.FirstOrDefault(x => x.Name == "postId")?.Value;
             if (!string.IsNullOrEmpty(postId))
                 Loc.Topic.ShowEditorCommand.Execute(Loc.Topic.CurrentTopic.TopicNewPostUriForm + $"&numrep={postId}");
         }
         else
         {
             Debug.WriteLine("WW " + args.Uri.Query + "-- " + args.Uri + " -- " + args.Uri.AbsoluteUri);
             string param = args.Uri.Query.Replace("?", "");
             if (Loc.Main.ContextMessageCommand.CanExecute(param))
                 Loc.Main.ContextMessageCommand.Execute(param);
         }
     }
 }
 private static IEnumerable<VideoInfo> GetVideoInfos(string source)
 {
     var t = new WwwFormUrlDecoder(source);
     var videoTitle = t.GetFirstValueByName("title");
     var splitByUrls = t.GetFirstValueByName("url_encoded_fmt_stream_map").Split(',');
     var videoInfos = new List<VideoInfo>();
     foreach (var s in splitByUrls) {
         var queries = new WwwFormUrlDecoder(s);
         var url = queries.GetFirstValueByName("url");
         var decoder = new WwwFormUrlDecoder(url.Substring(url.IndexOf('?')));
         byte formatCode;
         if (!Byte.TryParse(decoder.GetFirstValueByName("itag"), out formatCode)) continue;
         var fallbackHost = WebUtility.UrlDecode(queries.GetFirstValueByName("fallback_host"));
         var sig = WebUtility.UrlDecode(queries.GetFirstValueByName("sig"));
         var item = VideoInfo.Defaults.SingleOrDefault(videoInfo => videoInfo.FormatCode == formatCode);
         var info = item != null ? item.Clone() : new VideoInfo(formatCode);
         info.DownloadUri = new Uri(url + "&fallback_host=" + fallbackHost + "&signature=" + sig);
         info.Title = videoTitle;
         videoInfos.Add(info);
     }
     return videoInfos;
 }
Exemplo n.º 24
0
        public static void ParseArguments(string arguments)
        {
            if (string.IsNullOrEmpty(arguments))
            {
                return;
            }
            var decoder = new WwwFormUrlDecoder(arguments);

            var city = decoder.FirstOrDefault(x => x.Name.Equals("city"));
            var parkingLot = decoder.FirstOrDefault(x => x.Name.Equals("parkingLot"));
            if (city != null && parkingLot != null)
            {
                Task.Run(async () =>
                {
                    await ServiceLocator.Current.GetInstance<MainViewModel>().TrySelectParkingLotById(city.Value, parkingLot.Value);
                });
            }else if (city != null)
            {
                Task.Run(async () =>
                {
                    await ServiceLocator.Current.GetInstance<MainViewModel>().TrySelectCityById(city.Value);
                });
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Parses the GET parameters from the URL and loads them into the settings
        /// </summary>
        /// <param name="uri"></param>
        public void ParseUriIntoSettings(Uri uri)
        {
            var decoder = new WwwFormUrlDecoder(uri.Query);

            // Take the parameters from the URL and put it into Settings
            foreach (WwwFormUrlDecoderEntry entry in decoder)
            {
                try
                {
                    var field = typeof(AppSettings).GetField(entry.Name);
                    if (field.FieldType == typeof(int))
                    {
                        field.SetValue(App.Controller.XmlSettings, Convert.ToInt32(entry.Value));
                    }
                    else if(field.FieldType == typeof(CameraType) ||
                            field.FieldType == typeof(StorageProvider))
                    {
                        field.SetValue(App.Controller.XmlSettings, Enum.Parse(field.FieldType, entry.Value));
                    }
                    else
                    {
                        //if the field being saved is the alias, and the alias has changed, send a telemetry event
                        if(0 == field.Name.CompareTo("MicrosoftAlias") &&
                           0 != entry.Value.CompareTo(App.Controller.XmlSettings.MicrosoftAlias))
                        {
                            Dictionary<string, string> properties = new Dictionary<string, string> { { "Alias", entry.Value } };
                            App.Controller.TelemetryClient.TrackEvent("Alias Changed", properties);
                        }
                        field.SetValue(App.Controller.XmlSettings, entry.Value);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);

                    // Log telemetry event about this exception
                    var events = new Dictionary<string, string> { { "WebHelper", ex.Message } };
                    App.Controller.TelemetryClient.TrackEvent("FailedToParseUriIntoSettings", events);
                }
            }
        }
        private static IEnumerable<VideoInfo> GetVideoInfos(IEnumerable<Uri> downloadUrls, string videoTitle)
        {
            var downLoadInfos = new List<VideoInfo>();

            foreach (Uri url in downloadUrls)
            {
            #if NETFX_CORE
                string itag = new WwwFormUrlDecoder(url.Query).GetFirstValueByName("itag");
            #else
                string itag = HttpUtility.ParseQueryString(url.Query)["itag"];
            #endif

                // for this version, only get the download URL
                byte formatCode = Byte.Parse(itag);

                // Currently based on YouTube specifications (later we'll depend on the MIME type returned from the web request)
                VideoInfo info = VideoInfo.Defaults.SingleOrDefault(videoInfo => videoInfo.FormatCode == formatCode);

                if (info != null)
                {
                    info.DownloadUrl = url.ToString();
                    info.Title = videoTitle;
                }

                else
                {
                    info = new VideoInfo(formatCode);
                }

                downLoadInfos.Add(info);
            }

            return downLoadInfos;
        }
Exemplo n.º 27
0
        async protected override void OnActivated(IActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            if (rootFrame == null)
            {
                CreateRootFrame();

                if (!RootFrame.Navigate(typeof(MainPage)))
                {
                    throw new Exception("Failed to create initial page");
                }

                Window.Current.Activate();
            }

            if (args.Kind == ActivationKind.Launch)
            {
                var toastArgs = args as LaunchActivatedEventArgs;
                if (toastArgs == null)
                {
                    return;
                }
                var arguments = JsonConvert.DeserializeObject <ToastNotificationArgs>(toastArgs.Arguments);
                if (arguments.openBookmarks)
                {
                    var bookmarkCommand = new NavigateToBookmarksCommand();
                    bookmarkCommand.Execute(null);
                    return;
                }

                if (arguments != null && arguments.openPrivateMessages)
                {
                    var openPms = new NavigateToPrivateMessageListPageCommand();
                    openPms.Execute(null);
                    return;
                }
            }

            //Find out if this is activated from a toast;
            if (args.Kind == ActivationKind.ToastNotification)
            {
                //Get the pre-defined arguments and user inputs from the eventargs;
                var toastArgs = args as ToastNotificationActivatedEventArgs;
                if (toastArgs == null)
                {
                    return;
                }
                var arguments = JsonConvert.DeserializeObject <ToastNotificationArgs>(toastArgs.Argument);
                if (arguments != null && arguments.threadId > 0)
                {
                    var bookmarkCommand = new NavigateToBookmarksCommand();
                    bookmarkCommand.Execute(arguments.threadId);
                    return;
                }

                var forumEntity = JsonConvert.DeserializeObject <ForumEntity>(toastArgs.Argument);
                if (forumEntity != null)
                {
                    var navigateCommand = new NavigateToThreadListPageCommandViaTile();
                    navigateCommand.Execute(forumEntity);
                }
            }

            // Cortana
            if (args.Kind == ActivationKind.VoiceCommand)
            {
                var commandArgs = args as VoiceCommandActivatedEventArgs;
                HandleVoiceRequest(commandArgs);
            }

            if (args.Kind == ActivationKind.Protocol)
            {
                var commandArgs = args as ProtocolActivatedEventArgs;
                Windows.Foundation.WwwFormUrlDecoder decoder =
                    new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query);
                var destination = decoder.GetFirstValueByName("LaunchContext");
                var jsonTest    = WebUtility.UrlDecode(destination);

                var arguments = JsonConvert.DeserializeObject <ToastNotificationArgs>(jsonTest);
                if (arguments != null && arguments.threadId > 0)
                {
                    var bookmarkCommand = new NavigateToBookmarksCommand();
                    bookmarkCommand.Execute(arguments.threadId);
                    return;
                }

                if (arguments != null && arguments.openPrivateMessages)
                {
                    var openPms = new NavigateToPrivateMessageListPageCommand();
                    openPms.Execute(null);
                    return;
                }

                var forumEntity = JsonConvert.DeserializeObject <ForumEntity>(jsonTest);
                if (forumEntity != null)
                {
                    var navigateCommand = new NavigateToThreadListPageCommandViaTile();
                    navigateCommand.Execute(forumEntity);
                }
            }

            //...
        }
Exemplo n.º 28
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            SuspensionManager.KnownTypes.Add(typeof(Catalog));
            SuspensionManager.KnownTypes.Add(typeof(Cart));

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                //Associate the frame with a SuspensionManager key                                
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }

                if (!SuspensionManager.SessionState.ContainsKey(SuspensionManagerConstants.Catalog))
                {
                    Window.Current.Content = new ExtendedSplash();
                    Window.Current.Activate();
        
                    var repository = ServiceLocator.Get<CatalogRepository>();
                    var catalog = await repository.GetCatalog();
                    SuspensionManager.SessionState.Add(SuspensionManagerConstants.Catalog, catalog);
                }

                if (!SuspensionManager.SessionState.ContainsKey(SuspensionManagerConstants.Cart))
                {
                    SuspensionManager.SessionState.Add(SuspensionManagerConstants.Cart, new Cart());
                }

                var pushNotificationRegistration = ServiceLocator.Get<PushNotificationRegistrationService>();
                pushNotificationRegistration.AcquirePushChannel();

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllCategories"))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            if (!string.IsNullOrEmpty(args.Arguments))
            {
                var decoder = new WwwFormUrlDecoder(args.Arguments);

                var category = decoder.Where(v => v.Name == "category").Select(v => v.Value).FirstOrDefault();
                if (!string.IsNullOrEmpty(category))
                {
                    // if category exists then its launched from a secondary tile.
                    rootFrame.Navigate(typeof (GroupDetailPage), category);
                }

                var cartParam = decoder.Where(v => v.Name == "cartId").Select(v => v.Value).FirstOrDefault();
                long cartId;
                if (long.TryParse(cartParam, out cartId))
                {
                    // if cartId exists then its launched from a toast.
                    rootFrame.Navigate(typeof (CartPage), cartId);
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Parses the GET parameters from the URL and then uses them to log into OneDrive
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public async Task ParseOneDriveUri(Uri uri)
        {
            var oneDrive = App.Controller.Storage as OneDrive;
            if (oneDrive == null)
                return;

            try
            {
                var decoder = new WwwFormUrlDecoder(uri.Query);
                foreach (WwwFormUrlDecoderEntry entry in decoder)
                {
                    // codeUrl is the parameter that contains the URL that was pasted into the textbox on the OneDrive page
                    if (entry.Name.Equals("codeUrl"))
                    {
                        string codeUrl = WebUtility.UrlDecode(entry.Value);
                        var codeUri = new Uri(codeUrl);
                        var codeDecoder = new WwwFormUrlDecoder(codeUri.Query);
                        foreach (WwwFormUrlDecoderEntry subEntry in codeDecoder)
                        {
                            if (subEntry.Name.Equals("code"))
                            {
                                await oneDrive.Authorize(subEntry.Value);
                                break;
                            }
                        }
                        break;
                    }
                    else if (entry.Name.Equals("logout"))
                    {
                        await oneDrive.Logout();
                    }
                }
            }
            catch (Exception ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "WebHelper", ex.Message } };
                App.Controller.TelemetryClient.TrackEvent("FailedToParseOneDriveUri", events);
            }

        }
Exemplo n.º 30
0
        /// <summary>
        /// Invoked when the application is activated by some other means other than launching
        /// </summary>
        /// <param name="e">Event data for the event.</param>
        protected override async void OnActivated(IActivatedEventArgs args)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (args.Kind == ActivationKind.VoiceCommand)
            {
                try
                {
                    // now get the parameters pased in
                    VoiceCommandActivatedEventArgs commandArgs             = args as VoiceCommandActivatedEventArgs;
                    SpeechRecognitionResult        speechRecognitionResult = commandArgs.Result;
                    string voiceCommandName = speechRecognitionResult.RulePath[0];
                    string textSpoken       = speechRecognitionResult.Text;
                    IReadOnlyList <string> recognisedVoiceCommandPhrases;
                    System.Diagnostics.Debug.WriteLine("Voice CommandName: " + voiceCommandName);
                    System.Diagnostics.Debug.WriteLine("text Spoken: " + textSpoken);

                    switch (voiceCommandName)
                    {
                    case "readBook":
                    {
                        string bookName  = this.SemanticInterpretation("bookName", speechRecognitionResult);
                        var    folder    = ApplicationData.Current.LocalFolder;
                        var    subFolder = await folder.GetFolderAsync("books");

                        var files = await subFolder.GetFilesAsync();

                        foreach (StorageFile sf in files)
                        {
                            if (sf.DisplayName.Equals(bookName))
                            {
                                book = sf.Name;
                                break;
                            }
                        }
                        break;
                    }

                    default:
                    {
                        break;
                    }
                    }   // end Switch(voiceCommandName)

                    System.Diagnostics.Debug.WriteLine("go to main page Now ");
                }
                catch (Exception)
                {
                    MessageDialog msgDialog = new MessageDialog("Crashed");
                    await msgDialog.ShowAsync();
                }
            }
            else if (args.Kind == ActivationKind.Protocol)
            {
                var commandArgs = args as ProtocolActivatedEventArgs;
                Windows.Foundation.WwwFormUrlDecoder decoder = new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query);
                var destination = decoder.GetFirstValueByName("LaunchContext");
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(EnterByVoice), args.PreviousExecutionState);
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
 // return series ID
 static string ParseIDFromBookLink(string link)
 {
     Uri uri = new Uri(SeverBaseUri, link);
     var decoder = new WwwFormUrlDecoder(uri.Query);
     return decoder.GetFirstValueByName("id");
 }
 static NovelPositionIdentifier ParseIDFromReadLink(string link)
 {
     var pos = new NovelPositionIdentifier();
     Uri uri = new Uri(SeverBaseUri, link);
     var decoder = new WwwFormUrlDecoder(uri.Query);
     pos.ChapterId = decoder.GetFirstValueByName("chapterId");
     pos.VolumeId = decoder.GetFirstValueByName("volId");
     pos.SeriesId = decoder.GetFirstValueByName("bookId");
     return pos;
 }
Exemplo n.º 33
0
        /// <summary>
        /// Parses the GET parameters from the URL and returns the parameters and values in a Dictionary
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public Dictionary<string, string> ParseGetParametersFromUrl(Uri uri)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();

            var decoder = new WwwFormUrlDecoder(uri.Query);
            foreach (WwwFormUrlDecoderEntry entry in decoder)
            {
                parameters.Add(entry.Name, entry.Value);
            }

            return parameters;
        }