Inheritance: IMessageDialog
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (CountryPhoneCode.SelectedItem != null)
            {
                var _id = Guid.NewGuid().ToString("N");
                var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode;
                var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName;
                var _name = FullName.Text;
                var _phoneNumber = PhoneNumber.Text;
                var _password = Password.Password;

                var client = new HttpClient()
                {
                    BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/")
                };

                var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password="******"&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode);

                var serializer = new DataContractJsonSerializer(typeof(User));
                var ms = new MemoryStream();
                var user = serializer.ReadObject(ms) as User;

                Frame.Navigate(typeof(MainPage), user);
            }
            else
            {
                MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!");
                await dialog.ShowAsync();
            }
        }
        private async void saveConf_Click(object sender, RoutedEventArgs e)
        {
            if(serverExt.Text == "" && token.Text == "" && port.Text == "" && serverInt.Text == "")
            {
                MessageDialog msgbox = new MessageDialog("Un ou plusieurs champs sont vide...");
                await msgbox.ShowAsync(); 
            }
            else
            {
                localSettings.Values["savedServerExt"] = serverExt.Text;
                localSettings.Values["savedServerInt"] = serverInt.Text;
                localSettings.Values["savedToken"] = token.Text;
                localSettings.Values["savedPort"] = port.Text;

                if (tts.IsOn)
                {
                    localSettings.Values["tts"] = true;
                }
                else localSettings.Values["tts"] = false;

                Frame.Navigate(typeof(PageAction));
            }
            
           
        }
        private async void ButtonRequestToken_Click(object sender, RoutedEventArgs e)
        {
            var error = string.Empty;

            try
            {
                var response = await WebAuthentication.DoImplicitFlowAsync(
                    endpoint: new Uri(Constants.AS.OAuth2AuthorizeEndpoint),
                    clientId: Constants.Clients.ImplicitClient,
                    scope: "read");

                TokenVault.StoreToken(_resourceName, response);
                RetrieveStoredToken();

            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            if (!string.IsNullOrEmpty(error))
            {
                var dialog = new MessageDialog(error);
                await dialog.ShowAsync();
            }
        }
Example #4
0
        public bool LogIn(Windows.UI.Xaml.Controls.WebView webView, Windows.UI.Xaml.Controls.Frame parentFrame)
        {
            var uri = driveLink.GetStartUri();

            webView.Navigate(uri);

            webView.NavigationCompleted += (s, e) =>
            {
                if (driveLink.CheckRedirectUrl(e.Uri.AbsoluteUri))
                {
                    driveLink.ContinueGetTokens(e.Uri);
                    var dialog = new Windows.UI.Popups.MessageDialog("You are authenticated!", "Success!");
                    dialog.ShowAsync();
                    parentFrame.GoBack();
                }
            };

            webView.NavigationFailed += (s, e) =>
            {
                driveLink.ContinueGetTokens(null);
                var dialog = new Windows.UI.Popups.MessageDialog("There problems authenticating you. Please try again :(", "Fail!");
                dialog.ShowAsync();
                parentFrame.GoBack();
            };
            return(true);
        }
Example #5
0
        private async void checkInput()
        {
            int numCard = 0;
            Int32.TryParse(numCardBox.Text, out numCard);
            if (Int32.TryParse(numCardBox.Text, out numCard) != false && numCard <= 1000)   //if input is valid 
            {
                if (CardReturn.IsChecked == true)
                {
                    //reset all drawned card list
                    drawned = new bool[4, 13];
                    numDrawned = 0;
                    cardDrawReturn(numCard);
                }
                else
                    cardDrawNoReturn(numCard);
            }

            else if (Int32.TryParse(numCardBox.Text, out numCard) != false && (numCard > 1000 || numCard < 0))  //if input is out of bound
            {
                var messageDialog = new MessageDialog("Please enter a number between 0 and 1000.");
                messageDialog.Title = "Invalid Input";

                // Show the message dialog and wait
                await messageDialog.ShowAsync();
            }
            else
            {
                var messageDialog = new MessageDialog("Please enter a real number.");   //if input is not an integer
                messageDialog.Title = "Invalid Input";

                // Show the message dialog and wait
                await messageDialog.ShowAsync();
            }
        }
Example #6
0
        /// <summary>
        /// Shows a yes no dialog with a message.
        /// MUST BE CALLED FROM THE UI THREAD!
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<bool?> ShowYesNoMessage(string title, string content, string postiveButton = "Yes", string negativeButton = "No")
        {
            // Don't show messages if we are in the background.
            if (m_baconMan.IsBackgroundTask)
            {
                return null;
            }

            bool? response = null;

            // Add the buttons
            MessageDialog message = new MessageDialog(content, title);
            message.Commands.Add(new UICommand(
                postiveButton,
                (IUICommand command)=> {
                    response = true; }));
            message.Commands.Add(new UICommand(
                negativeButton,
                (IUICommand command) => { response = false; }));
            message.DefaultCommandIndex = 0;
            message.CancelCommandIndex = 1;

            // Show the dialog
            await message.ShowAsync();

            return response;
        }
Example #7
0
        private async Task Notify(string message, string valid = "OK")
        {
            var msgbox = new Windows.UI.Popups.MessageDialog(message);

            msgbox.Commands.Add(new Windows.UI.Popups.UICommand(valid));
            await msgbox.ShowAsync();
        }
Example #8
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            String Antwort = "";
            string Ziel = "/Nachricht.php?";

            HttpContent content = new FormUrlEncodedContent(new[]             // POST inhalt vorbereiten
            {
                new KeyValuePair<string, string>("NachrichtHead", GlobalData.Pers_ID),
                new KeyValuePair<string, string>("Betreff",textBox1.Text),
                new KeyValuePair<string, string>("inhalt", textBox.Text),
                    });
            // Schritt 4 Abfrage abschicken und ergebnis entgegennehmen 
            try
            {

                Antwort = await Globafunctions.HttpAbfrage(Ziel, content);
            }
            catch
            {
                MessageDialog msgbox = new MessageDialog("Nachricht konnte nicht Versendet werden");
                await msgbox.ShowAsync();

            }
            
            MessageDialog msgbox1 = new MessageDialog(Antwort);
            await msgbox1.ShowAsync();
            Frame.Navigate(typeof(Intern));
        }
Example #9
0
        private async void PlaySound(Uri soundUri)
        {
            Exception exception = null;

            try
            {
                if (_audioPlayer == null)
                    _audioPlayer = new AudioPlayer();

                _audioPlayer.PlaySound(soundUri);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                var dialog = new MessageDialog(exception.ToString(), "Exception Caught!");
                try
                {
                    await dialog.ShowAsync();
                }
                catch (UnauthorizedAccessException)
                {
                }
            }
        }
Example #10
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary <String, Object> pageState)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data

            //var sds = new SampleDataSource();
            if (pageState == null)
            {
                mainpageLoadingRing.IsActive    = true;
                mainpageLoadingPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;

                //if (SampleDataSource._sampleDataSource.AllGroups.Count == 0)
                //{
                try
                {
                    Data.SubredditManager._subredditManager.ReadSRFromFileAsync(mainpageLoadingRing, mainpageLoadingPanel);
                    //this is on purpose. subreddit should pop up as they are created.
                    //the method is passed the elements to disable upon its' completed
                }
                catch (System.Net.Http.HttpRequestException e)
                {
                    var dia = new Windows.UI.Popups.MessageDialog("Your computer and Reddit are having connection issues. Check internet connectivity and try again.");
                    dia.ShowAsync();
                }
                //}
            }

            var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);

            this.DefaultViewModel["Items"] = sampleDataGroups;
        }
Example #11
0
 private void dealClick(object sender, RoutedEventArgs e)
 {
     try
     {
         pack = new Pack();
         for (int handNum = 0; handNum < NumHands; handNum++)
         {
             hands[handNum] = new Hand();
             for (int numCards = 0; numCards < Hand.HandSize; numCards++)
             {
                 PlayingCard cardDealt = pack.DealCardFromPack();
                 hands[handNum].AddCardToHand(cardDealt);
             }
         }
         north.Text = hands[0].ToString();
         south.Text = hands[1].ToString();
         east.Text = hands[2].ToString();
         west.Text = hands[3].ToString();
     }
     catch (Exception ex)
     {
         MessageDialog msg = new MessageDialog(ex.Message, "Error");
         msg.ShowAsync();
     }
 }
Example #12
0
        private async void btnPotion_Click(object sender, RoutedEventArgs e)
        {
            if (_player.Potions <= 0.99) // when you have less than 1 potion in your inventoru
            {
                var dialog = new Windows.UI.Popups.MessageDialog("You have no potions in your inventory");
                var result = await dialog.ShowAsync(); // message is displayed saying that you don't have any
            }
            else
            {
                var dialog = new Windows.UI.Popups.MessageDialog("You have increased your health by 20");
                var result = await dialog.ShowAsync();      // message is displayed saying you have increase your health

                _player.CurrentHP = _player.CurrentHP + 20; // health increases by 20
                txtCurrentHP.Text = _player.CurrentHP.ToString();

                if (_player.CurrentHP >= 20)                           // if health goes above 20
                {
                    _player.CurrentHP = 20 + (5 * _player.DefEnemies); // health = 20 plus 5 for every level the player is
                    txtCurrentHP.Text = _player.CurrentHP.ToString();
                }

                txtCurrentHP.Text = _player.CurrentHP.ToString(); // updates player's stat

                _player.Potions = _player.Potions - 1;            // takes away a potion
                txtPotions.Text = _player.Potions.ToString();
            }
        }
Example #13
0
        private async void Add_Tapped_1(object sender, TappedRoutedEventArgs e)
        {
            if (SRMAddTextBox.Text == "Home Page")
            {
                await Data.SampleDataSource.AddHomePage();

                SRMAddTextBox.Text = "";
                Data.SubredditManager._subredditManager.WriteSubreddits();
            }
            else
            {
                try
                {
                    await Data.SampleDataSource.AddPage("http://www.reddit.com/r/" + SRMAddTextBox.Text + ".json");

                    SRMAddTextBox.Text = "";
                    Data.SubredditManager._subredditManager.WriteSubreddits();
                }
                catch (UnauthorizedAccessException ex)
                {
                    var dia = new Windows.UI.Popups.MessageDialog("Sorry, the subreddit you entered doesn't appear to exist or is private.  Please check for typos and try again");
                    dia.ShowAsync();
                }
            }
        }
Example #14
0
        // button to level up the player
        private async void btnLevelUp_Click(object sender, RoutedEventArgs e)
        {
            // if experience is more than what is required
            if (_player.Experience >= _player.ExpNeeded)
            {
                // takes away req experience from current experience
                _player.Experience = _player.Experience - _player.ExpNeeded;
                txtEXP_Points.Text = _player.Experience.ToString();

                // req exp for next time increases by 100
                _player.ExpNeeded = _player.ExpNeeded + 100;
                txtExpNeeded.Text = _player.ExpNeeded.ToString();

                // player level increments by one
                _player.Level++;
                txtLevel.Text = _player.Level.ToString();

                // increases attack of player by 2
                _player.CurrentAttack = _player.CurrentAttack + 2;
                txtCurrentAttack.Text = _player.CurrentAttack.ToString();

                // current player's hp increases by its base plus 5 more for every level they are
                _player.CurrentHP = 20 + (5 * _player.Level);

                var dialog = new Windows.UI.Popups.MessageDialog("You have leveled up to Level " + _player.Level + " Your Attack is now " + _player.CurrentAttack + " and Health is now at " + _player.CurrentHP);
                var result = await dialog.ShowAsync(); // displays message to confirm that the player has leveled up

                txtCurrentHP.Text = _player.CurrentHP.ToString();
            }
            else
            {
                var dialog = new Windows.UI.Popups.MessageDialog("You need more experience!");
                var result = await dialog.ShowAsync(); // displays message to say you don't have enough exp
            }
        }
 private void Change_B_Click(object sender, RoutedEventArgs e)
 {
     if (checkValid())
     {
         var    db       = App.conn;
         string Username = App.login_user.Username;
         string Password = Input_Password.Password;
         string sql_u    = @"UPDATE  User SET Password = ? WHERE Username = ?";
         try
         {
             using (var insertment = db.Prepare(sql_u))
             {
                 insertment.Bind(1, Password);
                 insertment.Bind(2, Username);
                 insertment.Step();
             }
             var i = new Windows.UI.Popups.MessageDialog("successfully change!").ShowAsync();
             Frame.Navigate(typeof(HomePage), "");
         }
         catch (Exception ex)
         {
             var i = new Windows.UI.Popups.MessageDialog("Change Defeat!").ShowAsync();
             throw (ex);
         }
     }
     else
     {
         return;
     }
 }
Example #16
0
        async private void Post_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            await this.loginButton.RequestNewPermissions("publish_actions");

            var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);

            var postParams = new {
                message = Joke.Text
            };

            try
            {
                // me/feed posts to logged in user's feed
                dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);

                var result = (IDictionary <string, object>)fbPostTaskResult;

                var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result["id"]);
                await successMessageDialog.ShowAsync();
            }
            catch (Exception ex)
            {
                var exceptionMessageDialog = new Windows.UI.Popups.MessageDialog("Exception during post: " + ex.Message);
                exceptionMessageDialog.ShowAsync();
            }
        }
        // Accepts two user shapes and adds them to the graphics layer
        private async void StartDrawingButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnDraw.IsEnabled = false;
                btnTest.IsEnabled = false;
                resultPanel.Visibility = Visibility.Collapsed;

                _graphicsOverlay.Graphics.Clear();

                // Shape One
                Esri.ArcGISRuntime.Geometry.Geometry shapeOne = await MyMapView.Editor.RequestShapeAsync(
                    (DrawShape)comboShapeOne.SelectedValue, _symbols[comboShapeOne.SelectedIndex]);

                _graphicsOverlay.Graphics.Add(new Graphic(shapeOne, _symbols[comboShapeOne.SelectedIndex]));

                // Shape Two
                Esri.ArcGISRuntime.Geometry.Geometry shapeTwo = await MyMapView.Editor.RequestShapeAsync(
                    (DrawShape)comboShapeTwo.SelectedValue, _symbols[comboShapeTwo.SelectedIndex]);

                _graphicsOverlay.Graphics.Add(new Graphic(shapeTwo, _symbols[comboShapeTwo.SelectedIndex]));
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
            finally
            {
                btnDraw.IsEnabled = true;
                btnTest.IsEnabled = (_graphicsOverlay.Graphics.Count >= 2);
            }
        }
Example #18
0
 protected override async void OnNavigatedTo(NavigationEventArgs e)
 {
     using (var client = new HttpClient())
     {
         var  response = "";
         Task task     = Task.Run(async() =>
         {
             response = await client.GetStringAsync(App.baseUri2);
         });
         try
         {
             task.Wait(); // Wait 
             var data = JsonConvert.DeserializeObject <List <diseaseData> >(response);
             App._disease = JsonConvert.DeserializeObject <List <diseaseData> >(response)[0];
             foreach (var item in data)
             {
                 this.Values.Add(item);
             }
             listView.ItemsSource = this.Values;
         }
         catch (Exception ex)
         {
             Windows.UI.Popups.MessageDialog obj = new Windows.UI.Popups.MessageDialog(ex.Message);
             await obj.ShowAsync();
         }
     }
 }
Example #19
0
        public static async Task <string> file_get_contents(string url)
        {
            try
            {
                HttpClient          httpClient = new HttpClient();
                HttpResponseMessage response   = await httpClient.GetAsync(url);

                response.EnsureSuccessStatusCode();
                Boolean statusCode = response.IsSuccessStatusCode;
                if (!statusCode)
                {
                    Windows.UI.Popups.MessageDialog dlg = new Windows.UI.Popups.MessageDialog("网络通信不畅");
                    await dlg.ShowAsync();

                    return(null);
                }
                result = await httpClient.GetStringAsync(url);

                return(result);
            }
            catch (Exception)
            {
                result = "";
                return("");
            }
        }
Example #20
0
        private async Task DeleteEvent()
        {
            if (_navigationService != null)
            {
                if (CanExecute())
                {
                    var ds = new DataService();
                    try
                    {
                        await ds.DeletePublication(_selectedPublication.Id);

                        var messageDialog = new MessageDialog("Supprimer");
                        await messageDialog.ShowAsync();

                        this.InitializeAsync();
                    }
                    catch (Exception e)
                    {
                        var dialog = new Windows.UI.Popups.MessageDialog(e.Message, "Erreur");

                        dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                        {
                            Id = 0
                        });

                        var result = dialog.ShowAsync();
                    }
                }
            }
            else
            {
                throw new NotImplementedException();
            }
        }
        private async void RegisterChannel()
        {
            var showRetryMessageDialog = false;
            var retryMessageDialog = new MessageDialog("");

            try
            {
                if (GetPrivateClient() != null && GetPrivateClient().CurrentUser != null)
                {
                    var ch = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
                    var channelDTO = new Channel { Uri = ch.Uri };
                    var channelTable = privateClient.GetTable<Channel>();

                    var id = ApplicationData.Current.LocalSettings.Values["ChannelId"];
                    if (id != null)
                    {
                        var channels = await channelTable.ToEnumerableAsync();

                        if (!channels.Where(item => item.Id.Equals(id)).Any())
                        {
                            ApplicationData.Current.LocalSettings.Values["ChannelId"] = null;
                        }
                    }

                    if (ApplicationData.Current.LocalSettings.Values["ChannelId"] == null)
                    {
                        await channelTable.InsertAsync(channelDTO);
                        ApplicationData.Current.LocalSettings.Values["ChannelId"] = channelDTO.Id;
                    }
                    else
                    {
                        channelDTO.Id = (int)ApplicationData.Current.LocalSettings.Values["ChannelId"];
                        await channelTable.UpdateAsync(channelDTO);
                    }
                }
            }
            catch(Exception e)
            {
                retryMessageDialog.Title = "There was a problem while registering the channel";
                retryMessageDialog.Content = e.Message;

                retryMessageDialog.Commands.Add(
                    new UICommand("Continue")
                    );

                // Set the command that will be invoked by default
                retryMessageDialog.DefaultCommandIndex = 0;

                // Set the command to be invoked when escape is pressed
                retryMessageDialog.CancelCommandIndex = 0;

                // Show the message dialog
                showRetryMessageDialog = true;
            }

            if (showRetryMessageDialog)
            {
                await retryMessageDialog.ShowAsync();
            }
        }
Example #22
0
        public async System.Threading.Tasks.Task <bool> exitDialog()
        {
            Class1.doLog("exitDialog started");

            bool      bDoExit    = true;
            UICommand yesCommand = new UICommand("Yes", cmd => { bDoExit = true; });
            UICommand noCommand  = new UICommand("No", cmd => { bDoExit = false; });

            Windows.UI.Popups.MessageDialog dlg = new Windows.UI.Popups.MessageDialog(_content, _title);
            dlg.Options = MessageDialogOptions.None;
            dlg.Commands.Add(yesCommand);

            if (noCommand != null)
            {
                dlg.Commands.Add(noCommand);
                dlg.CancelCommandIndex = (uint)dlg.Commands.Count - 1;
            }
            dlg.DefaultCommandIndex = 0;
            dlg.CancelCommandIndex  = 1;
            var command = await dlg.ShowAsync(); //already sets bDoExit

            if (command == yesCommand)
            {
                bDoExit = true;
            }
            if (command == noCommand)
            {
                bDoExit = false;
            }

            return(bDoExit);
        }
        // Create three List<Graphic> objects with random graphics to serve as layer GraphicsSources
        private async void CreateGraphics()
        {
			try
			{
				await MyMapView.LayersLoadedAsync();

				_graphicsSources = new List<List<Graphic>>()
				{
					new List<Graphic>(),
					new List<Graphic>(),
					new List<Graphic>()
				};

				foreach (var graphicList in _graphicsSources)
				{
					for (int n = 0; n < 10; ++n)
					{
						graphicList.Add(CreateRandomGraphic());
					}
				}

				_graphicSourceIndex = 0;
				_graphicsLayer.GraphicsSource = _graphicsSources[_graphicSourceIndex];
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog("Exception occurred : " + ex.ToString(), "Sample error").ShowAsync();
			}
        }
Example #24
0
        private async void MenuFlyoutItem_Click_8(object sender, RoutedEventArgs e)
        {
            Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
            savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;

            savePicker.FileTypeChoices.Add("Rich Text", new List <string>()
            {
                ".rtf"
            });

            savePicker.SuggestedFileName = "New Document";

            file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                randAccStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                flextextwrite.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);


                Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

                if (status != Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    Windows.UI.Popups.MessageDialog errorBox =
                        new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.");
                    await errorBox.ShowAsync();
                }
            }
        }
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     if (IsInternet())
     {
         Uri ur = new Uri("https://academics.vit.ac.in/parent/captcha.asp");
         webview1.Navigate(ur);
         try
         {
             await RestoreAsync();
         }
         catch (Exception)
         { }
     }
     else
     {
         var dlg = new Windows.UI.Popups.MessageDialog("An internet connection is needed. Please check your connection and restart the app.");
         dlg.Commands.Add(new UICommand("Exit", (UICommandInvokedHandler) =>
         {
             Application.Current.Exit();
         }));
         dlg.Commands.Add(new UICommand("Try Again", (UICommandInvokedHandler) =>
         {
         }));
         await dlg.ShowAsync();
     }
 }
Example #26
0
        private async void WebView_ScriptNotify(object sender, NotifyEventArgs e)
        {
            var    messageArray = e.Value.Split(':');
            string message, type;

            if (messageArray.Length > 1)
            {
                message = messageArray[1];
                type    = messageArray[0];
            }
            else
            {
                message = e.Value;
                type    = "typeAlert";
            }

            var dialog = new Windows.UI.Popups.MessageDialog(message);

            if (type.Equals("typeConfirm"))
            {
                var cmd = new UICommandInvokedHandler(this.CommandInvokedHandler);
                dialog.Commands.Add(new UICommand("Yes", cmd));
                dialog.Commands.Add(new UICommand("Cancel", cmd));
                dialog.DefaultCommandIndex = 0;
                dialog.CancelCommandIndex  = 1;
            }
            else if (type.Equals("typeLog"))
            {
                //Debug.WriteLine("type=" + type + " ,message=" + message);
            }

            var result = await dialog.ShowAsync();
        }
Example #27
0
        /// <summary>
        /// Restituisce i dati dell'utente
        /// </summary>
        public static async Task<Microsoft.Graph.User> GetMyInfoAsync()
        {
            //JObject jResult = null;

            try
            {
                HttpClient client = new HttpClient();
                var token = await OfficeHelper.GetTokenAsync();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // Endpoint dell'utente loggato
                Uri usersEndpoint = new Uri($"{serviceEndpoint}me");

                HttpResponseMessage response = await client.GetAsync(usersEndpoint);

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<Microsoft.Graph.User>(responseContent);                    
                }
                else
                {
                    var msg = new MessageDialog("Non è stato possibile recuperare i dati dell'utente. Risposta del server: " + response.StatusCode);
                    await msg.ShowAsync();
                    return null;
                }
            }
            catch (Exception e)
            {
                var msg = new MessageDialog("Si è verificato il seguente errore: " + e.Message);
                await msg.ShowAsync();
                return null;
            }
        }
Example #28
0
        //method to end game
        private async void methodGameOverAsync()
        {
            var dialog = new Windows.UI.Popups.MessageDialog("GAME OVER. THE MOUSE GOT DEAD!");
            var res    = await dialog.ShowAsync();

            CoreApplication.Exit();
        }
        // Define a method that performs the authentication process
        // using a Facebook sign-in. 
        //private async System.Threading.Tasks.Task AuthenticateAsync()
        //{
        //    while (user == null)
        //    {
        //        string message;
        //        try
        //        {
        //            // Change 'MobileService' to the name of your MobileServiceClient instance.
        //            // Sign-in using Facebook authentication.
        //            user = await App.MobileService
        //                .LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);
        //            message =
        //                string.Format("You are now signed in - {0}", user.UserId);
        //        }
        //        catch (InvalidOperationException)
        //        {
        //            message = "You must log in. Login Required";
        //        }

        //        var dialog = new MessageDialog(message);
        //        dialog.Commands.Add(new UICommand("OK"));
        //        await dialog.ShowAsync();
        //    }
        //}

        public override async void LogoutAsync()
        {
            App.MobileService.Logout();

            string message;
            // This sample uses the Facebook provider.
            var provider = "AAD";

            // Use the PasswordVault to securely store and access credentials.
            PasswordVault vault = new PasswordVault();
            PasswordCredential credential = null;
            try
            {
                // Try to get an existing credential from the vault.
                credential = vault.FindAllByResource(provider).FirstOrDefault();
                vault.Remove(credential);
            }
            catch (Exception)
            {
                // When there is no matching resource an error occurs, which we ignore.
            }
            message = string.Format("You are now logged out!");
            var dialog = new MessageDialog(message);
            dialog.Commands.Add(new UICommand("OK"));
            await dialog.ShowAsync();
            IsLoggedIn = false;

        }
        async void OnDelete(object sender, RoutedEventArgs e)
        {
            MessageDialog dlg    = new Windows.UI.Popups.MessageDialog("Are you sure to remove this child??", "Confirmation");
            UICommand     cmdYes = new UICommand("Yes");
            UICommand     cmdNo  = new UICommand("No");

            dlg.Commands.Add(cmdYes);
            dlg.Commands.Add(cmdNo);
            IUICommand x = await dlg.ShowAsync();

            if (x.Label == "Yes")
            {
                var item  = (JournalItem)(flipView.SelectedItem as FlipViewItemDetailPage).Tag;
                int count = App.AppDataFile.Items[item.Groups].Count;
                await App.AppDataFile.RemoveItem(item);

                await App.AppDataFile.WriteData();

                if (count == 1)
                {
                    this.Frame.Navigate(typeof(GroupedItemsPage));
                }
                else
                {
                    Init(new JournalItem {
                        ImageUri = new Uri("ms-appx:///Assets/Logo.png"),
                    });
                }
            }
        }
        private async Task NavigateToRightPage(bool loginContextPresent, bool projectContextPresent)
        {
            bool loginSuccess = false; ;
            if(loginContextPresent && projectContextPresent)
            {
                Action executeAction = () =>
                {
                    loginSuccess = LoginService.VSTSLogin();
                };

                executeAction();

                if (loginSuccess == false)
                {
                    
                    MessageDialog msgBox = new MessageDialog("Failed to login. Check internet connectivity and try again!");
                    var res = await msgBox.ShowAsync();

                    if(Frame != null)
                    {
                        Frame.Navigate(typeof(LoginPage));
                    }

                }
                else
                {
                    Frame.Navigate(typeof(ServiceSelectionPage));
                }
            }
            else
            {
                Frame.Navigate(typeof(LoginPage));
            }
        }
        private async Task LoginEvent()
        {
            if (IsValidEmail(_emailValue) && IsValidPassword(_passwordValue))
            {
                IsLoading = true;

                try
                {
                    var ds = new DataService();

                    try
                    {
                        await ds.Login(_emailValue, _passwordValue);



                        if (DataService._user.Status != "admin")
                        {
                            IsLoading = false;
                            throw new Exception("You are not admin !");
                        }
                        _navigationService.NavigateTo("WelcomePage");
                    }
                    catch (Exception e)
                    {
                        IsLoading = false;
                        var dialog = new Windows.UI.Popups.MessageDialog(e.Message, "Erreur");

                        dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                        {
                            Id = 0
                        });

                        var result = dialog.ShowAsync();
                    }
                }
                catch (Exception e) {
                    IsLoading = false;
                    var dialog = new Windows.UI.Popups.MessageDialog(e.Message, "Erreur");

                    dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                    {
                        Id = 0
                    });

                    var result = dialog.ShowAsync();
                }
            }
            else
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Email/password isnt valid !");

                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                {
                    Id = 0
                });

                var result = dialog.ShowAsync();
            }
        }
        private async void CheckIn(int roomId)
        {
            if (string.IsNullOrWhiteSpace(FirstName) || string.IsNullOrWhiteSpace(LastName) || SelectedRoom == null)
            {
                MessageDialog dialog = new MessageDialog("You must enter first and last name and select a room", "Error");
                await dialog.ShowAsync();
                return;
            }

            var sensor = new Sensor
            {
                FirstName = FirstName,
                LastName = LastName,
                SensorId = 5,
                SensorMac = "1"
            };

            var presence = new SensorPresence
            {
                RoomId = roomId,
                SensorId = sensor.SensorId,
                TimeStamp = DateTime.Now
            };

            await serverHubProxy.Invoke("RecordLocation", presence, sensor);
            navigationService.NavigateTo("checkedInList");
        }
Example #34
0
        private async void SignUpButton_Click(object sender, RoutedEventArgs e)
        {
            if (UsernameTextBox.Text == "")
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Please enter a username");
                dialog.DefaultCommandIndex = 1;
                await dialog.ShowAsync();
            }
            else if (PasswordTextBox.Password == "")
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Please enter a password");
                dialog.DefaultCommandIndex = 1;
                await dialog.ShowAsync();
            }



            else if (!Regex.IsMatch(EmailTextBox.Text.Trim(), @"^([a-zA-Z_])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])$"))

            {
                var dialog = new Windows.UI.Popups.MessageDialog("Invalid email id");
                dialog.DefaultCommandIndex = 1;
                await dialog.ShowAsync();
            }



            else
            {
                httpClient = new HttpClient();
                string resourceAddress = "";
            }
        }
        // Computes Class Statistics for the image layer using user input graphics as class definition polygons
        private async void ComputeClassStatisticsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
				if (_graphicsOverlay.Graphics.Count < 2)
					throw new ArgumentException("Before computing statistics, enter two or more class definition areas by clicking the image on the map.");

                progress.Visibility = Visibility.Visible;
                if (MyMapView.Editor.IsActive)
                    MyMapView.Editor.Cancel.Execute(null);

                var statsTask = new ComputeClassStatisticsTask(new Uri(_imageLayer.ServiceUri));

                var statsParam = new ComputeClassStatisticsParameters();
				statsParam.ClassDescriptions = _graphicsOverlay.Graphics
                    .Select((g, idx) => new ClassDescription(idx, idx.ToString(), g.Geometry as Polygon)).ToList();

                var result = await statsTask.ComputeClassStatisticsAsync(statsParam);

                _imageLayer.RenderingRule = new RenderingRule()
                {
                    RasterFunctionName = "MLClassify",
                    VariableName = "Raster",
                    RasterFunctionArguments = new Dictionary<string, object> { { "SignatureFile", result.GSG } },
                };
            }
            catch (Exception ex)
            {
				var _ = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
			}
            finally
            {
                progress.Visibility = Visibility.Collapsed;
            }
        }
Example #36
0
 public static async Task DeleteUserAccount(User _user)
 {
     using (HttpClient httpClient = new HttpClient())
     {
         httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
         var keyValues = new Dictionary <string, object>()
         {
             { "idToken", _user.idToken }
         };
         var url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount?key=" + APIKey;
         try
         {
             var refreshTokenResponse = await url
                                        .WithHeader("Accept", "application/json")
                                        .PostJsonAsync(keyValues)
                                        .ReceiveJson <RefreshTokenResponse>();
         }
         catch (FlurlHttpException ex)
         {
             var error = ex.GetResponseJson <ErrorBlock>();
             Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(error.error.message);
             await dialog.ShowAsync();
         }
     }
 }
Example #37
0
        public static async Task <string> post(string key, string url)
        {
            try
            {
                HttpClient client = new HttpClient();
                //准备POST的数据
                var postData = new List <KeyValuePair <string, string> >();
                postData.Add(new KeyValuePair <string, string>("chat", key));
                HttpContent         httpcontent = new FormUrlEncodedContent(postData);
                HttpResponseMessage response    = await client.PostAsync(url, httpcontent);

                Boolean statusCode = response.IsSuccessStatusCode;
                if (!statusCode)
                {
                    Windows.UI.Popups.MessageDialog dlg = new Windows.UI.Popups.MessageDialog("网络通信不畅");
                    await dlg.ShowAsync();

                    return(null);
                }
                //返回的信息
                return(await response.Content.ReadAsStringAsync());
            }
            catch (Exception)
            {
                return("");
            }
        }
Example #38
0
        public static async Task <User> RefreshUserToken(User _user)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
                var keyValues = new Dictionary <string, object>()
                {
                    { "grant_type", "refresh_token" },
                    { "refresh_token", _user.refreshToken }
                };
                var url = "https://securetoken.googleapis.com/v1/token?key=" + APIKey;
                try
                {
                    var refreshTokenResponse = await url
                                               .WithHeader("Accept", "application/json")
                                               .PostJsonAsync(keyValues)
                                               .ReceiveJson <RefreshTokenResponse>();

                    _user.expiresIn    = refreshTokenResponse.expires_in;
                    _user.refreshToken = refreshTokenResponse.refresh_token;
                    _user.idToken      = refreshTokenResponse.id_token;
                    return(_user);
                }
                catch (FlurlHttpException ex)
                {
                    var error = ex.GetResponseJson <ErrorBlock>();
                    Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(error.error.message);
                    await dialog.ShowAsync();
                }
                return(null);
            }
        }
        private async void displayMessageBox(String output)
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog(output);

            messageDialog.Commands.Add(new UICommand("OK", (command) => { }));
            await messageDialog.ShowAsync();
        }
Example #40
0
        public static async Task ResetPassword(string email)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
                var keyValues = new Dictionary <string, object>()
                {
                    { "requestType", "PASSWORD_RESET" },
                    { "email", email }
                };
                var url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key=" + APIKey;
                try
                {
                    await url
                    .WithHeader("Accept", "application/json")
                    .PostJsonAsync(keyValues);

                    MessageDialog dialog = new MessageDialog("Please continue your process through the link that we sent to your E-Mail Address.");
                    await dialog.ShowAsync();
                }
                catch (FlurlHttpException ex)
                {
                    var error = ex.GetResponseJson <ErrorBlock>();
                    Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(error.error.message);
                    await dialog.ShowAsync();
                }
            }
        }
Example #41
0
 private async void BluetoothManager_ExceptionOccured(object sender, Exception ex)
 {
     var md = new MessageDialog(ex.Message, "We've got a problem with bluetooth...");
     md.Commands.Add(new UICommand("Ok"));
     md.DefaultCommandIndex = 0;
     var result = await md.ShowAsync();
 }
Example #42
0
        private async void itemListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var myItem = ((MyTileItem)e.ClickedItem);

            switch (myItem.UniqueId)
            {
                case "Calculer-Vente-PrixDeVente":
                    {
                        //this.Frame.Navigate(typeof(SalePricePage), myItem);
                        var messageDialog =
                            new MessageDialog("Pas implémenté");
                        await messageDialog.ShowAsync();
                    }
                    break;
                case "Calculer-Outils-Convertisseur":
                    {
                        //this.Frame.Navigate(typeof(ConverterPage), myItem);
                        this.Frame.Navigate((typeof(ConverterPage)));
                    }
                    break;
                default:
                    {
                        var messageDialog =
                            new MessageDialog(string.Format(
                                        "Impossible de trouver l'id {0}",
                                        myItem.UniqueId));
                        await messageDialog.ShowAsync();
                    }
                    break;
            }
        }
        private async System.Threading.Tasks.Task RetriveUserInfo(AccessTokenData accessToken)
        {
            var client = new Facebook.FacebookClient(accessToken.AccessToken);

			dynamic result = null;
			bool failed = false;
			try
			{
				result = await client.GetTaskAsync("me?fields=id,birthday,first_name,last_name,middle_name,gender");
			}
			catch(Exception e)
			{
				failed = true;
			}
			if(failed)
			{
				MessageDialog dialog = new MessageDialog("Facebook is not responding to our authentication request. Sorry.");
				await dialog.ShowAsync();

				throw new Exception("Windows phone does not provide an exit function, so we have to crash the app.");
			}
            string fullName = string.Join(" ", new[] { result.first_name, result.middle_name, result.last_name });
            string preferredName = result.last_name;
            bool? gender = null;
            if (result.gender == "female")
            {
                gender = true;
            }
            else if (result.gender == "male")
            {
                gender = false;
            }
            DateTime birthdate = DateTime.UtcNow - TimeSpan.FromDays(365 * 30);
            if (result.birthday != null)
            {
                birthdate = DateTime.Parse(result.birthday);
            }

            var currentUser = new Facebook.Client.GraphUser(result);

            long facebookId = long.Parse(result.id);

            UserState.ActiveAccount = await Api.Do.AccountFacebook(facebookId);
            if (UserState.ActiveAccount == null)
            {
                Frame.Navigate(typeof(CreatePage), new CreatePage.AutofillInfo
                    {
                        SocialId = facebookId,
						Authenticator = Authenticator.Facebook,
                        Birthdate = birthdate,
                        FullName = fullName,
                        Gender = gender,
                        PreferredName = preferredName
                    });
            }
            else
            {
                Frame.Navigate(typeof(MainPage), UserState.CurrentId);
            }
        }
Example #44
0
        private async void JePropose1_Click(object sender, RoutedEventArgs e)
        {
            string message = "";
            var dialog = new MessageDialog("");
            dialog.Title = "Proposition d'évenement :";
            dialog.Commands.Add(new UICommand("OK"));
            var eventSending = new EventGest();
            if (await verifForm())
            {
                var NewEvent = new Event();

                NewEvent.TitreEvent = TextBoxTitre.Text;
                NewEvent.NbParticipEvent = int.Parse(TextBoxNbrPartMax.Text);
                NewEvent.ThemeEvent = ThemeCombo.SelectedItem.ToString();
                NewEvent.AdresseEvent = adressSugest.Text;
                NewEvent.DateEvent = CalendarStart.Date.ToString();
                NewEvent.DescripEvent = DescriptionTextboxTitre.Text;
                NewEvent.PhotoEvent = ImageTextBox.Text;
                NewEvent.IdUser = App.MobileService.CurrentUser.UserId.ToString();
                NewEvent.TimeEvent = TimePicker.Time.Hours.ToString();
                NewEvent.Duration = DurationPicker.Time.ToString();
                eventSending.sendEvent(NewEvent);
                Frame.GoBack();
                message = "Envoyé avec succé :D";
            }
            else
            {
                message = "Champs invalide :(";
            }
            dialog.Content = message;
            await dialog.ShowAsync();
        }
Example #45
0
        private async void OnClick(object sender, RoutedEventArgs e)
        {
            var dialog = new Windows.UI.Popups.MessageDialog("Content", "Title");

            _asyncOperation = dialog.ShowAsync();
            _ = await _asyncOperation;
        }
Example #46
0
        private async void Button_Tapped_1(object sender, TappedRoutedEventArgs e)
        {

            bool cleared = false;
            MessageDialog mBox = new MessageDialog("Selecting yes will clear all the air quality data stored by the app.", "Clear User Data");
            var cmd = new UICommandInvokedHandler((command) =>
            {
                var temp = command.Label;
            });

            mBox.Commands.Add(new UICommand(
                      "Yes", cmd));
            mBox.Commands.Add(new UICommand(
                                  "No", cmd));

            var returnCmd = await mBox.ShowAsync();

            if (String.Equals(returnCmd.Label, "Yes"))
                cleared = await airDB.clear();
            else
                return;

            if (cleared)
            {
                MessageDialog mBox2 = new MessageDialog("User Data Cleared", "User Data");
                mBox2.ShowAsync();
            }
            else
            {
                MessageDialog mBox2 = new MessageDialog("Failed to Clear User Data (there may be none to clear)", "User Data");
                mBox2.ShowAsync();
            }
        }
        private async void Login_Click_1(object sender, RoutedEventArgs e)
        {
            if (wdregno.Text.Length < 9)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog("Invalid Register number!!!");
                var result        = messageDialog.ShowAsync();
            }
            else if (wdpswd.Password.Length < 8)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog("Invalid DOB!!!");
                var result        = messageDialog.ShowAsync();
            }
            else if (cap.Text.Length < 6)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog("Wrong Captcha!!!");
                var result        = messageDialog.ShowAsync();
            }
            else
            {
                string ht = getstring(wdregno.Text, wdpswd.Password, cap.Text);
                ww.Visibility       = Windows.UI.Xaml.Visibility.Collapsed;
                maingrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                bar.Visibility      = Windows.UI.Xaml.Visibility.Visible;
                bar.IsIndeterminate = true;
                Stats.Name          = wdregno.Text;

                Stats.Id = wdpswd.Password;

                await SaveAsync();

                ww.NavigateToString(ht);
            }
            //var messageDialog = new Windows.UI.Popups.MessageDialog("Enter Correct details!!!");
            //var result = messageDialog.ShowAsync();
        }
        public void CountUserPunishment(List <IPunishment> pun)
        {
            int jailCount     = 0;
            int driveoutCount = 0;
            int fineCount     = 0;

            foreach (IPunishment p in pun)
            {
                if (p is Jail)
                {
                    jailCount += p.GetInt();
                }
                else if (p is Driveout)
                {
                    driveoutCount += p.GetInt();
                }
                else if (p is Fine)
                {
                    fineCount += p.GetInt();
                }
            }
            string punisgmentText = (jailCount != 0 ? (jailCount / 12).ToString() + " лет лишения свободы," : "").ToString() + (driveoutCount != 0 ? driveoutCount.ToString() + " месяцев лишение права управления ТС, " : "").ToString() + (fineCount != 0 ? fineCount.ToString() + " руб. штрафа" : "").ToString();

            if (jailCount == 0 & driveoutCount == 0 & fineCount == 0)
            {
                punisgmentText = "нет";
            }
            Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog(punisgmentText);

            md.ShowAsync();
        }
        //Use your consumerKey and ConsumerSecret


        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(pinText.Text))
            {
                var msgDialog = new MessageDialog("Please Enter the pin showed below");
                await msgDialog.ShowAsync();
            }
            else
            {
                var pinCode = pinText.Text.Trim();
                var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(pinCode, authenticationContext);
                Auth.SetCredentials(userCredentials);

                var vault = new PasswordVault();
                vault.Add(new PasswordCredential("Friend", "TwitterAccessToken", userCredentials.AccessToken));
                vault.Add(new PasswordCredential("Friend", "TwitterAccessTokenSecret", userCredentials.AccessTokenSecret));
                var localSettings = ApplicationData.Current.LocalSettings;
                var frame = Window.Current.Content as Frame;

                if (localSettings.Values.ContainsKey("FirstTimeRunComplete"))
                {
                    frame?.Navigate(typeof(MainPage));
                }
                else
                {
                    frame?.Navigate(typeof(FirstTimeTutorial));
                }
            }
        }
        public async override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState) {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);

            ErrorMessageTitle = string.Empty;
            ErrorMessage = string.Empty;

            try {
                LoadingData = true;
                CrudResult crudResult = await _entityRepository.GetEntitiesAsync();
                EntityList = JsonConvert.DeserializeObject<List<Entity>>(crudResult.Content.ToString());
            }
            catch (HttpRequestException ex) {
                ErrorMessageTitle = ErrorMessagesHelper.GetEntitiesAsyncFailedError;
                ErrorMessage = string.Format("{0}{1}", Environment.NewLine, ex.Message);
            }
            catch (Exception ex) {
                ErrorMessageTitle = ErrorMessagesHelper.ExceptionError;
                ErrorMessage = string.Format("{0}{1}", Environment.NewLine, ex.Message);
            }
            finally {
                LoadingData = false;
            }
            if (ErrorMessage != null && ErrorMessage != string.Empty) {
                MessageDialog messageDialog = new MessageDialog(ErrorMessage, ErrorMessageTitle);
                await messageDialog.ShowAsync();
            }
        }
        private async Task StartFlowAsync(string responseType, string scope)
        {
            Exception exception = null;

            try
            {
                _response = await WebAuthentication.DoImplicitFlowAsync(
                    new Uri(Constants.AuthorizeEndpoint),
                    "implicitclient",
                    responseType,
                    scope);

                Output.Text = _response.Raw;
                ParseResponse();
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                var md = new MessageDialog(exception.ToString());
                await md.ShowAsync();
            }
        }
        private async void ListProducts_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Windows.UI.Popups.MessageDialog message;
            try
            {
                Cueros.App.Core.Models.Product _objeto = null;
                var listProducts = await ProductsServices.GetProducts();

                if (ListProducts.SelectedItem != null)
                {
                    var _idProducto = (ListProducts.SelectedItem as Product).ProductID;
                    var result      = from item in listProducts
                                      where item.ProductID == _idProducto
                                      select item;
                    _objeto = result.ToList().FirstOrDefault();
                    Frame.Navigate(typeof(Materiales), _objeto);
                }
                else
                {
                    message = new Windows.UI.Popups.MessageDialog("Seleccione un producto", "Seleccion");
                    await message.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                message = new Windows.UI.Popups.MessageDialog(ex.Message.ToString());
                message.ShowAsync();
            }
        }
 private async void btnSave_Click(object sender, RoutedEventArgs e)
 {
     processBar.Visibility  = Visibility.Visible;
     DataHelper dbHelper = new DataHelper();
     DataBusLine name = new DataBusLine(data.Name, data.Data);
     dbHelper.InsertNewBusLine(name);
     //System.Diagnostics.Debug.WriteLine("Them tuyen");
     DataBusLine newLine = await dbHelper.GetNewLine();
     //System.Diagnostics.Debug.WriteLine("Lay gia tri vua them");
     int i = 0;
     if (newLine != null)
     {
         foreach (var item in data.ListPoints)
         {
             i++;
             DataPoint dataPoint = new DataPoint(item.Name, newLine.Id, item.Long, item.Lat);
             dbHelper.InsertNewPoint(dataPoint);
             //System.Diagnostics.Debug.WriteLine("Them diem");
         }
         processBar.Visibility = Visibility.Collapsed;
         var dialog = new MessageDialog("Lưu dữ liệu thành công! total: " + i);
         await dialog.ShowAsync();
         System.Diagnostics.Debug.WriteLine(data.Name);
         System.Diagnostics.Debug.WriteLine(data.Data);
     }
     Frame.Navigate(typeof (MainPage));
 }
        async void ErrorConexion()
        {
            var message = new Windows.UI.Popups.MessageDialog("Sin conexion", "Conexion fallida :(");

            message.DefaultCommandIndex = 1;
            await message.ShowAsync();
        }
 private void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     var errorMessage = e.Exception.ToString();
     Debug.WriteLine(errorMessage);
     var message = new MessageDialog(errorMessage, "An error occurred").ShowAsync();
     e.Handled = true;
 }
		private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
		{
			try
			{
				_trafficOverlay.Visibility = Visibility.Collapsed;
				_trafficOverlay.DataContext = null;

				var identifyTask = new IdentifyTask(new Uri(_trafficLayer.ServiceUri));
				// Get current viewpoints extent from the MapView
				var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
				var viewpointExtent = currentViewpoint.TargetGeometry.Extent;

				IdentifyParameters identifyParams = new IdentifyParameters(e.Location, viewpointExtent, 5, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth)
				{
					LayerIDs = new int[] { 2, 3, 4 },
					LayerOption = LayerOption.Top,
					SpatialReference = MyMapView.SpatialReference,
				};

				var result = await identifyTask.ExecuteAsync(identifyParams);

				if (result != null && result.Results != null && result.Results.Count > 0)
				{
					_trafficOverlay.DataContext = result.Results.First();
					_trafficOverlay.Visibility = Visibility.Visible;
				}
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
			}
		}
        public RecentThreadsViewModel(
            RecentThreadsService repositoryService,
            IBoard board,
            IShell shell,
            FavoriteThreadsService favoriteThreads)
            : base(repositoryService, board, shell) {

            FavoriteThreads = favoriteThreads;
            var dialog = new MessageDialog(
                Localization.GetForView("RecentThreads", "ClearConfirmationContent"),
                Localization.GetForView("RecentThreads", "ClearConfirmationTitle"));

            dialog.AddButton(
                Localization.GetForView("RecentThreads", "ConfirmClear"),
                async () => {
                    IsLoading = true;
                    Threads.Clear();
                    RepositoryService.Items.Clear();
                    await RepositoryService.Save();
                    IsLoading = false;
                });

            dialog.AddButton(
                Localization.GetForView("RecentThreads", "DontClear"), () => { });

            ClearConfirmationDialog = dialog;
        }
Example #58
0
		public static async Task<MessageBoxResult> ShowAsync ( string messageBoxText,
															 string caption,
															 MessageBoxButton button )
		{

			MessageDialog md = new MessageDialog ( messageBoxText, caption );
			MessageBoxResult result = MessageBoxResult.None;
			if ( button.HasFlag ( MessageBoxButton.OK ) )
			{
				md.Commands.Add ( new UICommand ( "OK",
					new UICommandInvokedHandler ( ( cmd ) => result = MessageBoxResult.OK ) ) );
			}
			if ( button.HasFlag ( MessageBoxButton.Yes ) )
			{
				md.Commands.Add ( new UICommand ( "Yes",
					new UICommandInvokedHandler ( ( cmd ) => result = MessageBoxResult.Yes ) ) );
			}
			if ( button.HasFlag ( MessageBoxButton.No ) )
			{
				md.Commands.Add ( new UICommand ( "No",
					new UICommandInvokedHandler ( ( cmd ) => result = MessageBoxResult.No ) ) );
			}
			if ( button.HasFlag ( MessageBoxButton.Cancel ) )
			{
				md.Commands.Add ( new UICommand ( "Cancel",
					new UICommandInvokedHandler ( ( cmd ) => result = MessageBoxResult.Cancel ) ) );
				md.CancelCommandIndex = ( uint ) md.Commands.Count - 1;
			}
			var op = await md.ShowAsync ();
			return result;
		}
Example #59
0
        public async void CheckInternet()
        {
            while (!App.IsInternetAvailable)
            {


                var messageDialog = new MessageDialog(("No data connection has been found."));

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
                messageDialog.Commands.Add(new UICommand(
                    "Try again",
                    new UICommandInvokedHandler(this.CommandInvokedHandlerInternet)));
                messageDialog.Commands.Add(new UICommand(
                    "Close",
                    new UICommandInvokedHandler(this.CommandInvokedHandlerInternet)));

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 0;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                // Show the message dialog
                try
                {
                   await messageDialog.ShowAsync();
                }
                catch { }
            }
             getAll();
             MainPage.getData();
        }
Example #60
0
        public DialogResult ShowDialog(Control parent)
        {
#if TODO_XAML // EnableThemingInScope was removed as it uses PInvoke
            using (var visualStyles = new EnableThemingInScope(ApplicationHandler.EnableVisualStyles))
#endif
            {
                var messageDialog = new wup.MessageDialog(Text ?? "", Caption ?? "");
                messageDialog.ShowAsync();

#if TODO_XAML
                var element = parent == null ? null : parent.GetContainerControl();
                var window  = element == null ? null : element.GetParent <sw.Window>();
                sw.MessageBoxResult result;
                var buttons       = Convert(Buttons);
                var defaultButton = Convert(DefaultButton, Buttons);
                var icon          = Convert(Type);
                var caption       = Caption ?? ((parent != null && parent.ParentWindow != null) ? parent.ParentWindow.Title : null);
                if (window != null)
                {
                    result = WpfMessageBox.Show(window, Text, caption, buttons, icon, defaultButton);
                }
                else
                {
                    result = WpfMessageBox.Show(Text, caption, buttons, icon, defaultButton);
                }
                return(Convert(result));
#else
                return(DialogResult.Ok);                // TODO: this returns immediately, but the MessageDialog appears asynchronously. Fix the Eto API to be asynchronous.
#endif
            }
        }