ShowAsync() public method

public ShowAsync ( ) : IAsyncOperation
return IAsyncOperation
        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();
            }
        }
        private async void buttonAgregar_Click(object sender, RoutedEventArgs e)
        {
            MessageDialog mensajeError = new MessageDialog("Los campos con * son OBLIGATORIOS");
            int error = -1;

            if (comboBoxCiudad.SelectedIndex != 0 || comboBoxEstado.SelectedIndex != 0 || textboxCodigoPostal.Text.Length != 0)
            {
                int idCiudad = listaCiudad[comboBoxCiudad.SelectedIndex-1].Id;
                if (BufferUsuario.Usuario != null)
                {
                    error = await servicio.agregarDireccionUsuarioAsync(BufferUsuario.Usuario.Id, idCiudad, textBoxDetalle.Text, int.Parse(textboxCodigoPostal.Text));
                    if (error == 1)
                    {
                        BufferUsuario.Usuario.Direcciones = await servicio.buscarDireccionUsuarioAsync(BufferUsuario.Usuario.Id);
                        var rootFrame = new Frame();
                        pagina.cargarDireciones();
                        popup.IsOpen = false;
                        servicio.enviarCorreoDeModificacionAsync(BufferUsuario.Usuario);
                    }
                }
                
            }
            else
            {
                mensajeError.ShowAsync();
            }

            if (error == 0)
            {
                mensajeError.Content = "No se pudo agregar la nueva dirección";
                mensajeError.ShowAsync();

            }

        }
Example #5
0
 private async void OnClick(object sender, RoutedEventArgs e)
 {
     Button btn = sender as Button;
     MessageDialog msgBox = new MessageDialog("请输入姓名、城市和年龄。");
     if(txtName.Text == "" || txtCity.Text == "" || txtAge.Text == "")
     {
         await msgBox.ShowAsync();
         return;
     }
     btn.IsEnabled = false;
     // 获取文档库目录
     StorageFolder doclib = KnownFolders.DocumentsLibrary;
     // 将输入的内容转化为 json 对象
     JsonObject json = new JsonObject();
     json.Add("name", JsonValue.CreateStringValue(txtName.Text));
     json.Add("city", JsonValue.CreateStringValue(txtCity.Text));
     json.Add("age", JsonValue.CreateNumberValue(Convert.ToDouble(txtAge.Text)));
     // 提取出 json 字符串
     string jsonStr = json.Stringify();
     // 在文档库中创建新文件
     string fileName = DateTime.Now.ToString("yyyy-M-d-HHmmss") + ".mydoc";
     StorageFile newFile = await doclib.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
     // 将 json 字符串写入文件
     await FileIO.WriteTextAsync(newFile, jsonStr);
     btn.IsEnabled = true;
     msgBox.Content = "保存成功";
     await msgBox.ShowAsync();
 }
        private async void btSalvar_Click(object sender, RoutedEventArgs e)
        {

            MessageDialog dialog = new MessageDialog("");
            double consumo = 0;

            if (tbPotencia.Text != null && tbPotencia.Text.Trim() != "" && tbNome.Text != null && tbNome.Text.Trim() != "" 
                && tbHoras.Text != null && tbHoras.Text.Trim() != "" && tbDias.Text != null && tbDias.Text.Trim() != "")
            {

                if (!(IsNumber(tbDias.Text) && IsNumber(tbHoras.Text) && IsNumber(tbPotencia.Text)))
                {
                    dialog.Content = "Entrada inválida!";
                    await dialog.ShowAsync();
                }
                else
                {

                    tbDias.Text = FinancasPage.ValidateAndReplaceComa(tbDias.Text);
                    tbHoras.Text = FinancasPage.ValidateAndReplaceComa(tbHoras.Text);
                    tbPotencia.Text = FinancasPage.ValidateAndReplaceComa(tbPotencia.Text);

                    if (double.Parse(tbDias.Text) > 0 && double.Parse(tbHoras.Text) > 0 && double.Parse(tbPotencia.Text) > 0)
                    {
                        consumo = ((double.Parse(tbPotencia.Text) / 1000) * double.Parse(tbDias.Text) * double.Parse(tbHoras.Text)) ;

                        Eletrodomestico eletrodomestico = new Eletrodomestico();
                        eletrodomestico.Consumo = consumo;
                        eletrodomestico.DiasUsado = int.Parse(tbDias.Text);
                        eletrodomestico.TempoDeUso = double.Parse(tbHoras.Text);
                        eletrodomestico.Potencia = double.Parse(tbPotencia.Text);
                        eletrodomestico.Nome = tbNome.Text;
                        eletrodomestico.UsuarioId = HomePage.currentUser.Id;

                        await App.MobileService.GetTable<Eletrodomestico>().InsertAsync(eletrodomestico);

                        dialog.Content = "Eletrodoméstico inserido com sucesso!";
                        await dialog.ShowAsync();
                        LimparTextBox();
                        App.MnFrame.Navigate(typeof(MeusEletrodomesticosPage)); 
                    }
                    else
                    {
                        dialog.Content = "Entrada inválida!";
                        await dialog.ShowAsync();
                    }
                }
            }
            else
            {
                
                dialog.Content = "Todos os campos devem ser preenchidos!";
                await dialog.ShowAsync();
            }

        }
Example #7
0
 public async static void ShowDialog(MessageDialog dialog)
 {
     if (dispatcher != null)
     {
         await dispatcher.RunAsync(CoreDispatcherPriority.Normal,
             async () =>
             {
                 await dialog.ShowAsync();
             });
     }
     else
         await dialog.ShowAsync();
 }
        private async void login_Click(object sender, RoutedEventArgs e)
        {
            var i = new MessageDialog("");
           
            //若没有输入账号密码就开始登录
            if(account.Text == "")
            {
                i.Content = "请输入账号";
                await i.ShowAsync();
            }
            else if(password.Text == "")
            {
                i.Content = "请输入密码";
                await i.ShowAsync();
            }
            else
            {
                var db = App.conn;
                using (var statement = db.Prepare("SELECT * FROM Players WHERE Account = ? AND Password = ?"))
                {
                    statement.Bind(1, account.Text);
                    statement.Bind(2, password.Text);
                    if (statement.Step() == SQLiteResult.ROW)
                    {
                        try
                        {
                            var username = (string)statement[1];
                            var password = (string)statement[2];
                            var account = (string)statement[3];
                            long highestScore = (long)statement[4];
                            App.Player = new Models.player(username, password, account, (string)statement[5], highestScore);
                            //若登录成功
                            Frame.Navigate(typeof(EnterPage), App.Player);
                        }
                        catch (Exception err)
                        {

                        }
                    }
                    else
                    {
                        var p = new MessageDialog("请输入正确的账号和密码").ShowAsync();
                    }
                }
            }

            //若登录不成功(账号密码不匹配之类)需添加代码(还有一个else if)

        }
		private async void showAsync(string title, string message, MessageBoxTypes type, MessageBoxOptions options, MessageBoxCallback callback)
		#endif
		{
			#if WINDOWS_PHONE
			WinRTPlugin.Dispatcher.BeginInvoke(delegate()
			{
				// XNA method
				Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(title, message,
				new System.Collections.Generic.List<string> {options.OkButtonName, options.CancelButtonText}, 0, Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.Error,
				asyncResult =>
				{
					int? result = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(asyncResult);
					ReignServices.InvokeOnUnityThread(delegate
					{
						if (callback != null) callback(result == 0 ? MessageBoxResult.Ok : MessageBoxResult.Cancel);
					});
				}, null);

				// Silverlight method. (Doesn't support custom named buttons)
				//var result = MessageBox.Show(message, title, type == MessageBoxTypes.Ok ? MessageBoxButton.OK : MessageBoxButton.OKCancel);
				//if (callback != null) callback(result == System.Windows.MessageBoxResult.OK ? MessageBoxResult.Ok : MessageBoxResult.Cancel);
			});
			#else
			await WinRTPlugin.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async delegate()
			{
				var msg = new MessageDialog(message, title);
				if (type == MessageBoxTypes.Ok)
				{
					await msg.ShowAsync();
					ReignServices.InvokeOnUnityThread(delegate
					{
						if (callback != null) callback(MessageBoxResult.Ok);
					});
				}
				else if (type == MessageBoxTypes.OkCancel)
				{
					bool result = false;
					msg.Commands.Add(new UICommand(options.OkButtonName, new UICommandInvokedHandler((cmd) => result = true)));
					msg.Commands.Add(new UICommand(options.CancelButtonText, new UICommandInvokedHandler((cmd) => result = false)));
					await msg.ShowAsync();
					ReignServices.InvokeOnUnityThread(delegate
					{
						if (callback != null) callback(result ? MessageBoxResult.Ok : MessageBoxResult.Cancel);
					});
				}
			});
			#endif
		}
Example #10
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;
		}
        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 #12
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);
        }
 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));
 }
        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();
        }
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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
            }
        }
Example #22
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 #23
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 #24
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 displayMessageBox(String output)
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog(output);

            messageDialog.Commands.Add(new UICommand("OK", (command) => { }));
            await messageDialog.ShowAsync();
        }
Example #26
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);
        }
Example #27
0
        private async void OnClick(object sender, RoutedEventArgs e)
        {
            var dialog = new Windows.UI.Popups.MessageDialog("Content", "Title");

            _asyncOperation = dialog.ShowAsync();
            _ = await _asyncOperation;
        }
        async void ErrorConexion()
        {
            var message = new Windows.UI.Popups.MessageDialog("Sin conexion", "Conexion fallida :(");

            message.DefaultCommandIndex = 1;
            await message.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));
                }
            }
        }
Example #30
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();
            }
        }
Example #31
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();
                }
            }
        }
Example #32
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();
            }
        }
Example #33
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 #34
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();
        }
        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();
        }
Example #36
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();
        }
        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 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 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));
            }
        }
Example #40
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 = "";
            }
        }
Example #41
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("");
            }
        }
        private async void Connect()
        {
            var users = Users.Where(u => u.UserName == UserCurrent.UserName);
            if (Users.Any())
            {
                if (UsersController.Initialize().First().Password == UserCurrent.Password)
                {
                    UsersController.IsConnected = true;

                    //Permet de naviguer vers la page ListClientsPage
                    //true indique que l'on souhaite lancer une nouvelle instance du ViewModel
                    NavigationService.NavigateTo<ListClientsPageViewModel>(true);
                }
                else
                {
                    var message = new MessageDialog("Mot de passe incorrect", "Erreur");
                    await message.ShowAsync();
                }
            }
            else
            {
                var message = new MessageDialog("Utilisateur inconnu", "Erreur");
                await message.ShowAsync();
            }
        }
Example #43
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();
     }
 }
        private async void SendData()
        {
            pairs.Clear();
            pairs.Add("country", country.Text);
            pairs.Add("airport", airport.Text);
            HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
            await clientOb.PostAsync(connectionUri, formContent);

            Windows.Web.Http.HttpResponseMessage response = await clientOb.PostAsync(connectionUri, formContent);

            if (!response.IsSuccessStatusCode)
            {
                var dialog = new MessageDialog("Error while Adding a trip", "Error");
                await dialog.ShowAsync();
            }
            else
            {

                responseBodyAsText = await response.Content.ReadAsStringAsync();
                responseBodyAsText = responseBodyAsText.Replace("<br>", Environment.NewLine); // Insert new lines
                if (responseBodyAsText.Substring(13, 2).Equals("ko"))
                {
                    var dialog = new MessageDialog("Error in Adding", "Error");
                    await dialog.ShowAsync();
                }
                else
                {
                    {
                        var dialog = new MessageDialog("Trip Added", "Added");
                        await dialog.ShowAsync();
                    }
                }

            }
        }
Example #45
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 #46
0
 private async void ChartOnDataClick(object sender, ChartPoint chartPoint)
 {
     var asPixels = this.Chart.ConvertToPixels(chartPoint.AsPoint());
     var dialog = new MessageDialog("You clicked (" + chartPoint.X + ", " + chartPoint.Y + ") in pixels (" +
                     asPixels.X + ", " + asPixels.Y + ")");
     await dialog.ShowAsync();
 }
        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 #48
0
        public async void ShowDialog(string messageText, string title = "BattleMech") {
            var dialog = new MessageDialog(messageText, title);

            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => {
                await dialog.ShowAsync();
            });
        }
Example #49
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)
                {
                }
            }
        }
        // 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;

        }
 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 #52
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
            }
        }
        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();
            }
        }
Example #54
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 #55
0
        private async Task SendNewPublicationEvent()
        {
            if (DescriptionValidation() && TitleValidation())
            {
                var ds = new DataService();
                try
                {
                    await ds.ModifyPubliction(SelectedPublication.Id, _titleValue, _descriptionValue);

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

                    _navigationService.NavigateTo("WelcomePage");
                }
                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();
            }
        }
Example #56
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;
            }
        }
Example #57
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();
         }
     }
 }
        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();
            }
        }
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 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);
            }
        }