コード例 #1
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            drug = e.Parameter as string;
            Windows.UI.Popups.MessageDialog m = new Windows.UI.Popups.MessageDialog("what is this: " + drug);

            m.ShowAsync();
        }
コード例 #2
0
ファイル: UserRole.cs プロジェクト: Guanyi/UWPDiplomaOptions
        public static async Task GetUserRoles(ObservableCollection<UserRole> UserRoleList)
        {
            var response = await http.GetAsync("http://uwproject.feifei.ca/api/ApplicationRoles");
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                JsonValue value = JsonValue.Parse(result);
                JsonArray root = value.GetArray();
                for (uint i = 0; i < root.Count; i++)
                {
                    string id = root.GetObjectAt(i).GetNamedString("Id");
                    string name = root.GetObjectAt(i).GetNamedString("Name");
                    var userRole = new UserRole
                    {
                        Id = id,
                        Name = name
                    };
                    UserRoleList.Add(userRole);
                }
            }
            else
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Cannot retrieve any record");
                await dialog.ShowAsync();
            }
        }
コード例 #3
0
ファイル: RateMyApp.cs プロジェクト: dmitry-osin/Drugs.WP8.1
        private async Task AskForReviewAsync()
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog(RateMyApp.REVIEW_TEXT);

            messageDialog.Commands.Add(new Windows.UI.Popups.UICommand(RateMyApp.REVIEW_INVITE_TEXT,
                async (action) =>
                {
#if WINDOWS_PHONE_APP
                    var uri = new Uri("ms-windows-store:reviewapp?appid=" + CurrentApp.AppId);
#elif WINDOWS_APP
                    var uri = new Uri("ms-windows-store:Review?PFN=" + Windows.ApplicationModel.Package.Current.Id.FamilyName);
#endif
                    await Windows.System.Launcher.LaunchUriAsync(uri);

                    this.status["userReviewedApp"] = true;
                    this.SaveReviewStatus();
                }
                ));

            messageDialog.Commands.Add(new Windows.UI.Popups.UICommand(RateMyApp.REVIEW_DECLINE_TEXT, null));

            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex = 1;

            await messageDialog.ShowAsync();
        }
コード例 #4
0
        public async void CaptureImage()
        {
            var dialog = new Windows.UI.Popups.MessageDialog("Would you like to use your camera or select a picture from your library?");
            dialog.Commands.Add(new Windows.UI.Popups.UICommand("I'd like to use my camera", null, "camera"));
            dialog.Commands.Add(new Windows.UI.Popups.UICommand("I already have the picture", null, "picker"));

            IStorageFile photoFile;
            var command = await dialog.ShowAsync();
            if ((string) command.Id == "camera")
            {
                var cameraCapture = new Windows.Media.Capture.CameraCaptureUI();
                photoFile = await cameraCapture.CaptureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.Photo);
            }
            else
            {
                var photoPicker = new FileOpenPicker();
                photoPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                photoPicker.FileTypeFilter.Add(".png");
                photoPicker.FileTypeFilter.Add(".jpg");
                photoPicker.FileTypeFilter.Add(".jpeg");

                photoFile = await photoPicker.PickSingleFileAsync();
            }

            if (photoFile == null)
                return;

            var raStream = await photoFile.OpenAsync(FileAccessMode.Read);
            Customer.ImageStream = raStream.AsStream();
        }
        public async void getPredictFailure()
        {
            try
            {
                List<string> QList = new List<string>();
                List<Double> FList = new List<Double>();


                var q = ParseObject.GetQuery("FailureNextWeek");

                    //    where allgroupname.Get<string>("EquipmentName") != ""
                    //    select allgroupname;

                var f = await q.FindAsync();


                foreach (var obj in f)
                {
                    QList.Add(obj.Get<String>("EquipmentName"));
                    FList.Add(obj.Get<Double>("FailureProbability"));

                    EquipmentNamelistView.ItemsSource = QList;
                    FPlistView.ItemsSource = FList;



                }
            }
            catch (Exception ex)
            {
                Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog(ex.Message);
                md.ShowAsync();
            }

        }
コード例 #6
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
             pickedContact = null;

            var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();
            contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);

            var contact = await contactPicker.PickContactAsync();

            if (contact != null)
            {
                string msg = "Got contact " + contact.DisplayName + " with phone numbers:  ";
                foreach (var phone in contact.Phones)
                {
                    msg += (phone.Kind.ToString() + "   " + phone.Number);
                }

                var dlg = new Windows.UI.Popups.MessageDialog(msg);
                await dlg.ShowAsync();

                pickedContact = contact;


            }
        }
コード例 #7
0
        private static async Task<bool> IsValid(OrderViewModel orderViewModel)
        {
            if (string.IsNullOrWhiteSpace(orderViewModel.Customer))
            {
                var messageBox = new Windows.UI.Popups.MessageDialog("You must specify a customer name.", "Warning!");
                await messageBox.ShowAsync();
                return false;
            }

            if (string.IsNullOrWhiteSpace(orderViewModel.SelectedProduct))
            {
                var messageBox = new Windows.UI.Popups.MessageDialog("You must select a product.", "Warning!");
                await messageBox.ShowAsync();
                return false;
            }

            if (orderViewModel.SelectedAmount == -1)
            {
                var messageBox = new Windows.UI.Popups.MessageDialog("You must select an amount.", "Warning!");
                await messageBox.ShowAsync();
                return false;
            }

            return true;
        }
コード例 #8
0
ファイル: YearTerm.cs プロジェクト: Guanyi/UWPDiplomaOptions
        public static async Task GetYearTerms(ObservableCollection<YearTerm> YearTermsList)
        {
            var response = await http.GetAsync("http://uwproject.feifei.ca/api/YearTerms");
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                JsonValue value = JsonValue.Parse(result);
                JsonArray root = value.GetArray();
                for (uint i = 0; i < root.Count; i++)
                {
                    int yearTermId = (int)root.GetObjectAt(i).GetNamedNumber("YearTermId");
                    int year = (int)root.GetObjectAt(i).GetNamedNumber("Year");
                    int term = (int)root.GetObjectAt(i).GetNamedNumber("Term");
                    bool isDefault = root.GetObjectAt(i).GetNamedBoolean("IsDefault");
                    string description = root.GetObjectAt(i).GetNamedString("Description");
                    var yearTerm = new YearTerm
                    {
                        YearTermId = yearTermId,
                        Year = year,
                        Term = term,
                        IsDefault = isDefault,
                    };
                    YearTermsList.Add(yearTerm);
                }
            }
            else
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Cannot retrieve any record");
                await dialog.ShowAsync();
            }
        }
コード例 #9
0
        private async void cambiarMiInfo(object sender, RoutedEventArgs e)
        {
            Esperar1.Visibility = Visibility.Visible;
            try
            {
                var trata = new ParseObject("User");
                trata.ObjectId = usu.Id;
                trata["Nombre"] = nombre.Text;
                trata["Apellido"] = apellido.Text;
                trata["email"] = correo.Text;
                trata["telefono"] = int.Parse(telefono.Text);
                trata["cedula"] = cedula.Text;
                trata["username"] = username.Text;
                trata["password"] = password.Password;

                usu.Nombre = nombre.Text;
                usu.Apellido = apellido.Text;
                usu.Correo = correo.Text;
                usu.Telefono = uint.Parse(telefono.Text);
                usu.Cedula = cedula.Text;
                usu.Username = username.Text;
                usu.Password = password.Password;

                await trata.SaveAsync();
                Esperar1.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                Esperar1.Visibility = Visibility.Collapsed;
                var dialog = new Windows.UI.Popups.MessageDialog("Tu información no ha podido ser editada");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK") { });
                var result = await dialog.ShowAsync();
            }
        }
コード例 #10
0
        private async void saveEditRecordatorio(object sender, RoutedEventArgs e)
        {
            if (validarDatos() == 1) //campos validados
            {
                fact.Alarma = getFechaAlarma();
                fact.Estado = "Pendiente";
                fact.Valor = Convert.ToInt32(txtValor.Text);

                factDao.updateFactura(fact);  //actualizo el objeto en la base de datos, y se actualiza en la coleccion de objetos

                //redirijo a la MainPage
                rootFrame.Navigate(typeof(MainPage), "1");
            }
            if (validarDatos() == 2) //problemas con la fecha 
            {
                var dialog = new Windows.UI.Popups.MessageDialog("No te podemos notificar " + (txtDia.SelectedIndex + 1) + " días antes, el día límite es el " + txtVence.Text, "Algo sucede!");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Entendido") { Id = 1 });
                var result = await dialog.ShowAsync();
            }
            if (validarDatos() == 0)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Falta información para crear el recordatorio", "Falta Información!");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Entendido") { Id = 1 });
                var result = await dialog.ShowAsync();
            }

        }
コード例 #11
0
        private async void onClickSiguiente(object sender, RoutedEventArgs e)
        {
            this.nombre = nombrePlan.Text;
            this.descripcion = descripcionPlan.Text;
            this.fecha = fechaPlan.Date.Day + "/" + fechaPlan.Date.Month + "/" + fechaPlan.Date.Year;
            this.hora = configurarHora(horaPlan.Time.Hours, horaPlan.Time.Minutes);

            if (nombre.Equals("") && descripcion.Equals(""))
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Por favor llene los campos");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK") { Id = 0 });
                var result = await dialog.ShowAsync();
            }
            else
            {
                if (photo == null)
                {
                    var packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
                    var assetsFolder = await packageLocation.GetFolderAsync("Assets");
                    photo = await assetsFolder.GetFileAsync("fotoplan.jpg");

                }

                Plan plan = new Plan()
                {
                    NombrePlan = nombre,
                    DescripcionPlan = descripcion,
                    FechaPlan = fecha,
                    HoraPlan = hora,
                    ImagenPlan = photo
                };
                Frame rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(AddMapa), plan);
            }
        }
コード例 #12
0
        private async void Next_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtDictTitle.Text))
                    throw new Exception("Please provide a dictionary title");

                if (await similarDictionaryFileNameExists())
                {
                    var dlg = new Windows.UI.Popups.MessageDialog("A dictionary titled '" + txtDictTitle.Text + "' already exists.\nPlease choose a different name");
                    await dlg.ShowAsync();
                    return;
                }

                // Go to the next stage where you can opt to import from text files
                if (this.Frame != null)
                {
                    this.Frame.Navigate(typeof(TextFileImport), txtDictTitle.Text);
                }
            }
            catch (Exception ex)
            {
                if (this.Frame != null)
                {
                    this.Frame.Navigate(typeof(MessagePopup), ex.Message);
                }
            }
        }
コード例 #13
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            json = e.Parameter as string;
            Windows.UI.Popups.MessageDialog m = new Windows.UI.Popups.MessageDialog("Test: " + json);

            m.ShowAsync();
        }
コード例 #14
0
ファイル: Option.cs プロジェクト: Guanyi/UWPDiplomaOptions
 public static async Task GetOptions(ObservableCollection<Option> OptionsList)
 {
     var response = await http.GetAsync("http://uwproject.feifei.ca/api/Options");
     if (response.IsSuccessStatusCode)
     {
         var result = await response.Content.ReadAsStringAsync();
         JsonValue value = JsonValue.Parse(result);
         JsonArray root = value.GetArray();
         for (uint i = 0; i < root.Count; i++)
         {
             int optionId = (int)root.GetObjectAt(i).GetNamedNumber("OptionId");
             string title = root.GetObjectAt(i).GetNamedString("Title");
             bool isActive = root.GetObjectAt(i).GetNamedBoolean("IsActive");
             var option = new Option
             {
                 OptionId = optionId,
                 Title = title,
                 IsActive = isActive,
             };
             OptionsList.Add(option);
         }
     }
     else
     {
         var dialog = new Windows.UI.Popups.MessageDialog("Cannot retrieve any record");
         await dialog.ShowAsync();
     }
 }
コード例 #15
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            SetupPersonGroup();

            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            bool permissionGained = await RequestMicrophonePermission();

            if (!permissionGained)
                return; // No permission granted

            Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
            string langTag = speechLanguage.LanguageTag;
            speechContext = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { langTag };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

            await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);

            try
            {
                await speechRecognizer.ContinuousRecognitionSession.StartAsync();
            }
            catch (Exception ex)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                await messageDialog.ShowAsync();
            }

        }
		private async void RecognizeWithSRGSGrammarFileConstraintOnce_Click(object sender, RoutedEventArgs e)
		{
			this.heardYouSayTextBlock.Visibility = this.resultTextBlock.Visibility = Visibility.Collapsed;

			// Start recognition.
			try
			{
				Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = await this.speechRecognizer.RecognizeWithUIAsync();
				// If successful, display the recognition result.
				if (speechRecognitionResult.Status == Windows.Media.SpeechRecognition.SpeechRecognitionResultStatus.Success)
				{
					this.heardYouSayTextBlock.Visibility = this.resultTextBlock.Visibility = Visibility.Visible;
					this.resultTextBlock.Text = speechRecognitionResult.Text;
				}
			}
			catch (Exception exception)
			{
				if ((uint)exception.HResult == App.HResultPrivacyStatementDeclined)
				{
					this.resultTextBlock.Visibility = Visibility.Visible;
					this.resultTextBlock.Text = "The privacy statement was declined.";
				}
				else
				{
					var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
					messageDialog.ShowAsync().GetResults();
				}
			}

			this.InitializeSpeechRecognizer();
		}
コード例 #17
0
        private async void CreateButton_Click(object sender, RoutedEventArgs e)
        {
            if (!App.HasConnectivity)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog("You can't create a Read it Later account until you have Internet access. Please try again once you're connected to the Internet.", "Error");

                await messageDialog.ShowAsync();

                return;
            }

            if (!string.IsNullOrWhiteSpace(passwordPasswordBox.Password) &&
                !string.IsNullOrWhiteSpace(usernameTextBox.Text))
            {
                var username = usernameTextBox.Text;
                var password = passwordPasswordBox.Password;

                var api = new ReadItLaterApi.Metro.ReadItLaterApi(username, password);

                if (await api.CreateAccount())
                {
                    SaveSettings(usernameTextBox.Text.Trim(), passwordPasswordBox.Password);

                    Hide();
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("There was an error creating your Read it Later account. Please try again later.", "Error");
    
                    await messageDialog.ShowAsync();
                }
            }
        }
コード例 #18
0
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            MarktplaatsItems feedDataSource = (MarktplaatsItems)App.Current.Resources["feedDataSource"];
            var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();

            if (connectionProfile != null)
            {

                MarktPlaatsConnection mp = new MarktPlaatsConnection();
                if (feedDataSource != null)
                {
                    feedDataSource = await mp.GetMarktplaatsItems(navigationParameter.ToString());
                }
            }
            else
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog("An internet connection is needed to download feeds. Please check your connection and restart the app.");
                var result = messageDialog.ShowAsync();
            }

            if (feedDataSource != null)
            {
                this.DefaultViewModel["Items"] = feedDataSource.Items;
                App.Current.Resources["feedDataSource"] = feedDataSource;
            }
        }
コード例 #19
0
ファイル: MainViewModel.cs プロジェクト: catrubens/Henallux
        private async void BookReseravation_Click(Book book)
        {
            var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
            string strVR = loader.GetString("ValideReservation");
            string yes = loader.GetString("Yes");
            string no = loader.GetString("No");
            var dialog = new Windows.UI.Popups.MessageDialog(book.Title+"\n" + strVR);      
            dialog.Commands.Add(new Windows.UI.Popups.UICommand(yes) { Id = 1 });
            dialog.Commands.Add(new Windows.UI.Popups.UICommand(no) { Id = 0 });

            var result = await dialog.ShowAsync();

            if ((int)result.Id == 1)
            {
                var duplicate = false;
                foreach (var b in bookReservation)
                {
                    if (b.NumBook == book.NumBook)
                        duplicate = true;
                }
                if(duplicate == false)
                    bookReservation.Add(book);
                else
                {
                    var str = loader.GetString("Duplicate");
                    dialog = new Windows.UI.Popups.MessageDialog(str);
                    await dialog.ShowAsync();
                }
            }
        }
コード例 #20
0
        private async void OnTargetFileRequested(FileSavePickerUI sender, TargetFileRequestedEventArgs e)
        {
            // This scenario demonstrates how the app can go about handling the TargetFileRequested event on the UI thread, from
            // which the app can manipulate the UI, show error dialogs, etc.

            // Requesting a deferral allows the app to return from this event handler and complete the request at a later time.
            // In this case, the deferral is required as the app intends on handling the TargetFileRequested event on the UI thread.
            // Note that the deferral can be requested more than once but calling Complete on the deferral a single time will complete
            // original TargetFileRequested event.
            var deferral = e.Request.GetDeferral();

            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                // This method will be called on the app's UI thread, which allows for actions like manipulating
                // the UI or showing error dialogs

                // Display a dialog indicating to the user that a corrective action needs to occur
                var errorDialog = new Windows.UI.Popups.MessageDialog("If the app needs the user to correct a problem before the app can save the file, the app can use a message like this to tell the user about the problem and how to correct it.");
                await errorDialog.ShowAsync();

                // Set the targetFile property to null and complete the deferral to indicate failure once the user has closed the
                // dialog.  This will allow the user to take any neccessary corrective action and click the Save button once again.
                e.Request.TargetFile = null;
                deferral.Complete();
            });
        }
コード例 #21
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            var deviceInfo = await SmartCardReaderUtils.GetDefaultSmartCardReaderInfo();

            if (deviceInfo == null)
            {
                LogMessage("NFC card reader mode not supported on this device", NotifyType.ErrorMessage);
                return;
            }

            if (!deviceInfo.IsEnabled)
            {
                var msgbox = new Windows.UI.Popups.MessageDialog("Your NFC proximity setting is turned off, you will be taken to the NFC proximity control panel to turn it on");
                msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
                await msgbox.ShowAsync();

                // This URI will navigate the user to the NFC proximity control panel
                NfcUtils.LaunchNfcProximitySettingsPage();
                return;
            }

            if (m_cardReader == null)
            {
                m_cardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id);
                m_cardReader.CardAdded += cardReader_CardAdded;
                m_cardReader.CardRemoved += cardReader_CardRemoved;
            }
        }
コード例 #22
0
ファイル: MainPage.xaml.cs プロジェクト: Madpixel6/Niewidomy
 private async void AppBarButton_Click_Help(object sender, RoutedEventArgs e)
 {
     var message = new Windows.UI.Popups.MessageDialog("Tutaj będzie opis aplikacji w j.Angielskim", "Help"); // Będzie odwołanie do pliku resource
     await message.ShowAsync();
     message = null;
     //Kliknięcie przycisku help, nawigacja do strony pomocy
 }
        public async void getRemainingUsefullLife()
        {
            try
            {
                List<string> QList = new List<string>();
                List<Double> TList = new List<Double>();


                var q = from allgroupname in ParseObject.GetQuery("RemainingUsefulLife")

                        where allgroupname.Get<string>("EquipmentName") != ""
                        select allgroupname;

                var f = await q.FindAsync();


                foreach (var obj in f)
                {
                    QList.Add(obj.Get<String>("EquipmentName"));
                    TList.Add(obj.Get<Double>("TTL"));

                    EquipmentNamelistView.ItemsSource = QList;
                    TTLlistView.ItemsSource = TList;



                }
            }
            catch (Exception ex)
            {
                Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog(ex.Message);
                md.ShowAsync();
            }

        }
コード例 #24
0
        private async void saveRecordatorio(object sender, RoutedEventArgs e)
        {
            if (validarDatos() == 1) //si los datos son validados
            {
                Factura factura = new Factura();

                factura = getInfoFactura(); //obtengo la infomacion de los controles y retonrno el objeto factura

                factDao.insertFactura(factura); //inserto en la base de datos el nuevo objeto

                var facturas = App.Current.Resources["facturas"] as Facturas; //obtengo la referencia de la coleccion de datos
                facturas.Data.Add(factura);  //actualizo la coleccion con el objeto que fue insertado en la base de datos

                //redirigo a MainPage con bandera 0 para mensaje de insertado con exito
                rootFrame.Navigate(typeof(MainPage), "0");
            }
            if (validarDatos() == 2) //problemas con la fecha 
            {
                var dialog = new Windows.UI.Popups.MessageDialog("No te podemos notificar " + (txtDia.SelectedIndex + 1) + " días antes, el día límite es el " + txtVence.Text, "Algo sucede!");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Entendido") { Id = 1 });
                var result = await dialog.ShowAsync();
            }
            if (validarDatos() == 0)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Falta información para crear el recordatorio", "Falta Información!");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Entendido") { Id = 1 });
                var result = await dialog.ShowAsync();
            }
        }
コード例 #25
0
        public async void NewsFeedPage_Loaded(object sender, RoutedEventArgs e)
        {
            loadingprogress.IsActive = true;
            bool internetworking;
            internetworking = true;
            try
            {
                HttpClient httpclient = new HttpClient();
                //Getting the data from the website
                var rsscontent = await httpclient.GetStringAsync(new Uri("http://gcuf.edu.pk/feed/"));
                //Parsing the content into XML Elements
                XElement xmlitems = XElement.Parse(rsscontent);
                //Getting the items from the content and decending them
                List<XElement> elements = xmlitems.Descendants("item").ToList();
                //Creating the Observable collection of RSS Items
                List<RSSItem> aux = new List<RSSItem>();
                foreach (XElement rssItem in elements)
                {
                    RSSItem rss = new RSSItem();
                    rss.Title1 = rssItem.Element("title").Value;
                    rss.Link1 = rssItem.Element("link").Value;
                    aux.Add(rss);



                }
                loadingprogress.IsActive = false;

                ListBoxRss.DataContext = aux;
            }
            catch(HttpRequestException)
            {
                internetworking = false;
            }
            if(internetworking == false)
            {
                var messageDialoghttp = new Windows.UI.Popups.MessageDialog("Unable to connect to Internet:(");
                messageDialoghttp.Title = "No Internet Connection!";
                try
                {
                    messageDialoghttp.ShowAsync();
                    loadingprogress.IsActive = false;
                    Frame.Navigate(typeof(HubPage));




                }
                catch (UnauthorizedAccessException)
                {

                }

            }
            

            //throw new NotImplementedException();
        }
コード例 #26
0
 private async void ShowError(LightChangeStateError response)
 {
     await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
         async () =>
         {
             var dialog = new Windows.UI.Popups.MessageDialog("Error");
             await dialog.ShowAsync();
         }
     );
 }
コード例 #27
0
        private void btnReadHtml_Click(object sender, RoutedEventArgs e)
        {
            string file = @"Assets\html\no2cloud.com.html";
            var c=System.IO.File.ReadAllText(file);

            Windows.UI.Popups.MessageDialog a = new Windows.UI.Popups.MessageDialog(c);

            a.ShowAsync();

        }
コード例 #28
0
        private void back(object handler, RoutedEventArgs e)
        {
            //rootFrame.Navigate(typeof(BlankPage2));
            String test = ((Button)handler).Name;
            Windows.UI.Popups.MessageDialog m = new Windows.UI.Popups.MessageDialog("Test: " + test);

            m.ShowAsync();
            (Window.Current.Content as Frame).Navigate(typeof(BlankPage1), test);
            //throw new NotImplementedException();
        }
コード例 #29
0
        /// <summary>
        /// Richiamato quando l'applicazione viene avviata normalmente dall'utente. All'avvio dell'applicazione
        /// verranno utilizzati altri punti di ingresso per aprire un file specifico, per visualizzare
        /// risultati di ricerche e così via.
        /// </summary>
        /// <param name="args">Dettagli relativi alla richiesta di avvio e al processo.</param>
        protected async override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;


            // Non ripetere l'inizializzazione dell'applicazione se la finestra già dispone di contenuto,
            // assicurarsi solo che la finestra sia attiva
            if (rootFrame == null)
            {
                // Creare un frame che agisca da contesto di navigazione e passare alla prima pagina
                rootFrame = new Frame();
                WindowsBlogReader.Common.SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                // Add this code after "rootFrame = new Frame();"
                var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
                if (connectionProfile != null)
                {
                    FeedDataSource feedDataSource = (FeedDataSource)App.Current.Resources["feedDataSource"];
                    if (feedDataSource != null)
                    {
                        if (feedDataSource.Feeds.Count == 0)
                        {
                            await feedDataSource.GetFeedsAsync();
                        }
                    }
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("An internet connection is needed to download feeds. Please check your connection and restart the app.");
                    var result = messageDialog.ShowAsync();
                }

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Caricare lo stato dall'applicazione sospesa in precedenza
                    await WindowsBlogReader.Common.SuspensionManager.RestoreAsync();
                }

                // Posizionare il frame nella finestra corrente
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // Quando lo stack di navigazione non viene ripristinato, esegui la navigazione alla prima pagina,
                // configurando la nuova pagina per passare le informazioni richieste come parametro di
                // navigazione
                if (!rootFrame.Navigate(typeof(ItemsPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Assicurarsi che la finestra corrente sia attiva
            Window.Current.Activate();
        }
コード例 #30
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected async override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

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

                var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
                if (connectionProfile != null)
                {
                    FeedDataSource feedDataSource = (FeedDataSource)App.Current.Resources["feedDataSource"];
                    if (feedDataSource != null)
                    {
                        if (feedDataSource.Feeds.Count == 0)
                        {
                            await feedDataSource.GetFeedsAsync();
                            
                        }
                    }
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("An internet connection is needed to download feeds. Please check your connection and restart the app.");
                    var result = messageDialog.ShowAsync();
                }

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                    await APIMASH_Univision_StarterKit.Common.SuspensionManager.RestoreAsync();
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(ItemsPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
コード例 #31
0
        /// <summary>
        /// Initialize Speech Recognizer and compile constraints.
        /// </summary>
        /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
        /// <returns>Awaitable task.</returns>
        private async Task InitializeRecognizer(Language recognizerLanguage)
        {
            if (speechRecognizer != null)
            {
                // cleanup prior to re-initializing this scenario.
                speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
                speechRecognizer.ContinuousRecognitionSession.Completed       -= ContinuousRecognitionSession_Completed;
                speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;

                this.speechRecognizer.Dispose();
                this.speechRecognizer = null;
            }

            try
            {
                this.speechRecognizer = new SpeechRecognizer(recognizerLanguage);

                // Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form
                // of an audio indicator to help the user understand whether they're being heard.
                speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;

                // Build a command-list grammar. Commands should ideally be drawn from a resource file for localization, and
                // be grouped into tags for alternate forms of the same command.
                foreach (var item in VoiceCommands)
                {
                    speechRecognizer.Constraints.Add(
                        new SpeechRecognitionListConstraint(
                            item.Value, item.Key));
                }


                // Update the help text in the UI to show localized examples
                string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'",
                                                     VoiceCommands[TagCommands.Calling][0],
                                                     VoiceCommands[TagCommands.TakePhoto][0],
                                                     VoiceCommands[TagCommands.TurnOnLamp][0]);

                /*
                 * listGrammarHelpText.Text = string.Format("{0}\n{1}",
                 *  speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString,
                 *  uiOptionsText);
                 */
                SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();

                if (result.Status != SpeechRecognitionResultStatus.Success)
                {
                    // Disable the recognition buttons.
                    //btnContinuousRecognize.IsEnabled = false;
                    IsRecognizerEnable = false;
                    // Let the user know that the grammar didn't compile properly.
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = "Unable to compile grammar.";
                }
                else
                {
                    //btnContinuousRecognize.IsEnabled = true;

                    resultTextBlock.Visibility = Visibility.Collapsed;
                    IsRecognizerEnable         = true;

                    // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
                    // some recognized phrases occur, or the garbage rule is hit.
                    speechRecognizer.ContinuousRecognitionSession.Completed       += ContinuousRecognitionSession_Completed;
                    speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
                }
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == HResultRecognizerNotFound)
                {
                    //btnContinuousRecognize.IsEnabled = false;
                    IsRecognizerEnable         = false;
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = "Speech Language pack for selected language not installed.";
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                    await messageDialog.ShowAsync();
                }
            }
        }
コード例 #32
0
 public async void ClickHandler(object sender, RoutedEventArgs e)
 {
     var dlg = new Windows.UI.Popups.MessageDialog(string.Format("CheckBox:{0}, TextBox:{1}", CheckBoxValue, TextBoxValue));
     await dlg.ShowAsync();
 }
コード例 #33
0
ファイル: MainPage.xaml.cs プロジェクト: Ranzu/Voluteers
        private async void MessageBox(string p)
        {
            var msgDlg = new Windows.UI.Popups.MessageDialog(p);

            await msgDlg.ShowAsync();
        }
コード例 #34
0
        protected async override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            Horoscope.Common.SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

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

                /* var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
                 * if (connectionProfile != null)
                 */
                if (IsInternet())
                {
                    FeedDataSource feedDataSource = (FeedDataSource)App.Current.Resources["feedDataSource"];
                    if (feedDataSource != null)
                    {
                        if (feedDataSource.Feeds.Count == 0)
                        {
                            await feedDataSource.GetFeedsAsync();
                        }
                    }
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("An internet connection is needed to download feeds. Please check your connection and restart the app.");
                    var result        = messageDialog.ShowAsync();
                }

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                    await Horoscope.Common.SuspensionManager.RestoreAsync();
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter

                /*   var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
                 * if (connectionProfile != null)
                 */
                if (IsInternet())
                {
                    if (!rootFrame.Navigate(typeof(SplitPage), args.Arguments))
                    {
                        throw new Exception("Failed to create initial page");
                    }
                }
                else if (!rootFrame.Navigate(typeof(BlankPage1), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
コード例 #35
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog("Hello world!");

            messageDialog.ShowAsync();
        }
コード例 #36
0
 async void beginexecblock()
 {
     if ((await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFilesAsync()).Count == 0)
     {
         await ApplicationData.Current.RoamingFolder.CreateFileAsync("testfile.txt");
         ApplicationData.Current.SignalDataChanged();
         Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Roaming file creation success", "Sync status");
         await tdlg.ShowAsync();
     }
     try
     {
         DateTime started = DateTime.Now;
         RenderContext mtext = new RenderContext();
         maincontext = mtext;
         StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
         StorageFile file = await folder.GetFileAsync("DXInteropLib\\VertexShader.cso");
         
         var stream = (await file.OpenAsync(FileAccessMode.Read));
         Windows.Storage.Streams.DataReader mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
         byte[] dgram = new byte[file.Size];
         await mreader.LoadAsync((uint)dgram.Length);
         mreader.ReadBytes(dgram);
         file = await folder.GetFileAsync("DXInteropLib\\PixelShader.cso");
         stream = await file.OpenAsync(FileAccessMode.Read);
         mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
         byte[] mgram = new byte[file.Size];
         await mreader.LoadAsync((uint)file.Size);
         mreader.ReadBytes(mgram);
         try
         {
             defaultshader = mtext.CreateShader(dgram, mgram);
             mtext.InitializeLayout(dgram);
             defaultshader.Apply();
             mtext.OnRenderFrame += onrenderframe;
         }
         catch (Exception er)
         {
             Windows.UI.Popups.MessageDialog mdlg = new Windows.UI.Popups.MessageDialog(er.ToString(),"Fatal error");
             mdlg.ShowAsync().Start();
         }
         IStorageFile[] files = (await folder.GetFilesAsync()).ToArray();
         bool founddata = false;
         foreach (IStorageFile et in files)
         {
             if (et.FileName.Contains("rawimage.dat"))
             {
                 stream = await et.OpenAsync(FileAccessMode.Read);
                 founddata = true;
             }
         }
         int width;
         int height;
         byte[] rawdata;
         if (!founddata)
         {
             file = await folder.GetFileAsync("TestProgram\\test.png");
             stream = await file.OpenAsync(FileAccessMode.Read);
             var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
             var pixeldata = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.IgnoreExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage);
             width = (int)decoder.PixelWidth;
             height = (int)decoder.PixelHeight;
             rawdata = pixeldata.DetachPixelData();
             file = await folder.CreateFileAsync("rawimage.dat");
             stream = (await file.OpenAsync(FileAccessMode.ReadWrite));
             var realstream = stream.GetOutputStreamAt(0);
             DataWriter mwriter = new DataWriter(realstream);
             mwriter.WriteInt32(width);
             mwriter.WriteInt32(height);
             mwriter.WriteBytes(rawdata);
             await mwriter.StoreAsync();
             await realstream.FlushAsync();
             
             
             
         }
         else
         {
             DataReader treader = new DataReader(stream.GetInputStreamAt(0));
             await treader.LoadAsync((uint)stream.Size);
             rawdata = new byte[stream.Size-(sizeof(int)*2)];
             width = treader.ReadInt32();
             height = treader.ReadInt32();
             treader.ReadBytes(rawdata);
         }
         Texture2D mtex = maincontext.createTexture2D(rawdata, width, height);
         List<VertexPositionNormalTexture> triangle = new List<VertexPositionNormalTexture>();
         triangle.Add(new VertexPositionNormalTexture(new Vector3(-.5f,-.5f,0),new Vector3(1,1,1),new Vector2(0,0)));
         triangle.Add(new VertexPositionNormalTexture(new Vector3(0,0.5f,0),new Vector3(1,1,1),new Vector2(1,0)));
         triangle.Add(new VertexPositionNormalTexture(new Vector3(.5f,-0.5f,0),new Vector3(1,1,1),new Vector2(1,1)));
         byte[] gpudata = VertexPositionNormalTexture.Serialize(triangle.ToArray());
         
         VertexBuffer mbuffer = maincontext.createVertexBuffer(gpudata,VertexPositionNormalTexture.Size);
         mbuffer.Apply(VertexPositionNormalTexture.Size);
         vertcount = 3;
         Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Unit tests successfully completed\nShader creation: Success\nTexture load: Success\nVertex buffer creation: Success\nTime:"+(DateTime.Now-started).ToString(), "Results");
         tdlg.ShowAsync().Start();
     }
     catch (Exception er)
     {
         Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog(er.ToString(), "Fatal error");
         tdlg.ShowAsync().Start();
     }
 }
コード例 #37
0
ファイル: DialogService.cs プロジェクト: acb122/App3
 public async void Show(string content)
 {
     var dialog = new Windows.UI.Popups.MessageDialog(content);
     await dialog.ShowAsync();
 }
コード例 #38
0
        /// <summary>
        /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
        /// it back on the screen. Uses developer-provided UI for user feedback.
        /// </summary>
        /// <param name="sender">Button that triggered this event</param>
        /// <param name="e">State information about the routed event</param>
        private async void RecognizeWithoutUIListConstraint_Click(object sender, RoutedEventArgs e)
        {
            heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;

            // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
            btnRecognizeWithUI.IsEnabled    = false;
            btnRecognizeWithoutUI.IsEnabled = false;
            cbLanguageSelection.IsEnabled   = false;
            listenWithoutUIButtonText.Text  = " listening for speech...";

            // Start recognition.
            try
            {
                // Save the recognition operation so we can cancel it (as it does not provide a blocking
                // UI, unlike RecognizeWithAsync()
                recognitionOperation = speechRecognizer.RecognizeAsync();

                SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;

                // If successful, display the recognition result. A cancelled task should do nothing.
                if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
                {
                    string tag = "unknown";
                    if (speechRecognitionResult.Constraint != null)
                    {
                        // Only attempt to retreive the tag if we didn't hit the garbage rule.
                        tag = speechRecognitionResult.Constraint.Tag;
                    }

                    heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text            = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString());
                }
                else
                {
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
                }
            }
            catch (TaskCanceledException exception)
            {
                // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
                // processing speech. Since this happens here when we navigate out of the scenario, don't try to
                // show a message dialog for this exception.
                System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
                System.Diagnostics.Debug.WriteLine(exception.ToString());
            }
            catch (Exception exception)
            {
                // Handle the speech privacy policy error.
                if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
                {
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = "The privacy statement was declined.";
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
                    await messageDialog.ShowAsync();
                }
            }

            // Reset UI state.
            listenWithoutUIButtonText.Text  = " without UI";
            cbLanguageSelection.IsEnabled   = true;
            btnRecognizeWithUI.IsEnabled    = true;
            btnRecognizeWithoutUI.IsEnabled = true;
        }
コード例 #39
0
        // </SnippetSetInitialStrokeAttributes>

        // <SnippetRecognize_Click>
        // Handle button click to initiate recognition.
        private async void Recognize_Click(object sender, RoutedEventArgs e)
        {
            // <SnippetGetStrokes>
            // Get all strokes on the InkCanvas.
            IReadOnlyList <InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();

            // </SnippetGetStrokes>

            // Ensure an ink stroke is present.
            if (currentStrokes.Count > 0)
            {
                // <SnippetInkRecognizerContainer>
                // Create a manager for the InkRecognizer object
                // used in handwriting recognition.
                InkRecognizerContainer inkRecognizerContainer =
                    new InkRecognizerContainer();
                // </SnippetInkRecognizerContainer>

                // inkRecognizerContainer is null if a recognition engine is not available.
                if (!(inkRecognizerContainer == null))
                {
                    // <SnippetRecognizeAsync>
                    // Recognize all ink strokes on the ink canvas.
                    IReadOnlyList <InkRecognitionResult> recognitionResults =
                        await inkRecognizerContainer.RecognizeAsync(
                            inkCanvas.InkPresenter.StrokeContainer,
                            InkRecognitionTarget.All);

                    // </SnippetRecognizeAsync>
                    // Process and display the recognition results.
                    if (recognitionResults.Count > 0)
                    {
                        // <SnippetGetTextCandidates>
                        string str = "Recognition result\n";
                        // Iterate through the recognition results.
                        foreach (var result in recognitionResults)
                        {
                            // Get all recognition candidates from each recognition result.
                            IReadOnlyList <string> candidates = result.GetTextCandidates();
                            str += "Candidates: " + candidates.Count.ToString() + "\n";
                            foreach (string candidate in candidates)
                            {
                                str += candidate + " ";
                            }
                        }
                        // Display the recognition candidates.
                        recognitionResult.Text = str;
                        // Clear the ink canvas once recognition is complete.
                        inkCanvas.InkPresenter.StrokeContainer.Clear();
                        // </SnippetGetTextCandidates>
                    }
                    else
                    {
                        recognitionResult.Text = "No recognition results.";
                    }
                }
                else
                {
                    Windows.UI.Popups.MessageDialog messageDialog = new Windows.UI.Popups.MessageDialog("You must install handwriting recognition engine.");
                    await messageDialog.ShowAsync();
                }
            }
            else
            {
                recognitionResult.Text = "No ink strokes to recognize.";
            }
        }
コード例 #40
0
 public static async void ShowMessageBox(string title, string message)
 {
     var dialog = new Windows.UI.Popups.MessageDialog(message, title);
     await dialog.ShowAsync();
 }
コード例 #41
0
        /// <summary>
        /// Initialize Speech Recognizer and compile constraints.
        /// </summary>
        /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
        /// <returns>Awaitable task.</returns>
        private async Task InitializeRecognizer(Language recognizerLanguage)
        {
            if (speechRecognizer != null)
            {
                // cleanup prior to re-initializing this scenario.
                speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;

                this.speechRecognizer.Dispose();
                this.speechRecognizer = null;
            }
            try
            {
                // Create an instance of SpeechRecognizer.
                speechRecognizer = new SpeechRecognizer(recognizerLanguage);

                // Provide feedback to the user about the state of the recognizer.
                speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;

                // Add a list constraint to the recognizer.
                speechRecognizer.Constraints.Add(
                    new SpeechRecognitionListConstraint(
                        new List <string>()
                {
                    speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString
                }, "Home"));
                speechRecognizer.Constraints.Add(
                    new SpeechRecognitionListConstraint(
                        new List <string>()
                {
                    speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString
                }, "GoToContosoStudio"));
                speechRecognizer.Constraints.Add(
                    new SpeechRecognitionListConstraint(
                        new List <string>()
                {
                    speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString,
                    speechResourceMap.GetValue("ListGrammarOpenMessage", speechContext).ValueAsString
                }, "Message"));
                speechRecognizer.Constraints.Add(
                    new SpeechRecognitionListConstraint(
                        new List <string>()
                {
                    speechResourceMap.GetValue("ListGrammarSendEmail", speechContext).ValueAsString,
                    speechResourceMap.GetValue("ListGrammarCreateEmail", speechContext).ValueAsString
                }, "Email"));
                speechRecognizer.Constraints.Add(
                    new SpeechRecognitionListConstraint(
                        new List <string>()
                {
                    speechResourceMap.GetValue("ListGrammarCallNitaFarley", speechContext).ValueAsString,
                    speechResourceMap.GetValue("ListGrammarCallNita", speechContext).ValueAsString
                }, "CallNita"));
                speechRecognizer.Constraints.Add(
                    new SpeechRecognitionListConstraint(
                        new List <string>()
                {
                    speechResourceMap.GetValue("ListGrammarCallWayneSigmon", speechContext).ValueAsString,
                    speechResourceMap.GetValue("ListGrammarCallWayne", speechContext).ValueAsString
                }, "CallWayne"));

                // RecognizeWithUIAsync allows developers to customize the prompts.
                string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'",
                                                     speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString,
                                                     speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString,
                                                     speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString);
                speechRecognizer.UIOptions.ExampleText = uiOptionsText;
                helpTextBlock.Text = string.Format("{0}\n{1}",
                                                   speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString,
                                                   uiOptionsText);

                // Compile the constraint.
                SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();

                // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
                if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
                {
                    // Disable the recognition buttons.
                    btnRecognizeWithUI.IsEnabled    = false;
                    btnRecognizeWithoutUI.IsEnabled = false;

                    // Let the user know that the grammar didn't compile properly.
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = "Unable to compile grammar.";
                }
                else
                {
                    btnRecognizeWithUI.IsEnabled    = true;
                    btnRecognizeWithoutUI.IsEnabled = true;

                    resultTextBlock.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == HResultRecognizerNotFound)
                {
                    btnRecognizeWithUI.IsEnabled    = false;
                    btnRecognizeWithoutUI.IsEnabled = false;

                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = "Speech Language pack for selected language not installed.";
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                    await messageDialog.ShowAsync();
                }
            }
        }
コード例 #42
0
        /// <summary>
        /// Adds or removes the 'phone' constraint from the recognizer.
        /// </summary>
        /// <param name="sender">The button that generated this event</param>
        /// <param name="e">Unused event details</param>
        public async void PhoneButton_Click(object sender, RoutedEventArgs e)
        {
            // Update UI, disabling buttons so the user can't interrupt.
            updateUI(false);
            string newButtonText = "";

            long start = DateTime.Now.Ticks;

            try
            {
                // Pause the session. This allows you to update the grammars without stopping the
                // session and potentially losing audio and a recognition.
                await speechRecognizer.ContinuousRecognitionSession.PauseAsync();

                // Update the grammar appropriately.
                if (phoneButtonText.Text.Equals("Remove 'phone' grammar"))
                {
                    phoneButtonText.Text = "Updating...";
                    speechRecognizer.Constraints.Remove(phoneConstraint);
                    newButtonText = "Add 'phone' grammar";
                    phoneInfoTextBlock.Visibility = Visibility.Collapsed;
                }
                else
                {
                    phoneButtonText.Text = "Updating...";
                    speechRecognizer.Constraints.Add(phoneConstraint);
                    newButtonText = "Remove 'phone' grammar";
                    phoneInfoTextBlock.Visibility = Visibility.Visible;
                }

                // Recompile with the new constraints and resume the session again.
                SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();

                if (result.Status != SpeechRecognitionResultStatus.Success)
                {
                    // Disable the recognition buttons.
                    updateUI(false);

                    // Let the user know that the grammar didn't compile properly.
                    resultTextBlock.Text = "Unable to compile grammar.";

                    await speechRecognizer.ContinuousRecognitionSession.CancelAsync();

                    return;
                }

                speechRecognizer.ContinuousRecognitionSession.Resume();

                // For diagnostic purposes, display the amount of time it took to update the grammar.
                long elapsed = (DateTime.Now.Ticks - start) / TimeSpan.TicksPerMillisecond;
                msTextBlock.Text = "Grammar update took " + elapsed + " ms";
            }
            catch (Exception ex)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                await messageDialog.ShowAsync();
            }

            // Restore the original UI state.
            updateUI(true);
            phoneButtonText.Text = newButtonText;
        }
コード例 #43
0
 /// <summary>
 /// ShowMessageAsync
 /// </summary>
 /// <param name="message"></param>
 /// <param name="title"></param>
 /// <returns></returns>
 public static async Task ShowMessageAsync(string message, string title = "Information")
 {
     var messageDialog = new Windows.UI.Popups.MessageDialog(message, title);
     await messageDialog.ShowAsync();
 }
コード例 #44
0
 private async Task notifyUser(string str)
 {
     var message = new Windows.UI.Popups.MessageDialog(str);
     await message.ShowAsync();
 }
コード例 #45
0
        public bool SetValues()
        {
            //Errorhandling til klokkeslæt så det altid er rigtig format
            if (DateTime.TryParse(Klokkeslæt, out DateTime aDate) == false)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Fejl. Du har indtastet klokkeslættet forkert");
                dialog.ShowAsync();
                return(false);
            }

            //Errorhandling til Holdbarhed så det altid er rigtig format
            if (DateTime.TryParseExact(Holdbarhedsdato, "dd-MM-yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out DateTime bDate) == false)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Fejl. Du har indtastet Holdbarhedsdato forkert");
                dialog.ShowAsync();
                return(false);
            }

            //Errorhandling til klokkeslæt så det altid er rigtig format

            if (DateTime.TryParseExact(Produktionsdato, "dd-MM-yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out DateTime cDate) == false)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Fejl. Du har indtastet Produktionsdato forkert");
                dialog.ShowAsync();
                return(false);
            }


            //double + int værdier skal parses
            //if (Ludkoncetration != "") NytSkema.Ludkoncentration = double.Parse(Ludkoncetration);
            // else NytSkema.Ludkoncentration = null;
            if (FærdigvareNr != "")
            {
                Registrering.FærdigvareNr = int.Parse(FærdigvareNr);
            }
            else
            {
                Registrering.FærdigvareNr = null;
            }

            if (HætteNr != "")
            {
                Registrering.HætteNr = int.Parse(HætteNr);
            }
            else
            {
                Registrering.HætteNr = null;
            }

            if (EtiketNr != "")
            {
                Registrering.EtiketNr = int.Parse(EtiketNr);
            }
            else
            {
                Registrering.EtiketNr = null;
            }

            //datetime skal også parses men med specifikt format
            Registrering.Klokkeslæt      = DateTime.Parse(Klokkeslæt, new DateTimeFormatInfo());
            Registrering.Holdbarhedsdato = DateTime.ParseExact(Holdbarhedsdato, "dd-MM-yyyy", new CultureInfo("en-US"));
            Registrering.Produktionsdato = DateTime.ParseExact(Produktionsdato, "dd-MM-yyyy", new CultureInfo("en-US"));

            //strings er guds gave til dovenskab
            Registrering.Kommentar = Kommentar;
            Registrering.Fustage   = Fustage;
            Registrering.Signatur  = Signatur;

            //bools skal omdannes til enten "OK" eller "IKKE OK"
            // Registrering.Spritkontrol = ToBool(Spritkontrol);
            Registrering.Spritkontrol = ToBool(Spritkontrol);

            //FK_kolonne skal hentes fra tilsvarende Forside
            Registrering.FK_Kolonne = Info.FK_Kolonne;

            return(true);
        }
コード例 #46
0
ファイル: App.xaml.cs プロジェクト: erviveksoni/Aucovei
 private void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
 {
     Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog(e.Message);
     msg.ShowAsync().GetAwaiter().GetResult(); // this will show error message(if Any)
 }
コード例 #47
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            var client  = new RestSharp.Portable.HttpClient.RestClient("http://localhost:3000/");
            var request = new RestRequest("http://localhost:3000/api/v1/users/sign_up", Method.POST);

            client.IgnoreResponseStatusCode = true;

            request.AddBody(new
            {
                first_name            = textBox.Text,
                last_name             = textBox1.Text,
                profile_name          = textBox2.Text,
                email                 = textBox3.Text,
                password              = passwordBox.Password,
                password_confirmation = passwordBox1.Password
            });
            var response = await client.Execute(request).ConfigureAwait(true);

            HttpStatusCode statusCode        = response.StatusCode;
            int            numericStatusCode = (int)statusCode;

            if (numericStatusCode == 200)
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Zarejestrowano poprawnie, nastąpi przekierowanie do strony głównej");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                {
                    Id = 0
                });
                dialog.CancelCommandIndex = 0;

                var result = await dialog.ShowAsync();

                var btn = sender as Button;
                btn.Content = $"Result: {result.Label} ({result.Id})";

                Frame.Navigate(typeof(MainPage), null);
            }

            /*
             * if (numericStatusCode== <nr response, email already taken >){
             *
             *  var dialog = new Windows.UI.Popups.MessageDialog("email jest zajęty, podaj inny email lub zaloguj się");
             *  dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok") { Id = 0 });
             *  dialog.CancelCommandIndex = 0;
             *
             *  var result = await dialog.ShowAsync();
             *
             *  var btn = sender as Button;
             *  btn.Content = $"Result: {result.Label} ({result.Id})";
             * }
             */

            /*
             * if (numericStatusCode== <nr response, username already taken >){
             *
             *  var dialog = new Windows.UI.Popups.MessageDialog("username jest zajęty, podaj inny username");
             *  dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok") { Id = 0 });
             *  dialog.CancelCommandIndex = 0;
             *
             *  var result = await dialog.ShowAsync();
             *
             *  var btn = sender as Button;
             *  btn.Content = $"Result: {result.Label} ({result.Id})";
             * }
             */
        }
コード例 #48
0
        private async void Button1_Click(object sender, RoutedEventArgs e)
        {
            Random rand = new Random();

            switch (App.page1_steps)
            {
            case 0:
                //MainPage.started = true;
                e_error1 = false;

                try
                {
                    epiStart = Convert.ToInt32(TextBlock1.Text);
                }

                catch (Exception error1)
                {
                    var dialog = new Windows.UI.Popups.MessageDialog("You tried to enter a string in an interger field.");
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                    {
                        Id = 0
                    });

                    var result = await dialog.ShowAsync();

                    e_error1 = true;
                }

                if (!e_error1)
                {
                    Text2.Text                 = epiStart.ToString();
                    TextBlock1.Text            = "";
                    TextBlock1.PlaceholderText = "numOfEpisodes";
                    Text1.Text                 = "Enter number of episodes";
                    App.start = true;
                    App.page1_steps++;
                }

                break;

            case 1:
                e_error2 = false;

                try
                {
                    App.numOfEpisodes = Convert.ToInt32(TextBlock1.Text);
                }

                catch (Exception error2)
                {
                    var dialog = new Windows.UI.Popups.MessageDialog("You tried to enter a string in an interger field.");
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                    {
                        Id = 0
                    });

                    var result = await dialog.ShowAsync();

                    e_error2 = true;
                }

                if (!e_error2)
                {
                    TextBlock1.Text            = "";
                    TextBlock1.PlaceholderText = "sourceCode";
                    Text1.Text      = "Enter Source Code:";
                    App.page1_steps = 13;
                }

                break;

            case 13:
                sourceCode = TextBlock1.Text;
                authCode   = get_string(sourceCode, "\"languageMode\":\"" + App.duborsub.ToLower() + "\"," + "\"authToken\":\"", "\"");

                if (authCode == "" && App.duborsub.ToLower() == "dub")
                {
                    Text1.Text       = "You're getting sub now :(\nEnter Source Code:";
                    App.duborsub_num = 1;
                    App.duborsub     = "Sub";
                    langTitle.Text   = "Sub";
                    langLink         = "JPN";
                    authCode         = get_string(sourceCode, "\"languageMode\":\"" + App.duborsub.ToLower() + "\"," + "\"authToken\":\"", "\"");
                }

                if (authCode == "" && App.duborsub.ToLower() == "sub")
                {
                    Text1.Text       = "You're getting dub now!!! :)\nEnter Source Code:";
                    App.duborsub_num = 1;
                    App.duborsub     = "Dub";
                    langTitle.Text   = "Dub";
                    langLink         = "ENG";
                    authCode         = get_string(sourceCode, "\"languageMode\":\"" + App.duborsub.ToLower() + "\"," + "\"authToken\":\"", "\"");
                }
                replace_variable_al(ref authCode);

                if (get_string(sourceCode, "\"hd1080Url\":\"", "\"") == "" && choice == 3)
                {
                    App.quality = "2500K.mp4";
                }

                if (get_string(sourceCode, "\"hdUrl\":\"", "\"") == "" && choice == 3 || choice == 2 && get_string(sourceCode, "\"hdUrl\":\"", "\"") == "")
                {
                    App.quality = "1500K.mp4";
                }

                animeInit = get_string(sourceCode, "http:\\/\\/wpc.8c48.edgecastcdn.net\\/008C48\\/SV\\/480\\/", "ENG");

                if (get_string(sourceCode, "http:\\/\\/wpc.8c48.edgecastcdn.net\\/008C48\\/SV\\/480\\/", "ENG") == "")
                {
                    animeInit = get_string(sourceCode, "http:\\/\\/wpc.8c48.edgecastcdn.net\\/008C48\\/SV\\/480\\/", "JPN");
                }

                aniLink = get_string(sourceCode, animeInit + langLink, "1500K.mp4");

                page1.link = "http:\\/\\/wpc.8c48.edgecastcdn.net\\/008C48\\/SV\\/480\\/" + animeInit + langLink + aniLink + App.quality;
                replace_variable_al(ref link);

                aniName = get_string(sourceCode, "<title>", " - ");
                replace_variable(ref aniName);
                if (aniName == "-q")
                {
                    break;
                }

                epiName = get_string(sourceCode, " - ", "</title>");
                replace_variable(ref epiName);
                if (epiName == "-q")
                {
                    break;
                }


                if (App.duborsub.ToLower() == "sub")
                {
                    language = "Sub";
                }
                if (App.duborsub.ToLower() == "dub")
                {
                    language = "Dub";
                }

                string episode  = language + "-" + epiStart.ToString() + "-" + aniName + "--" + epiName;
                string episode0 = language + "-" + "0" + epiStart.ToString() + "-" + aniName + "--" + epiName;


                if (epiStart <= 9)
                {
                    App.output.Add(line1 + "\"" + link + authCode + "\"" + " " + line2 + episode0 + line3 + "\r\n");
                }

                else
                {
                    App.output.Add(line1 + "\"" + link + authCode + "\"" + " " + line2 + episode + line3 + "\r\n");
                }

                if (App.firstNum == App.numOfEpisodes)
                {
                    while (true)
                    {
                        FolderPicker folderPick = new FolderPicker();
                        folderPick.CommitButtonText       = "Anime Location";
                        folderPick.SuggestedStartLocation = PickerLocationId.VideosLibrary;
                        folderPick.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                        folderPick.FileTypeFilter.Add("*");
                        StorageFolder folder = await folderPick.PickSingleFolderAsync();

                        if (folder != null)
                        {
                            App.aniDirectory = folder.Path;
                            if (!folder.Path.Contains("C:\\"))
                            {
                                App.aniDirectory = "/d " + folder.Path;
                            }

                            while (true)
                            {
                                Text1.Text = "Save bat file location";
                                FolderPicker fp = new FolderPicker();
                                fp.CommitButtonText       = "File Location";
                                fp.SuggestedStartLocation = PickerLocationId.Desktop;
                                fp.FileTypeFilter.Add("*");

                                var savePicker = new FileSavePicker();

                                savePicker.SuggestedFileName = aniName;
                                savePicker.FileTypeChoices.Add("Batch File (\".bat\")", new List <string>()
                                {
                                    ".bat"
                                });
                                savePicker.DefaultFileExtension = ".bat";
                                App.batFile = await savePicker.PickSaveFileAsync();

                                if (App.batFile != null)
                                {
                                    break;
                                }
                            }
                            var stream = await App.batFile.OpenAsync(FileAccessMode.ReadWrite);

                            using (var outputStream = stream.GetOutputStreamAt(0))
                            {
                                using (var dataWriter = new DataWriter(outputStream))
                                {
                                    dataWriter.WriteString("cd " + App.aniDirectory + "\r\n");

                                    if (App.numOfEpisodes == App.firstNum)
                                    {
                                        foreach (string element in App.output)
                                        {
                                            dataWriter.WriteString(element);
                                        }
                                    }

                                    await dataWriter.StoreAsync();

                                    await outputStream.FlushAsync();
                                }
                            }
                            stream.Dispose();
                        }
                        if (folder != null)
                        {
                            break;
                        }
                    }

                    if (App.firstNum == App.numOfEpisodes)
                    {
                        TextBlock1.Visibility = Visibility.Collapsed;
                        Button1.Visibility    = Visibility.Collapsed;
                        Text1.Text            = "You're done! Reset or Close Application";
                        newText.FontSize      = 25;
                        newText.Text          = "Anime located at:\n" + App.aniDirectory + "\n\nBat file located at:\n" + App.batFile.Path;
                        App.finished          = true;

                        if (App.finished)
                        {
                            newText.Visibility = Visibility.Visible;
                        }

                        App.page1_steps = 14;
                    }

                    if (App.numOfEpisodes != App.firstNum)
                    {
                        App.firstNum++;
                        epiStart++;
                        listNums++;
                        Text2.Text      = epiStart.ToString();
                        TextBlock1.Text = "";
                        App.page1_steps = 13;
                    }
                }
                else
                {
                    incr++;
                    App.firstNum++;
                    epiStart++;
                    listNums++;
                    Text2.Text      = epiStart.ToString();
                    TextBlock1.Text = "";
                    App.page1_steps = 13;
                }
                break;
            }
        }
コード例 #49
0
 public async void ShowMessage(string msg)
 {
     var dialog = new Windows.UI.Popups.MessageDialog(msg);
     await dialog.ShowAsync();
 }
コード例 #50
0
 private async void messageBox(string msg)
 {
     var msgDisplay = new Windows.UI.Popups.MessageDialog(msg);
     await msgDisplay.ShowAsync();
 }
コード例 #51
0
 private async void ButtonSettings_Click(object sender, RoutedEventArgs e)
 {
     var dlg = new Windows.UI.Popups.MessageDialog("This feature is not implemented yet.", "Settings");
     await dlg.ShowAsync();
 }
コード例 #52
0
 private async void Button_Click_1(object sender, RoutedEventArgs e)
 {
     Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog("Click the zombies as many times as possible for high score!!", "");
     await msg.ShowAsync();
 }
コード例 #53
0
        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog("This is a very important message.", "Notice");

            messageDialog.ShowAsync();
        }
コード例 #54
0
        /// <summary>
        /// Button Click method that is executed when the Request Button is clicked on the main UI
        /// </summary>
        /// <param name="context">There is none for this button</param>
        private async void ButtonClicked(object context)
        {
            //Return Show Details
            var    escapedShowName  = Uri.EscapeUriString("Coding 101");
            string jsonShowResponse = null;

            try {
                jsonShowResponse = await StudioMetadata.Coding101.TWiT.TV.TWiTApiProxy.TWiTRestRequest("shows", string.Format(CultureInfo.InvariantCulture, "?filter[label]={0}", escapedShowName));

                var twitShows = Newtonsoft.Json.JsonConvert.DeserializeObject <StudioMetadata.Coding101.TWiT.TV.TWiTShows>(jsonShowResponse);
                jsonShowResponse = null;                 //Large (could be over 85K), null it out for the current stack.

                //Return All Episodes
                int numberOfEpisodes      = 0;
                int returnedEpisodes      = 0;
                Uri nextPageOfEpisodesUri = null;

                if (twitShows.Count > 0)
                {
                    int showId = twitShows.Shows[0].Id;
                    ShowTitle = twitShows.Shows[0].Title;
                    while (returnedEpisodes == 0 || returnedEpisodes < numberOfEpisodes)
                    {
                        string jsonEpisodesResponse =
                            await StudioMetadata.Coding101.TWiT.TV.TWiTApiProxy.TWiTRestRequest("episodes",
                                                                                                null == nextPageOfEpisodesUri?
                                                                                                string.Format(CultureInfo.InvariantCulture, "?filter[shows]={0}", showId)
                                                                                                :
                                                                                                nextPageOfEpisodesUri.Query
                                                                                                );

                        var twitEpisodes = Newtonsoft.Json.JsonConvert.DeserializeObject <StudioMetadata.Coding101.TWiT.TV.TWiTShowEpisodes>(jsonEpisodesResponse);
                        if (numberOfEpisodes == 0)
                        {
                            numberOfEpisodes = twitEpisodes.count;
                        }

                        if (numberOfEpisodes == 0)
                        {
                            break;
                        }

                        returnedEpisodes += twitEpisodes.episodes.Count;
                        foreach (var episode in twitEpisodes.episodes)
                        {
                            Episodes.Add(episode);
                        }
                        if (returnedEpisodes < numberOfEpisodes)
                        {
                            if (twitEpisodes.Links.next.Url == null)
                            {
                                break;
                            }

                            nextPageOfEpisodesUri = twitEpisodes.Links.next.Url;
                        }
                    }
                }
            }
            catch (StudioMetadata.Coding101.TWiT.TV.TWiTApiException ex)
            {
                var dialog = new Windows.UI.Popups.MessageDialog(ex.Message);
                await dialog.ShowAsync();
            }
        }
コード例 #55
0
        private async void ElementClick(MapControl sender, MapElementClickEventArgs args)
        {
            string dir     = null;
            double ArgsLat = 0;
            double ArgsLon = 0;

            foreach (var e in args.MapElements)
            {
                var icon = e as MapIcon;
                dir     = icon.Title;
                ArgsLat = icon.Location.Position.Latitude;
                ArgsLon = icon.Location.Position.Longitude;
            }
            if (!dir.Equals("MiPosicion"))
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Elegir Lugar");

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

                var result = await dialog.ShowAsync();

                if (result.Id.Equals(1))
                {
                    progressRing.IsActive = true;

                    StorageFile file  = plan.ImagenPlan;
                    var         bytes = await GetBtyeFromFile(file);

                    ParseFile parseFile = new ParseFile("defaultimg.jpg", bytes, "image/jpeg");

                    ParseObject parseObject = new ParseObject("Plan");


                    parseObject.Add("nombre", plan.NombrePlan);
                    parseObject.Add("descripcion", plan.DescripcionPlan);
                    parseObject.Add("fecha", plan.FechaPlan + " " + plan.HoraPlan);
                    parseObject.Add("id_user", ParseUser.CurrentUser);
                    parseObject.Add("imagen", parseFile);

                    ParseGeoPoint geoLugar = new ParseGeoPoint(ArgsLat, ArgsLon);
                    parseObject.Add("lugar", geoLugar);

                    parseObject.Add("direccion", dir);

                    if (crearLugar == 1)
                    {
                        ParseObject objectLugar = new ParseObject("Lugares");
                        objectLugar.Add("nombre", titulo_lugar);
                        objectLugar.Add("direccion", dir);
                        objectLugar.Add("ubicacion", geoLugar);
                        await objectLugar.SaveAsync();

                        crearLugar = -1;
                    }

                    try
                    {
                        await parseObject.SaveAsync();

                        progressRing.IsActive = false;
                        rootFrame             = Window.Current.Content as Frame;
                        rootFrame.Navigate(typeof(MainPage));
                    }
                    catch
                    {
                        var dialog2 = new Windows.UI.Popups.MessageDialog("Error al crear el plan, intentalo de nuevo");
                        dialog2.Commands.Add(new Windows.UI.Popups.UICommand("Aceptar")
                        {
                            Id = 1
                        });
                        var result2 = await dialog2.ShowAsync();

                        progressRing.IsActive = false;
                    }
                }
            }
        }
コード例 #56
0
        private async Task InitializeRecognizer(Language recognize)
        {
            if (speechRecognizer != null)
            {
                speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
                speechRecognizer.ContinuousRecognitionSession.Completed       -= ContinuousRecognitionSession_Completed;
                speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;
                this.speechRecognizer.Dispose();
                this.speechRecognizer = null;
            }
            try
            {
                this.speechRecognizer = new SpeechRecognizer(recognize);

                if (textBox.IsEnabled == true)
                {
                    var grammar        = new[] { "Brown Wallet", "Elephant Puzzle" };
                    var playConstraint = new SpeechRecognitionListConstraint(grammar);
                    speechRecognizer.Constraints.Add(playConstraint);
                    speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
                    SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();

                    if (result.Status != SpeechRecognitionResultStatus.Success)
                    {
                        btnContinuousRecognize.IsEnabled = false;


                        resultTextBlock.Visibility = Visibility.Visible;
                        resultTextBlock.Text       = "Unable to compile grammar.";
                    }
                    else
                    {
                        btnContinuousRecognize.IsEnabled = true;
                        resultTextBlock.Visibility       = Visibility.Collapsed;
                        speechRecognizer.ContinuousRecognitionSession.Completed       += ContinuousRecognitionSession_Completed;
                        speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
                    }
                }
                else if (textBox.IsEnabled == false)
                {
                    var grammar        = new[] { "next", "undo", "home", "help" };
                    var playConstraint = new SpeechRecognitionListConstraint(grammar);
                    speechRecognizer.Constraints.Add(playConstraint);
                    speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
                    SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();

                    if (result.Status != SpeechRecognitionResultStatus.Success)
                    {
                        btnContinuousRecognize.IsEnabled = false;


                        resultTextBlock.Visibility = Visibility.Visible;
                        resultTextBlock.Text       = "Unable to compile grammar.";
                    }
                    else
                    {
                        btnContinuousRecognize.IsEnabled = true;
                        resultTextBlock.Visibility       = Visibility.Collapsed;
                        speechRecognizer.ContinuousRecognitionSession.Completed       += ContinuousRecognitionSession_Completed;
                        speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
                    }
                }
            }

            catch (Exception ex)
            {
                if ((uint)ex.HResult == HResultRecognizerNotFound)
                {
                    btnContinuousRecognize.IsEnabled = false;
                    resultTextBlock.Visibility       = Visibility.Visible;
                    resultTextBlock.Text             = "Speech Language pack for selected language not installed.";
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                    await messageDialog.ShowAsync();
                }
            }
        }
コード例 #57
0
        private async void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(titleBox.Text) && !string.IsNullOrWhiteSpace(descBox.Text) && listaSkladnikow.SelectedItems.Count != 0)
            {
                Przepis przepis = new Przepis
                {
                    Tytul = titleBox.Text,
                    Opis  = descBox.Text
                };

                await App.MobileService.GetTable <Przepis>().InsertAsync(przepis);


                foreach (Skladnik s in listaSkladnikow.SelectedItems)
                {
                    SkladnikiPrzepisu sk = new SkladnikiPrzepisu {
                        Skladnik = s.Nazwa,
                        Przepis  = przepis.Id
                    };

                    await App.MobileService.GetTable <SkladnikiPrzepisu>().InsertAsync(sk);
                }

                var tileXml =
                    TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text02);

                var tileAttributes = tileXml.GetElementsByTagName("text");
                tileAttributes[0].AppendChild(tileXml.CreateTextNode(titleBox.Text));

                var tileNotification = new TileNotification(tileXml);
                TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

                var type = BadgeTemplateType.BadgeNumber;
                var xml  = BadgeUpdateManager.GetTemplateContent(type);

                var elements = xml.GetElementsByTagName("badge");
                var element  = elements[0] as Windows.Data.Xml.Dom.XmlElement;
                element.SetAttribute("value", "1");

                var updator      = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
                var notification = new BadgeNotification(xml);
                updator.Update(notification);

                var xmlToastTemplate = "<toast launch=\"app-defined-string\">" +
                                       "<visual>" +
                                       "<binding template =\"ToastGeneric\">" +
                                       "<text>CoDobrego</text>" +
                                       "<text>" +
                                       "Dodano nowy przepis!" +
                                       "</text>" +
                                       "</binding>" +
                                       "</visual>" +
                                       "</toast>";

                // load the template as XML document
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xmlToastTemplate);

                // create the toast notification and show to user
                var toastNotification = new ToastNotification(xmlDocument);
                var notif             = ToastNotificationManager.CreateToastNotifier();
                notif.Show(toastNotification);

                Frame.Navigate(typeof(Home));
            }
            else
            {
                var dialog = new Windows.UI.Popups.MessageDialog("Proszę uzupełnić dane. ", "Nie powiodło się!");
                dialog.Commands.Add(new Windows.UI.Popups.UICommand("Ok")
                {
                    Id = 0
                });
                dialog.DefaultCommandIndex = 0;
                var result = await dialog.ShowAsync();
            }
        }
コード例 #58
0
 public async void Show(string message)
 {
     var Dialog = new Windows.UI.Popups.MessageDialog(message);
     await Dialog.ShowAsync();
 }
コード例 #59
0
 private async void Show()
 {
     var helper = new SharedProject.MySharedCode();
     var dialog = new Windows.UI.Popups.MessageDialog(helper.GetFilePath("demo.dat"));
     await dialog.ShowAsync();
 }
コード例 #60
0
        private async void LoadPdfFileAsync(StorageFile bookUrl)
        {
            try
            {
                ObservableCollection <BookPdf> bookPages = new ObservableCollection <BookPdf>();
                PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(bookUrl);

                int count = 0;
                popUp.IsOpen           = true;
                progressLoader.Maximum = (int)pdfDocument.PageCount;
                pageCount.Text         = pdfDocument.PageCount.ToString() + " Pages";
                progressStatus.Text    = "Loading Pages...";
                for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
                {
                    var pdfPage = pdfDocument.GetPage((uint)pageIndex);
                    if (pdfPage != null)
                    {
                        StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
                        StorageFile   pngFile    = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                        if (pngFile != null && pdfPage != null)
                        {
                            IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite);

                            await pdfPage.RenderToStreamAsync(randomStream);

                            await randomStream.FlushAsync();

                            randomStream.Dispose();
                            pdfPage.Dispose();

                            count++;
                            progressLoader.Value = pageIndex;
                            int progress = (100 * pageIndex) / (int)pdfDocument.PageCount;

                            downloadSize.Text = String.Format("{0} of {1} pages loaded - {2} % complete.", pageIndex, pdfDocument.PageCount, progress);
                            bookPages.Add(new BookPdf {
                                Id = pageIndex.ToString(), PageNumber = pageIndex.ToString(), ImagePath = pngFile.Path
                            });
                        }
                    }
                }
                if (progressLoader.Value >= 99 || count >= (int)pdfDocument.PageCount - 1)
                {
                    progressStatus.Text = "Pages Loaded";
                    popUp.IsOpen        = false;
                }
                bookPagesView.ItemsSource = bookPages;
            }
            catch (Exception ex)
            {
                var popup = new Windows.UI.Popups.MessageDialog("The Program doesn't support this type of file. It only opens PDF files");
                popup.Commands.Add(new Windows.UI.Popups.UICommand("Ok"));
                popup.DefaultCommandIndex = 0;
                popup.CancelCommandIndex  = 1;
                var results = await popup.ShowAsync();

                if (results.Label == "OK")
                {
                    this.Frame.GoBack();
                }
            }
        }