public static void ShowWarningMessage(Window window, string message)
 {
     Dialog dialog = new MessageDialog(window, DialogFlags.DestroyWithParent | DialogFlags.Modal,
             MessageType.Warning, ButtonsType.Ok, message);
         dialog.Run();
         dialog.Hide();
 }
 public void TestInitialize()
 {
     var fixture = new Fixture();
     factories = Substitute.For<Factories>();
     navigator = Substitute.For<Navigator>();
     stateProvider = Substitute.For<StateProvider>();
     facade = Substitute.For<ReplacementBuilderAndSugarEstimatorFacade>();
     clipboard = Substitute.For<Clipboard>();
     messageDialog = Substitute.For<MessageDialog>();
     navigation = new InsulinEditingViewModel.Navigation();
     CreateSut();
     insulin = fixture.Create<Insulin>();
     insulin.InitializeCircumstances(new List<Guid>());
     insulin.SetOwner(factories);
     sugar = new Sugar();
     sugar.SetOwner(factories);
     factories.InsulinCircumstances.Returns(fixture.CreateMany<InsulinCircumstance>().ToList());
     factories.CreateSugar().Returns(sugar);
     settings = new Settings { MaxBolus = 5 };
     factories.Settings.Returns(settings);
     meal = fixture.Create<Meal>();
     factories.Finder.FindMealByInsulin(insulin).Returns(meal);
     factories.Finder.FindInsulinById(insulin.Id).Returns(insulin);
     var replacementAndEstimatedSugars = new ReplacementAndEstimatedSugars();
     replacementAndEstimatedSugars.EstimatedSugars = new List<Sugar>();
     replacementAndEstimatedSugars.Replacement
         = new Replacement { InsulinTotal = new Insulin(), Items = new List<ReplacementItem>() };
     facade.GetReplacementAndEstimatedSugars(Arg.Any<Meal>(), Arg.Any<Insulin>(), Arg.Any<Sugar>())
             .Returns(replacementAndEstimatedSugars);
     factories.MealNames.Returns(new List<MealName>());
     stateProvider.State.Returns(new Dictionary<string, object>());
 }
Esempio n. 3
0
    protected void OnDeleteActionActivated(object sender, EventArgs e)
    {
        MessageDialog messageDialog = new MessageDialog (
            this,
            DialogFlags.Modal,
            MessageType.Question,
            ButtonsType.YesNo,
            "¿Quieres eliminar el registro?"
        );
        messageDialog.Title = Title;
        ResponseType response = (ResponseType) messageDialog.Run ();
        messageDialog.Destroy ();

        if (response != ResponseType.Yes)
            return;

        TreeIter treeIter;
        treeView.Selection.GetSelected (out treeIter);
        object id = listStore.GetValue (treeIter, 0);
        string deleteSql = string.Format ("delete from categoria where id={0}", id);
        IDbCommand dbCommand = dbConnection.CreateCommand ();
        dbCommand.CommandText = deleteSql;

        dbCommand.ExecuteNonQuery ();
    }
Esempio n. 4
0
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        try
        {
        CheckForUpdatesProgress cfup = new CheckForUpdatesProgress(Assembly.GetExecutingAssembly().GetName().Version);
        cfup.Show();
        if (cfup.CheckForUpdates() == false)
            cfup.Destroy();
        }
        catch
        {
            MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok,
                "Communication could not be established to our servers: you must be online to use the LunaLua Module Manager.\n\nPress ok so we can self destruct.");
            md.Icon = Image.LoadFromResource("Gtktester.Icons.PNG.256.png").Pixbuf;
            md.WindowPosition = WindowPosition.Center;
            md.Run();
            md.Destroy();
            this.Destroy();
            Environment.Exit(-5);
        }

        Build ();

        if (Program.ProgramSettings.StartMaximized)
            this.Maximize();

        this.hpaned2.Position = 170;
        this.hpaned1.Position = 170;

        OnWindowLoad();

        this.notebook1.CurrentPage = 0;
    }
Esempio n. 5
0
    protected void OnButtonLoginClicked(object sender, EventArgs e)
    {
        try{
            string connectionString = "Server=localhost;" + "Database=dbprueba;" +
                "User ID=" + entryUser.Text.ToString () + ";" + "Password="******"\t\tConnection Error\t\t\nCannot connect to database");
            messageDialog.Title = "SQL DataBase Error";
            messageDialog.Run ();
            messageDialog.Destroy ();

            entryUser.Text = "";
            entryPwd.Text = "";

        }
        catch{
            Console.WriteLine ("\nError 404 Not Found");
            Application.Quit ();
        }
    }
Esempio n. 6
0
    //LOGIN
    protected void OnLoginButtonClicked(object sender, EventArgs e)
    {
        try{
            string connectionString = "Server=localhost;" + "Database=dbprueba;" +
                "User ID=" + userEntry.Text.ToString () + ";" + "Password="******"\t\tConnection Error\t\t\nCannot connect to database");
            msgDialog.Title = "SQL DataBase Error";
            msgDialog.Run ();
            msgDialog.Destroy ();

            pwdEntry.Text = "";

        }
        catch{
            Console.WriteLine ("\nError 404 Not Found");
            Application.Quit ();

        }
    }
Esempio n. 7
0
    protected void clicked(object sender, EventArgs e)
    {
        double pes;
        double cam;
        double res;

        if (double.TryParse (pesos.Text, out pes) && double.TryParse (camb.Text, out cam)) {
            if(pes == 0 || cam == 0){
                MessageDialog cero;
                cero = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Conversion invalida entre cero");
                cero.Run();
                cero.Destroy();
        }
            else{
                res = pes / cam;
                dol.Text = Convert.ToString (res);
            }
        }
        else if(pesos.Text == "" || camb.Text == ""){
            MessageDialog d;
            d = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Campos vacios, ingrese numeros");
            d.Run();
            d.Destroy();
        }else {
            MessageDialog dia;
            dia = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Ingrese solo numeros");
            dia.Run();
            dia.Destroy();
        }
    }
Esempio n. 8
0
    protected void btnEnter_Click(object sender, EventArgs e)
    {
        TeenvioAPI api = new TeenvioAPI (txtUser.Text, txtPlan.Text, txtPassword.Text);

        try{
            api.getServerVersion ();
            MainWindow win = new MainWindow();
            win.Show();
            win.setAPI(api);
            this.Destroy();

        }catch(TeenvioException ex){
            MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, ex.Message);
            msg.Title = "Error";

            ResponseType response = (ResponseType) msg.Run();
            if (response == ResponseType.Close || response == ResponseType.DeleteEvent) {
                msg.Destroy();
            }
        }catch(Exception ex){
            MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, ex.Message);
            msg.Title = "Error";

            ResponseType response = (ResponseType) msg.Run();
            if (response == ResponseType.Close || response == ResponseType.DeleteEvent) {
                msg.Destroy();
            }
        }
    }
Esempio n. 9
0
    protected virtual void OnBtnAnularClicked(object sender, System.EventArgs e)
    {
        MessageDialog Mensaje = null;
        string Tiquete = "", REF = "", c = "";

        REF = txtEfectivo.Text;

        c = "UPDATE `cafeteria_transacciones` SET `precio_grabado`= 0.00, `cancelado` = 1 WHERE ID_ticket = '"+REF+"'";
        if (MySQL.consultar(c))
        {
            if( MySQL.Reader.RecordsAffected > 0 )
            {
                Console.WriteLine("RA:" + MySQL.Reader.RecordsAffected);
                Tiquete += Imprimidor.Imprimir("CANCELACION CAFETERIA",1);
                Tiquete += Imprimidor.Imprimir("REF: "+REF,1);
                Imprimidor.Tiquete(Tiquete, "666");

                Mensaje = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Tiquete anulado");
                Mensaje.Title="Éxito";
                Mensaje.Run();
                Mensaje.Destroy();
                txtEfectivo.Text = "";
                return;
            }
        }

        Mensaje = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Tiquete no pudo ser anulado.");
        Mensaje.Title="Error";
        Mensaje.Run();
        Mensaje.Destroy();
        txtEfectivo.GrabFocus();
        return;
    }
Esempio n. 10
0
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        this.Resize (600, 100);
        this.Title = "metafang";
        _main = new VBox ();

        HBox title = new HBox ();
        title.PackStart (new Label ("Login to your Metasploit RPC instance to begin"), true, true, 0);

        _main.PackStart (title, true, true, 0);

        HBox loginInfo = new HBox ();

        loginInfo.PackStart (new Label ("Host:"), false, false, 20);

        Entry hostEntry = new Entry ();
        loginInfo.PackStart (hostEntry, false, false, 0);

        loginInfo.PackStart (new Label ("User:"******"Pass:"******"Login");

        login.Clicked += (object sender, EventArgs e) => {
            try {
                //Console.WriteLine ("Creating session");
                _session = new MetasploitSession (userEntry.Text, passEntry.Text, hostEntry.Text);
                //Console.WriteLine ("Creating manager and getting current list of payloads");
                _manager = new MetasploitManager (_session);
                _payloads = _manager.GetPayloads ();
                BuildWorkspace ();
            } catch {
                MessageDialog md = new MessageDialog (this,
                                       DialogFlags.DestroyWithParent,
                                       MessageType.Error,
                    ButtonsType.Close, "Authentication failed. Please ensure your credentials and API URL are correct.");

                md.Run ();
                md.Destroy ();
            }
        };

        HBox loginBox = new HBox ();
        loginBox.PackStart (login, false, false, 300);

        _main.PackStart (loginBox, true, true, 0);

        _main.ShowAll ();
        this.Add (_main);
    }
Esempio n. 11
0
    protected void OnBtnTerminarClicked(object sender, EventArgs e)
    {
        int puntos = 0;
            if (this.radiobtnC.Active)
                puntos++;

        if(this.spinbtn1.Text=="6")
                puntos++;

        if (this.checkbtnA.Active)
                puntos++;

        if (this.checkbtnC.Active)
                puntos++;

        DateTime fecha = this.calIndependencia.GetDate();
        string fechaSeleccionada = fecha.ToShortDateString();
        if (fechaSeleccionada == "16/09/1810"){
                puntos++;
        }

        MessageDialog md = new MessageDialog (null,
               DialogFlags.Modal,
               MessageType.Info,
               ButtonsType.None, "Estos son los puntos obtenidos: \n" +
                                              "Puntos: " + puntos + "\n");
        md.Show();
    }
Esempio n. 12
0
    protected void OnAceptaClicked(object sender, System.EventArgs e)
    {
        if (password.Text=="123456"&& usuario.Text=="ricardo")
        {
            MessageDialog hola = new MessageDialog(
                null,
                DialogFlags.Modal,
                MessageType.Info,
                ButtonsType.None,
                "Hola Bienvenido"
            );
            hola.Show();
        }

        else
        {
            MessageDialog error = new MessageDialog(

                null,
                DialogFlags.Modal,
                MessageType.Info,
                ButtonsType.None,
                "Error verifique password y/o Usuario"
            );
            error.Show();
        }
    }
Esempio n. 13
0
        /// <summary>
        ///     Registers the assembly into the Global Assembly Cache
        /// </summary>
        /// <param name="m_fileName">The File name</param>
        public static void RegisterAssembly(string m_fileName)
        {
            string result = string.Empty;
            try
            {   // register the assembly
                result = RegisterAssemblyCode(m_fileName);
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }

            MessageDialog msgDialog = new MessageDialog();

            if (result.ToLower().Contains("success"))
            {   // if the success contains into the message then its okay
                msgDialog.MessageText = "Successfully added to the Global Assembly Cache.";
            }
            else
            {   // failureMessageDetails
                msgDialog.MessageText = "Failed to register the assembly.";
            }

            msgDialog. = result;
            msgDialog.ShowDialog();
        }
Esempio n. 14
0
    protected virtual void OnBtnokClicked(object sender, System.EventArgs e)
    {
        if(txturl.Text==String.Empty||txtname.Text==String.Empty)
        {
            MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent,MessageType.Error, ButtonsType.Close, "Fields must not be empty");
        int result = md.Run ();
        md.Destroy();
        }
        else
        {
            if(!txturl.Text.Contains("http://"))
            {
                MessageDialog md = new MessageDialog(this,DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "Please Introduce a valid URL");
                int result=md.Run();
                md.Destroy();
            }
            else
            {
                url=txturl.Text;
                path=txtpath.CurrentFolder+"/"+txtname.Text;
                Thread down = new Thread(downloadStart);
                down.Start();

            }

        }
    }
Esempio n. 15
0
    protected void OnButton1Clicked(object sender, EventArgs e)
    {
        int puntos=0;
        if(this.radiobutton3.Active)
            puntos++;

        if(this.spinbutton1.Text=="4")
            puntos++;

        if(this.checkbutton1.Active)
            puntos++;

        if(this.checkbutton2.Active)
            puntos++;

        DateTime fecha=this.calendar1.GetDate();
        string fechaseleccionada=fecha.ToShortDateString();
        if(fechaseleccionada=="16/09/1810"){
            puntos++;

            MessageDialog md = new MessageDialog (null,DialogFlags.Modal,MessageType.Info,
            ButtonsType.None, "puntos" +
             puntos);
            md.Show();

        }
    }
Esempio n. 16
0
    protected void OnButton1Clicked(object sender, EventArgs e)
    {
        int aciertos = 0;

        if (this.radb1.Active) {
            aciertos += 1;
        }

        if (this.chPortu.Active) {
            aciertos += 1;
        }

        if (this.chReino.Active) {
            aciertos += 1;
        }

        if (this.chMace.Active) {
            aciertos += 1;
        }

        if (this.spinb1.Text == "31") {
            aciertos += 1;
        }

        if (this.calendar1.GetDate ().ToShortDateString () == "07/05/1945") {
            aciertos +=1;
        }

        MessageDialog ve=new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Código: " + this.entry1.Text
                                           + "\nNombre: " + this.entry2.Text + "\n" + Convert.ToString(aciertos) + " aciertos.");
        ve.Run();
        ve.Destroy();
        aciertos=0;
    }
Esempio n. 17
0
    protected void OnButton1Clicked(object sender, EventArgs e)
    {
        int puntos =0;

        if(this.opca.Active)
            puntos++;

        if(this.spm.Text == "4")

        if(this.opa.Active)
            puntos++;
        if(this.opd.Active)
            puntos++;

        DateTime fecha = this.calendario.GetDate();
        string fechaseleccionada = fecha.ToShortDateString();
        if(fechaseleccionada == "16/09/1810"){
            puntos++;
        }
        string a,b;

        a= nombre.Text;
        b= codigo.Text;

        MessageDialog md = new MessageDialog (null,
                                              DialogFlags.Modal,
                                              MessageType.Info,
                                              ButtonsType.None,"Nombre : "+ a +"\n"+ "Codigo: "+b + "\n" +
                                              "Grupo: " +
                                              "Ha obtenido: " + puntos + " aciertos");
        md.Show();
    }
    protected void OnBtnGenerateClicked(object sender, EventArgs e)
    {
        try {
            BarcodeLib.Barcode codeBar = new BarcodeLib.Barcode ();
            codeBar.Alignment = BarcodeLib.AlignmentPositions.CENTER;
            codeBar.IncludeLabel = true;
            codeBar.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;

            BarcodeLib.TYPE bCodeType = (BarcodeLib.TYPE)Enum.Parse (typeof(BarcodeLib.TYPE), cmbBarCodeType.ActiveText.ToString ());
            System.Drawing.Image imgTmpCodeBar = codeBar.Encode (bCodeType, txtData.Text.Trim (), System.Drawing.Color.Black, System.Drawing.Color.White, 300, 300);

            MemoryStream memoryStream = new MemoryStream();
            imgTmpCodeBar.Save(memoryStream, ImageFormat.Png);
            Gdk.Pixbuf pb = new Gdk.Pixbuf (memoryStream.ToArray());

            imgCodeBar.Pixbuf = pb;

        } catch (Exception err) {
            MessageDialog dlg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, string.Format ("Ocurrió un error \n {0}", err.Message));
            dlg.Run ();
            dlg.Destroy ();
            dlg.Dispose ();
            dlg = null;
        }
    }
Esempio n. 19
0
        /// <summary>
        /// Shows the message box.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="caption">The caption.</param>
        /// <param name="button">The button.</param>
        /// <param name="icon">The icon.</param>
        /// <returns>The message result.</returns>
        /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception>
        protected virtual async Task<MessageResult> ShowMessageBox(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None)
        {
            // TODO: Add translations for system

            var result = MessageBoxResult.None;
            var messageBoxButton = TranslateMessageButton(button);
            var messageDialog = new MessageDialog(message, caption);

            if (Enum<MessageButton>.Flags.IsFlagSet(button, MessageButton.OK) || 
                Enum<MessageButton>.Flags.IsFlagSet(button, MessageButton.OKCancel))
            {
                messageDialog.Commands.Add(new UICommand("OK", cmd => result = MessageBoxResult.OK));
            }

            if (Enum<MessageButton>.Flags.IsFlagSet(button, MessageButton.YesNo) ||
                Enum<MessageButton>.Flags.IsFlagSet(button, MessageButton.YesNoCancel))
            {
                messageDialog.Commands.Add(new UICommand("Yes", cmd => result = MessageBoxResult.Yes));
                messageDialog.Commands.Add(new UICommand("No", cmd => result = MessageBoxResult.No));
            }

            if (Enum<MessageButton>.Flags.IsFlagSet(button, MessageButton.OKCancel) ||
                Enum<MessageButton>.Flags.IsFlagSet(button, MessageButton.YesNoCancel))
            {
                messageDialog.Commands.Add(new UICommand("Cancel", cmd => result = MessageBoxResult.Cancel));
                messageDialog.CancelCommandIndex = (uint)messageDialog.Commands.Count - 1;
            }

            await messageDialog.ShowAsync();

            return TranslateMessageBoxResult(result);
        }
Esempio n. 20
0
    protected virtual void OnExecButtonClicked(object sender, System.EventArgs e)
    {
        resultString = new StringBuilder();
        try{
            parser.Execute(); // Parse selected file
        }
        catch(Exception exc){
            string errorText = "Ouch! Something bad happened and an exception" +
                " was thrown. The error message was: " + Environment.NewLine +
                    exc.Message + Environment.NewLine + Environment.NewLine +
                    "Make sure your input file is formatted correctly and try again.";

            MessageDialog md = new MessageDialog(this, DialogFlags.Modal,
                                             MessageType.Info, ButtonsType.Ok,
                                             errorText);
            ResponseType res = (ResponseType)md.Run();
            if(res == ResponseType.Ok){
                md.Destroy();
                Application.Quit();
            }
        }

        // Append each line
        foreach(string str in parser.GetResults()){
            resultString.Append(str + Environment.NewLine);
        }
        resultString.Append(Environment.NewLine);
        // Enable View and Save buttons
        TextView.Buffer.Text = "File parsed. Press View to view results or Save to save results.";
        //TextView.Buffer.Text = "File parsed. Press Save to save the results.";
        ViewButton.Sensitive = true;
        SaveButton.Sensitive = true;
    }
Esempio n. 21
0
 protected void OnButton1Clicked(object sender, EventArgs a)
 {
     using (var dialog = new MessageDialog(
         this, DialogFlags.Modal, MessageType.Info,
         ButtonsType.Ok, "World!")) {
         dialog.Run ();
     }
 }
Esempio n. 22
0
 protected virtual void OnCmbGrupoChanged(object sender, System.EventArgs e)
 {
     MessageDialog md = new MessageDialog (null,
                                           DialogFlags.Modal,
                                           MessageType.Info,
                                           ButtonsType.None, "Grupo: " + this.Grupo.ActiveText );
     md.Show();
 }
Esempio n. 23
0
 protected void click(object sender, System.EventArgs e)
 {
     //throw new System.NotImplementedException ();
     //label1.Text="Hola Mundo";
     MessageDialog dialogo;
     dialogo = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "MENSAJE DE ERROR");
     dialogo.Run();
     dialogo.Destroy();
 }
Esempio n. 24
0
 private void ShowError(string errorMessage)
 {
     MessageDialog errorMsg = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, errorMessage);
     errorMsg.Title = "Error";
     if ((ResponseType) errorMsg.Run() == ResponseType.Close)
     {
         errorMsg.Destroy();
     }
 }
Esempio n. 25
0
 public void StartGame(Config config)
 {
     game = new Game (this.createBoard (config.Width, config.Height));
     game.GameWon += delegate(object sender, EventArgs e) {
         MessageDialog dialog = new MessageDialog (
             this,
          DialogFlags.Modal,
          MessageType.Info,
          ButtonsType.None,
          "Úroveň dokončena! Abyste zvládli víc nepřátel, dostanete další život."
         );
         dialog.AddButton ("Další kolo", ResponseType.Accept);
         dialog.AddButton ("Konec hry", ResponseType.Cancel);
         dialog.Response += delegate(object o, ResponseArgs args) {
             if (args.ResponseId == ResponseType.Accept) {
                 NextLevel (config);
             } else {
                 Application.Quit ();
             }
         };
         dialog.Run ();
         dialog.Destroy ();
     };
     game.GameLost += delegate(object sender, EventArgs e) {
         MessageDialog dialog = new MessageDialog (
             this,
          DialogFlags.Modal,
          MessageType.Info,
          ButtonsType.None,
          "Konec hry"
         );
         dialog.AddButton ("Nová hra", ResponseType.Accept);
         dialog.AddButton ("Konec", ResponseType.Close);
         dialog.Response += delegate(object o, ResponseArgs args) {
             if (args.ResponseId == ResponseType.Accept) {
                 MainClass.ShowLauncher ();
                 this.Destroy ();
             } else {
                 Application.Quit ();
             }
         };
         dialog.Run ();
         dialog.Destroy ();
     };
     game.FilledAreaChanged += delegate(object sender, int value) {
         fillCounter.Text = String.Format ("Zaplněno: {0}%", value);
     };
     game.LivesChanged += delegate(object sender, int value) {
         lifeCounter.Text = String.Format ("Životy: {0}", value);
     };
     game.RemainingTimeChanged += delegate(object sender, int value) {
         remainingTimeCounter.Text = string.Format ("Zbývající čas: {0} sekund", value);
     };
     game.Start (config);
     level = 1;
     updateLevelCounter ();
 }
 public async Task<bool> Confirm(string content, string title, string ok, string cancel)
 {
     bool result = false;
     MessageDialog dialog = new MessageDialog(content, title);
     dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
     dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
     await dialog.ShowAsync();
     return result;
 }
Esempio n. 27
0
 protected void clicou(object sender, EventArgs e)
 {
     //throw new NotImplementedException ();
     String texto = txtInput.Text;
     MessageDialog dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Other, ButtonsType.YesNo, texto);
     ResponseType tp = (Gtk.ResponseType)dialog.Run();
     //dialog.Run ();
     dialog.Destroy();
 }
Esempio n. 28
0
 protected void FinishedAlert()
 {
     var md = new MessageDialog (this,
                                DialogFlags.DestroyWithParent,
                                MessageType.Info,
                                ButtonsType.Ok,
                                "Scraping finished!");
     md.Run ();
     md.Destroy ();
 }
Esempio n. 29
0
    /// <summary>
    /// Raises the login button clicked event.
    /// </summary>
    /// <param name='sender'>
    /// Sender.
    /// </param>
    /// <param name='e'>
    /// E.
    /// </param>
    protected void OnLoginButtonClicked(object sender, EventArgs e)
    {
        MessageDialog md = new MessageDialog (this,
                                              DialogFlags.DestroyWithParent,
                                              MessageType.Info,
                                              ButtonsType.Close, "Visit http://splunk.net");

        md.Run ();
        md.Destroy();
    }
        private void Help_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new MessageDialog(Strings.DialogMessage);

            dialog.ShowAsync();
        }
Esempio n. 31
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
            {
                var statusbar = StatusBar.GetForCurrentView();
                statusbar.BackgroundColor = new Windows.UI.Color()
                {
                    R = 115, G = 143, B = 186
                };
                statusbar.BackgroundOpacity = 1;
                statusbar.ForegroundColor   = Windows.UI.Colors.White;
            }

            int    paramIndex = e.Parameter.ToString().IndexOf("|");
            string strId      = e.Parameter.ToString().Substring(0, paramIndex);
            string type       = e.Parameter.ToString().Substring(paramIndex + 1);

            Cast      = new ObservableCollection <ExtendedVideoCast>();
            IsLoading = true;

            try
            {
                int id = int.Parse(strId);

                VideoCast[] cast;
                if (type.Equals("episode", StringComparison.OrdinalIgnoreCase))
                {
                    var episode = await App.Context.Connection.Kodi.VideoLibrary.GetEpisodeDetailsAsync(id, VideoFieldsEpisode.cast);

                    cast = episode.EpisodeDetails.Cast;
                }
                else if (type.Equals("tvshow", StringComparison.OrdinalIgnoreCase))
                {
                    var tvShow = await App.Context.Connection.Kodi.VideoLibrary.GetTvShowDetailsAsync(id, VideoFieldsTVShow.cast);

                    cast = tvShow.TvShowDetails.Cast;
                }
                else if (type.Equals("movie", StringComparison.OrdinalIgnoreCase))
                {
                    var movie = await App.Context.Connection.Kodi.VideoLibrary.GetMovieDetailsAsync(id, VideoFieldsMovie.cast);

                    cast = movie.Cast;
                }
                else
                {
                    if (Frame.CanGoBack)
                    {
                        Frame.GoBack();
                    }

                    return;
                }

                foreach (var c in cast)
                {
                    Cast.Add(new ExtendedVideoCast(c));
                }
            }
            catch (Exception ex)
            {
                App.TrackException(ex);
                var dialog = new MessageDialog(_resourceLoader.GetString("GlobalErrorMessage"), _resourceLoader.GetString("ApplicationTitle"));
                await dialog.ShowAsync();
            }
            finally
            {
                IsLoading = false;
            }
        }
Esempio n. 32
0
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            _settings.ShowHamburgerButton = true;
            RideHistories histories = null;

            try
            {
                histories = await _api.GetRideHistories();
            }
            catch (NotLoggedInException)
            {
                var dialog = new MessageDialog("You need to login to access this page.");
                await dialog.ShowAsync();

                NavigationService.Navigate(typeof(Views.SettingsPage), 0);
                return;
            }
            catch (Exception e)
            {
                var dialog = new MessageDialog($"Error: {e.Message}");
                await dialog.ShowAsync();

                NavigationService.Navigate(typeof(Views.MapPage));
                return;
            }

            if (histories == null)
            {
                if (_settings.UserToken == null)
                {
                    var dialog = new MessageDialog("An error occured. Are you logged in?");
                    await dialog.ShowAsync();

                    NavigationService.Navigate(typeof(Views.MapPage));
                    return;
                }
                else
                {
                    var dialog = new MessageDialog("An error occured on Lyfts part. Try again later.");
                    await dialog.ShowAsync();

                    NavigationService.Navigate(typeof(Views.MapPage));
                    return;
                }
            }

            if (histories != null && histories.RideHistory.Any())
            {
                foreach (var ride in histories.RideHistory)
                {
                    RideHistories.Add(ride);

                    if (ride.Status == "droppedOff")
                    {
                        var rideTime = ride.Dropoff.Time - ride.Pickup.Time;

                        var elem = new InactiveRide()
                        {
                            DateAndTime     = ride.RequestedAt.ToString("MMM d - h:mm tt"),
                            Price           = $"{ride.Price.Amount / 100:C}",
                            ProfileImageSrc = new Uri(ride.Driver.ImageUrl),
                            Ride            = $"{ride.RideType.ToString()} \u2022 {rideTime.Minutes}m {rideTime.Seconds}s",
                            RideId          = ride.RideId,
                        };
                        Rides.Add(elem);
                    }
                    else if (ride.Status == "canceled")
                    {
                        var elem = new InactiveRide()
                        {
                            DateAndTime     = ride.RequestedAt.ToString("MMM d - h:mm tt"),
                            Price           = $"{ride.Price?.Amount ?? 0:C}",
                            ProfileImageSrc = new Uri(ride.Driver?.ImageUrl ?? "ms-appx://29Quizlet/Assets/avatar.png"),
                            Ride            = $"{ride.RideType.ToString()} \u2022 cancelled",
                            RideId          = ride.RideId,
                        };

                        Rides.Add(elem);
                    }
                    else
                    {
                        string rideType = "ms-appx://29Quizlet/Assets/Lyft.png";

                        switch (ride.RideType)
                        {
                        case Api.Public.models.LyftRideTypeEnum.Unknown:
                            break;

                        case Api.Public.models.LyftRideTypeEnum.Lyft:
                            break;

                        case Api.Public.models.LyftRideTypeEnum.Plus:
                            rideType = "ms-appx://29Quizlet/Assets/LyftPlus.png";
                            break;

                        case Api.Public.models.LyftRideTypeEnum.Line:
                            rideType = "ms-appx://29Quizlet/Assets/LyftLine.png";
                            break;

                        case Api.Public.models.LyftRideTypeEnum.Premier:
                            rideType = "ms-appx://29Quizlet/Assets/LyftPremier.png";
                            break;

                        default:
                            break;
                        }

                        var elem = new ActiveRide()
                        {
                            RideInProgress   = "This ride is in progress.",
                            RideStatus       = $"Ride is {ride.Status}, click to continue...",
                            RideTypeImageSrc = new BitmapImage(new Uri(rideType)),
                            RideId           = ride.RideId,
                        };

                        Rides.Add(elem);
                    }
                }
            }

            await Task.CompletedTask;
        }
 public void Show(string content, string title)
 {
     IAsyncOperation <IUICommand> command = new MessageDialog(content, title).ShowAsync();
 }
Esempio n. 34
0
 public async static void ShowDialog(string message)
 {
     var dlg = new MessageDialog(message);
     await dlg.ShowAsync();
 }
 private async void ShowMessage(string msg)
 {
     MessageDialog msgBox = new MessageDialog(msg);
     await msgBox.ShowAsync();
 }
Esempio n. 36
0
        void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageDialog msgDialog = new MessageDialog(e.Message);

            msgDialog.ShowAsync();
        }
Esempio n. 37
0
        public Windows()
        {
            Button bp = new Button("Show borderless window");

            PackStart(bp);
            bp.Clicked += delegate {
                Window w = new Window();
                w.Decorated = false;
                Button c = new Button("This is a window");
//				c.Margin.SetAll (10);
                w.Content  = c;
                c.Clicked += delegate {
                    w.Dispose();
                };
                var bpos = bp.ScreenBounds;
                w.ScreenBounds = new Rectangle(bpos.X, bpos.Y + bp.Size.Height, w.Width, w.Height);
                w.Show();
            };
            Button b = new Button("Show message dialog");

            PackStart(b);
            b.Clicked += delegate {
                MessageDialog.ShowMessage(ParentWindow, "Hi there!");
            };

            Button db = new Button("Show custom dialog");

            PackStart(db);
            db.Clicked += delegate {
                Dialog d = new Dialog();
                d.Title = "This is a dialog";
                Table t = new Table();
                t.Add(new Label("Some field:"), 0, 0);
                t.Add(new TextEntry(), 1, 0);
                t.Add(new Label("Another field:"), 0, 1);
                t.Add(new TextEntry(), 1, 1);
                d.Content         = t;
                d.CloseRequested += delegate(object sender, CloseRequestedEventArgs args) {
                    args.AllowClose = MessageDialog.Confirm("Really close?", Command.Close);
                };

                Command custom = new Command("Custom");
                d.Buttons.Add(new DialogButton(custom));
                d.Buttons.Add(new DialogButton("Custom OK", Command.Ok));
                d.Buttons.Add(new DialogButton(Command.Cancel));
                d.Buttons.Add(new DialogButton(Command.Ok));

                var r = d.Run(this.ParentWindow);
                db.Label = "Result: " + (r != null ? r.Label : "(Closed)");
                d.Dispose();
            };

            b = new Button("Show Open File dialog");
            PackStart(b);
            b.Clicked += delegate {
                OpenFileDialog dlg = new OpenFileDialog("Select a file");
                dlg.InitialFileName = "Some file";
                dlg.Multiselect     = true;
                dlg.Filters.Add(new FileDialogFilter("Xwt files", "*.xwt"));
                dlg.Filters.Add(new FileDialogFilter("All files", "*.*"));
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Files have been selected!", string.Join("\n", dlg.FileNames));
                }
            };

            b = new Button("Show Save File dialog");
            PackStart(b);
            b.Clicked += delegate {
                SaveFileDialog dlg = new SaveFileDialog("Select a file");
                dlg.InitialFileName = "Some file";
                dlg.Multiselect     = true;
                dlg.Filters.Add(new FileDialogFilter("Xwt files", "*.xwt"));
                dlg.Filters.Add(new FileDialogFilter("All files", "*.*"));
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Files have been selected!", string.Join("\n", dlg.FileNames));
                }
            };

            b = new Button("Show Select Folder dialog (Multi select)");
            PackStart(b);
            b.Clicked += delegate {
                SelectFolderDialog dlg = new SelectFolderDialog("Select some folder");
                dlg.Multiselect = true;
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Folders have been selected!", string.Join("\n", dlg.Folders));
                }
            };

            b = new Button("Show Select Folder dialog (Single select)");
            PackStart(b);
            b.Clicked += delegate {
                SelectFolderDialog dlg = new SelectFolderDialog("Select a folder");
                dlg.Multiselect = false;
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Folders have been selected!", string.Join("\n", dlg.Folders));
                }
            };

            b = new Button("Show Select Folder dialog (Single select, allow creation)");
            PackStart(b);
            b.Clicked += delegate {
                SelectFolderDialog dlg = new SelectFolderDialog("Select or create a folder");
                dlg.Multiselect      = false;
                dlg.CanCreateFolders = true;
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Folders have been selected/created!", string.Join("\n", dlg.Folders));
                }
            };

            b = new Button("Show Select Color dialog");
            PackStart(b);
            b.Clicked += delegate {
                SelectColorDialog dlg = new SelectColorDialog("Select a color");
                dlg.SupportsAlpha = true;
                dlg.Color         = Xwt.Drawing.Colors.AliceBlue;
                if (dlg.Run(ParentWindow))
                {
                    MessageDialog.ShowMessage("A color has been selected!", dlg.Color.ToString());
                }
            };

            b = new Button("Show window shown event");
            PackStart(b);
            b.Clicked += delegate
            {
                Window w = new Window();
                w.Decorated = false;
                Button c = new Button("This is a window with events on");
                w.Content  = c;
                c.Clicked += delegate
                {
                    w.Dispose();
                };
                w.Shown  += (sender, args) => MessageDialog.ShowMessage("My Parent has been shown");
                w.Hidden += (sender, args) => MessageDialog.ShowMessage("My Parent has been hidden");

                w.Show();
            };

            b = new Button("Show dialog with dynamically updating content");
            PackStart(b);
            b.Clicked += delegate
            {
                var dialog = new Dialog();
                dialog.Content = new Label("Hello World");
                Xwt.Application.TimeoutInvoke(TimeSpan.FromSeconds(2), () => {
                    dialog.Content = new Label("Goodbye World");
                    return(false);
                });
                dialog.Run();
            };

            b = new Button("Show dialog and make this window not sensitive");
            PackStart(b);
            b.Clicked += delegate
            {
                var dialog = new Dialog();
                dialog.Content = new Label("Hello World");
                dialog.Run();
                dialog.Shown  += (sender, args) => this.ParentWindow.Sensitive = false;
                dialog.Closed += (sender, args) => this.ParentWindow.Sensitive = true;
            };
        }
Esempio n. 38
0
 private void Show(string content, string title) =>
 _ = new MessageDialog(content, title).ShowAsync();
Esempio n. 39
0
 private async void showDialog(string content)
 {
     MessageDialog dialog = new MessageDialog(content, "Fatal Error");
     await dialog.ShowAsync();
 }
Esempio n. 40
0
        /*
         * 分为地图查找和交通路况显示,由checkbox控制
         */
        private async void searchMap(object sender, RoutedEventArgs e)
        {
            currentCity = "";
            if (searchTraffic.IsChecked == false)
            {
                if (mapSearchBlock.Text != "")
                {
                    string     url    = "http://restapi.amap.com/v3/geocode/geo?key=5fd3b8bd943a505ccfec387943bba945&address=" + mapSearchBlock.Text;
                    HttpClient client = new HttpClient();
                    string     result = await client.GetStringAsync(url);

                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    if (jo["status"].ToString() == "0" || jo["count"].ToString() == "0")
                    {
                        var i = new MessageDialog("查无此地区").ShowAsync();
                    }
                    else
                    {
                        JArray ja       = (JArray)jo["geocodes"];
                        string location = ja[0]["location"].ToString();
                        currentCity = ja[0]["formatted_address"].ToString();

                        string url2 = "http://restapi.amap.com/v3/staticmap?key=5fd3b8bd943a505ccfec387943bba945&location=" + location + "&zoom=10&size=731*458&labels=" + mapSearchBlock.Text + ",2,0,16,0xFFFFFF,0x008000:" + location;
                        HttpResponseMessage response = await client.GetAsync(url2);

                        BitmapImage bitmap = new BitmapImage();
                        Stream      stream = await response.Content.ReadAsStreamAsync();

                        IInputStream inputStream = stream.AsInputStream();
                        using (IRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream())
                        {
                            using (IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0))
                            {
                                await RandomAccessStream.CopyAsync(inputStream, outputStream);

                                randomAccessStream.Seek(0);
                                bitmap.SetSource(randomAccessStream);
                                map.Source = bitmap;
                            }
                        }
                    }
                }
            }
            else
            {
                if (mapSearchBlock.Text != "")
                {
                    string     url    = "http://restapi.amap.com/v3/geocode/geo?key=5fd3b8bd943a505ccfec387943bba945&address=" + mapSearchBlock.Text;
                    HttpClient client = new HttpClient();
                    string     result = await client.GetStringAsync(url);

                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    if (jo["status"].ToString() == "0" || jo["count"].ToString() == "0")
                    {
                        var i = new MessageDialog("查无此地区").ShowAsync();
                    }
                    else
                    {
                        JArray ja       = (JArray)jo["geocodes"];
                        string location = ja[0]["location"].ToString();
                        currentCity = ja[0]["formatted_address"].ToString();

                        string url2 = "http://restapi.amap.com/v3/staticmap?key=5fd3b8bd943a505ccfec387943bba945&zoom=10&size=731*458&traffic=1&location=" + location;
                        HttpResponseMessage response = await client.GetAsync(url2);

                        BitmapImage bitmap = new BitmapImage();
                        Stream      stream = await response.Content.ReadAsStreamAsync();

                        IInputStream inputStream = stream.AsInputStream();
                        using (IRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream())
                        {
                            using (IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0))
                            {
                                await RandomAccessStream.CopyAsync(inputStream, outputStream);

                                randomAccessStream.Seek(0);
                                bitmap.SetSource(randomAccessStream);
                                map.Source = bitmap;
                            }
                        }
                    }
                }
            }
        }
            // Export DataTable into an excel file with field names in the header line
            // - Save excel file without ever making it visible if filepath is given
            // - Don't save excel file, just make it visible if no filepath is given
            public static string ExportToExcel
            (
                DataTable tbl,
                string excelFilePath = null)
            {
                if (string.IsNullOrEmpty(excelFilePath))
                {
                    return(excelFilePath);
                }
                excelFilePath = excelFilePath + "LogBook_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                try
                {
                    if (tbl == null || tbl.Columns.Count == 0)
                    {
                        MessageDialog.Show
                        (
                            "ExportToExcel: Null or empty input table!",
                            "Error Log Not found For This Date!"
                        );
                        return(null);
                    }

                    // load excel, and create a new workbook
                    var excelApp = new Application();
                    excelApp.Workbooks.Add();

                    // single worksheet
                    _Worksheet workSheet = excelApp.ActiveSheet;

                    // column headings
                    for (int i = 0;
                         i < tbl.Columns.Count;
                         i++)
                    {
                        workSheet.Cells[1,
                                        (i + 1)] = tbl.Columns[i].ColumnName;
                    }

                    // rows
                    for (int i = 0;
                         i < tbl.Rows.Count;
                         i++)
                    {
                        // to do: format datetime values before printing
                        for (int j = 1;
                             j < tbl.Columns.Count;
                             j++)
                        {
                            workSheet.Cells[(i + 2),
                                            (j + 1)] = tbl.Rows[i][j];
                        }
                    }

                    try
                    {
                        workSheet.SaveAs(excelFilePath);
                        excelApp.Quit();
                        return(excelFilePath);
                        // MessageBox.Show("Excel file saved!");
                    }
                    catch (Exception ex)
                    {
                        throw new Exception
                              (
                                  "ExportToExcel: Excel file could not be saved! Check filepath.\n"
                                  + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: \n" + ex.Message);
                }
            }
Esempio n. 42
0
 public async Task ShowInfoMessageBox(string text)
 {
     var dialog = new MessageDialog(text);
     await dialog.ShowAsync();
 }
Esempio n. 43
0
        // Handle a new selected comment record in the table view.
        private async void CommentsListBox_SelectionChanged(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

            // Get the selected comment feature. If there is no selection, return.
            ArcGISFeature selectedComment = e.AddedItems[0] as ArcGISFeature;

            if (selectedComment == null)
            {
                return;
            }

            // Get the map image layer that contains the service request sublayer and the service request comments table.
            ArcGISMapImageLayer serviceRequestsMapImageLayer = (ArcGISMapImageLayer)MyMapView.Map.OperationalLayers[0];

            // Get the (non-spatial) table that contains the service request comments.
            ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];

            // Get the relationship that defines related service request features for features in the comments table (this is the first and only relationship).
            RelationshipInfo commentsRelationshipInfo = commentsTable.LayerInfo.RelationshipInfos.FirstOrDefault();

            // Create query parameters to get the related service request for features in the comments table.
            RelatedQueryParameters relatedQueryParams = new RelatedQueryParameters(commentsRelationshipInfo)
            {
                ReturnGeometry = true
            };

            try
            {
                // Query the comments table to get the related service request feature for the selected comment.
                IReadOnlyList <RelatedFeatureQueryResult> relatedRequestsResult = await commentsTable.QueryRelatedFeaturesAsync(selectedComment, relatedQueryParams);

                // Get the first result.
                RelatedFeatureQueryResult result = relatedRequestsResult.FirstOrDefault();

                // Get the first feature from the result. If it's null, warn the user and return.
                ArcGISFeature serviceRequestFeature = result.FirstOrDefault() as ArcGISFeature;
                if (serviceRequestFeature == null)
                {
                    MessageDialog message = new MessageDialog("Related feature not found.", "No Feature");
                    await message.ShowAsync();

                    return;
                }

                // Load the related service request feature (so its geometry is available).
                await serviceRequestFeature.LoadAsync();

                // Get the service request geometry (point).
                MapPoint serviceRequestPoint = serviceRequestFeature.Geometry as MapPoint;

                // Create a cyan marker symbol to display the related feature.
                Symbol selectedRequestSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Cyan, 14);

                // Create a graphic using the service request point and marker symbol.
                Graphic requestGraphic = new Graphic(serviceRequestPoint, selectedRequestSymbol);

                // Add the graphic to the graphics overlay and zoom the map view to its extent.
                _selectedFeaturesOverlay.Graphics.Add(requestGraphic);
                await MyMapView.SetViewpointCenterAsync(serviceRequestPoint, 150000);
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.ToString(), "Error").ShowAsync();
            }
        }
Esempio n. 44
0
 async void MapElement_ClickEvent2(object sendeer, MapElementsLayerClickEventArgs e)
 {
     var dialog = new MessageDialog("Pushpin 4 was clicked!");
     await dialog.ShowAsync();
 }
Esempio n. 45
0
        /// <summary>
        /// On export-publishednodes button clicked
        //  -- generate "publishednodes.json" file to target file path
        /// <summary>
        private async void btnExportPublishedNodes_Click(object sender, RoutedEventArgs e)
        {
            if (sessionConfig?.sessions?.Count > 0)
            {
            }
            else
            {
                MessageDialog showDialog = new MessageDialog("No Node for Publishing!");
                showDialog.Commands.Add(new UICommand("Close")
                {
                    Id = 1
                });
                showDialog.DefaultCommandIndex = 1;
                showDialog.CancelCommandIndex  = 1;
                await showDialog.ShowAsync();

                return;
            }

            var picker = new Windows.Storage.Pickers.FileSavePicker();

            picker.SuggestedFileName      = SiteProfileManager.DEFAULT_PUBLISHEDNODESPATH;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads;
            picker.FileTypeChoices.Add("JSON", new List <string>()
            {
                ".json"
            });

            StorageFile destfile = await picker.PickSaveFileAsync();

            if (destfile != null)
            {
                try
                {
                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                    bool          isSuccess   = await SiteProfileManager.DefaultSiteProfileManager?.SavePublishedNodes();

                    if (isSuccess)
                    {
                        var         srcuri  = new Uri("ms-appdata:///local/" + SiteProfileManager.GetFullPath(App.SiteProfileId, SiteProfileManager.DEFAULT_PUBLISHEDNODESPATH));
                        StorageFile srcfile = await StorageFile.GetFileFromApplicationUriAsync(srcuri);

                        await srcfile.CopyAndReplaceAsync(destfile);

                        MessageDialog showDialog = new MessageDialog("Export PublisherNodes Done!\n" + destfile.Path);
                        showDialog.Commands.Add(new UICommand("Close")
                        {
                            Id = 1
                        });
                        showDialog.DefaultCommandIndex = 1;
                        showDialog.CancelCommandIndex  = 1;
                        await showDialog.ShowAsync();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("btnExportPublishedNodes_Click Exception! " + ex.Message);
                    MessageDialog showDialog = new MessageDialog("Export PublishedNodes Failed!\nError: " + ex.Message);
                    showDialog.Commands.Add(new UICommand("Close")
                    {
                        Id = 1
                    });
                    showDialog.DefaultCommandIndex = 1;
                    showDialog.CancelCommandIndex  = 1;
                    await showDialog.ShowAsync();
                }
            }
        }
Esempio n. 46
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter != null)
            {
                geolocator.DesiredAccuracyInMeters = 150;
                // получаем позицию
                var position = await geolocator.GetGeopositionAsync();

                // установка этой позиции на карте
                // Specify a known location.
                BasicGeoposition snPosition = new BasicGeoposition()
                {
                    Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude
                };
                Geopoint snPoint = new Geopoint(snPosition);

                // Create a MapIcon.
                MapIcon mapIcon2 = new MapIcon();
                mapIcon2.Location = snPoint;
                mapIcon2.NormalizedAnchorPoint = new Point(0.5, 1.0);



                mapIcon2.Title  = e.Parameter.ToString();
                mapIcon2.ZIndex = 0;
                objectList.Add(mapIcon2);
                // Add the MapIcon to the map.
                foreach (MapIcon o in objectList)
                {
                    map.MapElements.Add(o);
                }
            }



            try
            {
                map.MapServiceToken = "mapToken";
                // получаем инструмент геолокации

                //точность геолокации до 150 метров
                geolocator.DesiredAccuracyInMeters = 150;
                // получаем позицию
                var position = await geolocator.GetGeopositionAsync();

                // установка этой позиции на карте
                // Specify a known location.
                BasicGeoposition snPosition = new BasicGeoposition()
                {
                    Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude
                };
                Geopoint snPoint = new Geopoint(snPosition);

                // Create a MapIcon.
                MapIcon mapIcon1 = new MapIcon();
                mapIcon1.Location = snPoint;
                mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0);
                mapIcon1.Title  = "Вы";
                mapIcon1.ZIndex = 0;

                // Add the MapIcon to the map.
                map.MapElements.Add(mapIcon1);

                // Center the map over the POI.
                map.Center    = snPoint;
                map.ZoomLevel = 14;
            }
            catch
            {
                MessageDialog msgbox = new MessageDialog("Невозможно получить данные местоположения", "Ошибка");
                await msgbox.ShowAsync();
            }
        }
        public static async Task <GenericResponse> GetList(int TipoId, string filtro = "", string ordenar_por = "", string orden = "", int Page = 1)
        {
            GenericResponse response = new GenericResponse();

            try
            {
                List <CloureParam> cparams = new List <CloureParam>();
                cparams.Add(new CloureParam("module", "products_services_categories"));
                cparams.Add(new CloureParam("topic", "listar"));
                cparams.Add(new CloureParam("tipo_id", TipoId));
                if (filtro.Length > 0)
                {
                    cparams.Add(new CloureParam("filtro", filtro));
                }
                if (ordenar_por.Length > 0)
                {
                    cparams.Add(new CloureParam("ordenar_por", ordenar_por));
                }
                if (orden.Length > 0)
                {
                    cparams.Add(new CloureParam("orden", orden));
                }
                cparams.Add(new CloureParam("pagina", Page.ToString()));
                string res = await CloureManager.ExecuteAsync(cparams);

                JsonObject api_result = JsonObject.Parse(res);
                string     error      = api_result.GetNamedString("Error");
                if (error == "")
                {
                    JsonObject api_response = api_result.GetNamedObject("Response");
                    JsonArray  registers    = api_response.GetNamedArray("Registros");

                    foreach (JsonValue jsonValue in registers)
                    {
                        JsonObject             register = jsonValue.GetObject();
                        ProductServiceCategory item     = new ProductServiceCategory();
                        item.Id   = (int)register.GetNamedNumber("Id");
                        item.Name = register.GetNamedString("Nombre");

                        JsonArray available_commands_arr = register.GetNamedArray("AvailableCommands");
                        item.AvailableCommands = new List <AvailableCommand>();
                        foreach (JsonValue available_cmd_obj in available_commands_arr)
                        {
                            JsonObject       available_cmd_item  = available_cmd_obj.GetObject();
                            int              available_cmd_id    = (int)available_cmd_item.GetNamedNumber("Id");
                            string           available_cmd_name  = available_cmd_item.GetNamedString("Name");
                            string           available_cmd_title = available_cmd_item.GetNamedString("Title");
                            AvailableCommand availableCommand    = new AvailableCommand(available_cmd_id, available_cmd_name, available_cmd_title);
                            item.AvailableCommands.Add(availableCommand);
                        }

                        response.Items.Add(item);
                    }

                    response.TotalPages = (int)api_response.GetNamedNumber("TotalPaginas");
                    response.PageString = api_response.GetNamedString("PageString");
                }
                else
                {
                    throw new Exception(error);
                }
            }
            catch (Exception ex)
            {
                var dialog = new MessageDialog(ex.Message);
                await dialog.ShowAsync();
            }

            return(response);
        }
        public async Task ShowAsync(string title, string message)
        {
            var messageDialog = new MessageDialog(message, title);

            await messageDialog.ShowAsync();
        }
Esempio n. 49
0
        private async void SaveMapClicked(object sender, RoutedEventArgs e)
        {
            try
            {
                // Don't attempt to save if the OAuth settings weren't provided
                if (string.IsNullOrEmpty(AppClientId) || string.IsNullOrEmpty(OAuthRedirectUrl))
                {
                    var dialog = new MessageDialog("OAuth settings were not provided.", "Cannot Save");
                    await dialog.ShowAsync();

                    SaveMapFlyout.Hide();

                    return;
                }

                // Show the progress bar so the user knows work is happening
                SaveProgressBar.Visibility = Visibility.Visible;

                // Get the current map
                var myMap = MyMapView.Map;

                // Apply the current extent as the map's initial extent
                myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // See if the map has already been saved (has an associated portal item)
                if (myMap.Item == null)
                {
                    // Get information for the new portal item
                    var title       = TitleTextBox.Text;
                    var description = DescriptionTextBox.Text;
                    var tagText     = TagsTextBox.Text;

                    // Make sure all required info was entered
                    if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description) || string.IsNullOrEmpty(tagText))
                    {
                        throw new Exception("Please enter a title, description, and some tags to describe the map.");
                    }

                    // Call a function to save the map as a new portal item
                    await SaveNewMapAsync(MyMapView.Map, title, description, tagText.Split(','));

                    // Report a successful save
                    var messageDialog = new MessageDialog("Saved '" + title + "' to ArcGIS Online!", "Map Saved");
                    await messageDialog.ShowAsync();
                }
                else
                {
                    // This is not the initial save, call SaveAsync to save changes to the existing portal item
                    await myMap.SaveAsync();

                    // Report update was successful
                    var messageDialog = new MessageDialog("Saved changes to '" + myMap.Item.Title + "'", "Updates Saved");
                    await messageDialog.ShowAsync();
                }

                // Update the portal item thumbnail with the current map image
                try
                {
                    // Export the current map view
                    var mapImage = await Esri.ArcGISRuntime.UI.RuntimeImageExtensions.ToImageSourceAsync(await MyMapView.ExportImageAsync());

                    // Call a function that writes a temporary jpeg file of the map
                    var imagePath = await WriteTempThumbnailImageAsync(mapImage);

                    // Call a function to update the portal item's thumbnail with the image
                    UpdatePortalItemThumbnailAsync(imagePath);
                }
                catch
                {
                    // Throw an exception to let the user know the thumbnail was not saved (the map item was)
                    throw new Exception("Thumbnail was not updated.");
                }
            }
            catch (Exception ex)
            {
                // Report error message
                var messageDialog = new MessageDialog("Error saving map to ArcGIS Online: " + ex.Message);
                await messageDialog.ShowAsync();
            }
            finally
            {
                // Hide the progress bar
                SaveProgressBar.Visibility = Visibility.Collapsed;
            }
        }
Esempio n. 50
0
        private async void BtnConfirmOrder_Click(object sender, RoutedEventArgs e)
        {
            MessageDialog dialog;

            //if the temporary order items list is not empty
            if (orderItems.Count != 0)
            {
                //if no employee or customer is logged
                if (App.employeeLogged != null || App.customerLogged != null)
                {
                    //default proceed value is true
                    bool proceed = true;
                    //loop through the list
                    foreach (Item item in orderItems)
                    {
                        //if the NumInEachOrder of an item is more than its stock
                        if (item.NumInEachOrder > item.Stock)
                        {
                            //set proceed to false
                            proceed = false;
                        }
                    }
                    //if proceed is true
                    if (proceed == true)
                    {
                        //set the current order's order items to the temporary order items list
                        App.currentOrder.OrderItems = orderItems;
                        //update the current order in the database
                        App.MY_ORDERVIEWMODEL.UpdateOrder(App.currentOrder);
                        //if the employee is logged
                        if (App.employeeLogged != null)
                        {
                            //display message
                            dialog = new MessageDialog("Order has been updated", "Order Updated");
                            await dialog.ShowAsync();

                            //navigate to the Sale Page
                            this.Frame.Navigate(typeof(SalePage));
                        }
                        //if the customer is logged
                        else if (App.customerLogged != null)
                        {
                            //display message
                            dialog = new MessageDialog("Your order has been updated.\nPlease proceed to the counter to make your purchase", "Order Updated");
                            await dialog.ShowAsync();

                            //set logged customer and current order to null
                            App.customerLogged = null;
                            App.currentOrder   = null;
                            //navigate to the Main Menu
                            this.Frame.Navigate(typeof(MainMenu));
                        }
                    }
                    else
                    {
                        //display error message
                        dialog = new MessageDialog("One or more of your order items is more than the stock we have.\nPlease change the number of order items in your cart.", "Cannot Update Order");
                        await dialog.ShowAsync();
                    }
                }
                else
                {
                    //get the current order ID
                    int currentID = Int32.Parse(txtOrderNum.Text);
                    //create a new order
                    App.currentOrder = new Order(currentID, "", new Customer(), false, orderItems);
                    //display the Add Customer Details Content Dialog
                    AddCustomerDetails customerDetails = new AddCustomerDetails();
                    await customerDetails.ShowAsync();
                }
            }
            else
            {
                //display error message
                dialog = new MessageDialog("Please select items you'd like to purchase", "Select Item");
                await dialog.ShowAsync();
            }
        }
Esempio n. 51
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(XmppClient).GetTypeInfo().Assembly,
                    typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(XML).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Persistence.SQL.Select).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                string Host = await RuntimeSettings.GetAsync("XmppHost", "waher.se");

                int Port = (int)await RuntimeSettings.GetAsync("XmppPort", 5222);

                string UserName = await RuntimeSettings.GetAsync("XmppUserName", string.Empty);

                string PasswordHash = await RuntimeSettings.GetAsync("XmppPasswordHash", string.Empty);

                string PasswordHashMethod = await RuntimeSettings.GetAsync("XmppPasswordHashMethod", string.Empty);

                if (string.IsNullOrEmpty(Host) ||
                    Port <= 0 || Port > ushort.MaxValue ||
                    string.IsNullOrEmpty(UserName) ||
                    string.IsNullOrEmpty(PasswordHash) ||
                    string.IsNullOrEmpty(PasswordHashMethod))
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                async() => await this.ShowConnectionDialog(Host, Port, UserName));
                }
                else
                {
                    this.xmppClient = new XmppClient(Host, Port, UserName, PasswordHash, PasswordHashMethod, "en",
                                                     typeof(App).GetTypeInfo().Assembly) // Add "new LogSniffer()" to the end, to output communication to the log.
                    {
                        AllowCramMD5   = false,
                        AllowDigestMD5 = false,
                        AllowPlain     = false,
                        AllowScramSHA1 = true
                    };
                    this.xmppClient.OnStateChanged    += this.StateChanged;
                    this.xmppClient.OnConnectionError += this.ConnectionError;

                    Log.Informational("Connecting to " + this.xmppClient.Host + ":" + this.xmppClient.Port.ToString());
                    this.xmppClient.Connect();
                }

                this.minuteTimer = new Timer((State) =>
                {
                    if (this.xmppClient != null &&
                        (this.xmppClient.State == XmppState.Error || this.xmppClient.State == XmppState.Offline))
                    {
                        this.xmppClient.Reconnect();
                    }
                }, null, 60000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Esempio n. 52
0
        public async void Login_Click(object sender, RoutedEventArgs e)
        {
            if (!Regex.IsMatch(UserName.Text.Trim(), @"^[A-Za-z_][a-zA-Z0-9_\s]*$"))
            {
                //MessageBox.Show("Invalid UserName");
                var dialog = new MessageDialog("Invalid UserName");
                await dialog.ShowAsync();
            }
            //Password length Validation
            else if (PassWord.Password.Length < 6)
            {
                //MessageBox.Show("Password length should be minimum of 6 characters!");
                var dialog = new MessageDialog("Password length is greater than 6 characters!");
                await dialog.ShowAsync();
            }
            //    //After validation success ,store user detials and also check information
            else if (UserName.Text != "" && PassWord.Password != "")
            {
                var firebase = new FirebaseClient("https://calendarbot-2573c.firebaseio.com/");
                var username = await firebase
                               .Child("users")
                               .OnceAsync <UserName>();

                MainPage.log = UserName.Text;

                bool       find          = false;
                bool       err           = false;
                string     urlParameters = "https://calendarbot-2573c.firebaseio.com/users/" + UserName.Text + "/password.json";
                HttpClient client        = new HttpClient();

                HttpResponseMessage response = client.GetAsync(urlParameters).Result;

                string responseBody = await response.Content.ReadAsStringAsync();

                if (responseBody != "null")
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string pa    = PassWord.Password;
                        var    json  = JObject.Parse(responseBody);
                        var    first = json.Properties().Select(p => p.Name).FirstOrDefault();
                        if (first == PassWord.Password)
                        {
                            find = true;
                        }
                    }
                }
                else
                {
                    var dialog = new MessageDialog("Wrong username or password");
                    await dialog.ShowAsync();
                }


                foreach (var u in username)
                {
                    if (u.Key == UserName.Text && find == true)
                    {
                        MainPage.accessPage = true;
                        LoginFrame.Navigate(typeof(MainPage));
                    }
                    else if (u.Key == UserName.Text && find != true)
                    {
                        err = true;
                    }
                }

                if (err == true)
                {
                    var dialog = new MessageDialog("Wrong username or password");
                    await dialog.ShowAsync();
                }
            }
        }
        private async void calendar_DoubleTapped(object sender, RoutedEventArgs e)
        {
            if (_calTask != null)
            {
                // if there is already opened task, cancel it first
                _calTask.Cancel();
                _calTask.Close();
                _calTask = null;
            }
            // show the list of appointments for the bolded day
            FrameworkElement fel = e.OriginalSource as FrameworkElement;

            if (fel != null)
            {
                DaySlot slot = fel.DataContext as DaySlot;
                if (slot != null)
                {
                    DateTime date    = slot.Date;
                    string   message = date.ToString();
                    if (slot.DataSource == null || slot.DataSource.Count == 0)
                    {
                        if (UseAppointmentManager)
                        {
                            // create new appointment and fill initial properties
                            Windows.ApplicationModel.Appointments.Appointment app = new Windows.ApplicationModel.Appointments.Appointment();
                            app.StartTime = date;
                            app.AllDay    = true;
                            app.Subject   = Strings.DeviceAppointmentSubject;
                            // Show the Appointments provider Add Appointment UI, to enable the user to add an appointment.
                            // The returned id can be used later to edit or remove existent appointment.
                            _calTask = AppointmentManager.ShowEditNewAppointmentAsync(app);
                            string id = await _calTask;
                            Refresh(calendar.DisplayDate);
                            _calTask = null;
                            return;
                        }
                        else
                        {
                            if (!Device.IsWindowsPhoneDevice())
                            {
                                DataTemplate boldedDaySlotTemplate = this.Resources["BoldedDaySlotTemplate"] as DataTemplate;
                                calendar.BoldedDaySlotTemplate = boldedDaySlotTemplate;
                                Appointment app = new Appointment();
                                app.Start    = calendar.SelectedDate;
                                app.Duration = TimeSpan.FromDays(1);
                                app.Subject  = Strings.AppointmentSubject + " " + app.Start.ToString();
                                _appointments.Add(app);
                                calendar.DataSource = _appointments;
                                return;
                            }
                            else
                            {
                                message += "\r\n" + Strings.Message;
                            }
                        }
                    }
                    else
                    {
                        if (!UseAppointmentManager)
                        {
                            foreach (Appointment app in slot.DataSource)
                            {
                                message += "\r\n" + app.Subject;
                            }
                        }
                        else
                        {
                            foreach (Windows.ApplicationModel.Appointments.Appointment app in slot.DataSource)
                            {
                                message += "\r\n" + app.Subject;
                            }
                        }
                        var dialog = new MessageDialog(message);
                        dialog.ShowAsync();
                    }
                }
            }
        }
Esempio n. 54
0
        /// <summary>
        /// Creates PDF
        /// </summary>
        public async void CreatePDF(IList <InvoiceItem> dataSource, BillingInformation billInfo, double totalDue)
        {
            PdfDocument document = new PdfDocument();

            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            PdfPage        page    = document.Pages.Add();
            PdfGraphics    g       = page.Graphics;
            PdfTextElement element = new PdfTextElement(@"Syncfusion Software 
2501 Aerial Center Parkway 
Suite 200 Morrisville, NC 27560 USA 
Tel +1 888.936.8638 Fax +1 919.573.0306");

            element.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            PdfLayoutResult result = element.Draw(page, new RectangleF(0, 0, page.Graphics.ClientSize.Width / 2, 200));

            Stream imgStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Invoice.Assets.SyncfusionLogo.jpg");

            PdfImage img = PdfImage.FromStream(imgStream);

            page.Graphics.DrawImage(img, new RectangleF(g.ClientSize.Width - 200, result.Bounds.Y, 190, 45));
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);

            g.DrawRectangle(new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(0, result.Bounds.Bottom + 40, g.ClientSize.Width, 30));
            element       = new PdfTextElement("INVOICE " + billInfo.InvoiceNumber.ToString(), subHeadingFont);
            element.Brush = PdfBrushes.White;
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 48));
            string currentDate = "DATE " + billInfo.Date.ToString("d");
            SizeF  textSize    = subHeadingFont.MeasureString(currentDate);

            g.DrawString(currentDate, subHeadingFont, element.Brush, new PointF(g.ClientSize.Width - textSize.Width - 10, result.Bounds.Y));

            element       = new PdfTextElement("BILL TO ", new PdfStandardFont(PdfFontFamily.TimesRoman, 12));
            element.Brush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));

            g.DrawLine(new PdfPen(new PdfColor(34, 83, 142), 0.70f), new PointF(0, result.Bounds.Bottom + 3), new PointF(g.ClientSize.Width, result.Bounds.Bottom + 3));

            element       = new PdfTextElement(billInfo.Name, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 5, g.ClientSize.Width / 2, 100));

            element       = new PdfTextElement(billInfo.Address, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 3, g.ClientSize.Width / 2, 100));
            string[] headers = new string[] { "Item", "Quantity", "Rate", "Taxes", "Amount" };
            PdfGrid  grid    = new PdfGrid();

            grid.Columns.Add(headers.Length);
            //Adding headers in to the grid
            grid.Headers.Add(1);
            PdfGridRow headerRow = grid.Headers[0];
            int        count     = 0;

            foreach (string columnName in headers)
            {
                headerRow.Cells[count].Value = columnName;
                count++;
            }
            //Adding rows into the grid
            foreach (var item in dataSource)
            {
                PdfGridRow row = grid.Rows.Add();
                row.Cells[0].Value = item.ItemName;
                row.Cells[1].Value = item.Quantity.ToString();
                row.Cells[2].Value = "$" + item.Rate.ToString("#,###.00", CultureInfo.InvariantCulture);
                row.Cells[3].Value = "$" + item.Taxes.ToString("#,###.00", CultureInfo.InvariantCulture);
                row.Cells[4].Value = "$" + item.TotalAmount.ToString("#,###.00", CultureInfo.InvariantCulture);
            }

            PdfGridCellStyle cellStyle = new PdfGridCellStyle();

            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];

            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

            headerStyle.Borders.All     = new PdfPen(new PdfColor(34, 83, 142));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            headerStyle.TextBrush       = PdfBrushes.White;
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            for (int i = 0; i < header.Cells.Count; i++)
            {
                if (i == 0)
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }

            header.Cells[0].Value = "ITEM";
            header.Cells[1].Value = "QUANTITY";
            header.Cells[2].Value = "RATE";
            header.Cells[3].Value = "TAXES";
            header.Cells[4].Value = "AMOUNT";
            header.ApplyStyle(headerStyle);
            grid.Columns[0].Width    = 180;
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(34, 83, 142), 0.70f);
            cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f);
            cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(0, 0, 0));
            foreach (PdfGridRow row in grid.Rows)
            {
                row.ApplyStyle(cellStyle);
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    PdfGridCell cell = row.Cells[i];
                    if (i == 0)
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }

                    if (i > 1)
                    {
                        if (cell.Value.ToString().Contains("$"))
                        {
                            cell.Value = cell.Value.ToString();
                        }
                        else
                        {
                            if (cell.Value is double)
                            {
                                cell.Value = "$" + ((double)cell.Value).ToString("#,###.00", CultureInfo.InvariantCulture);
                            }
                            else
                            {
                                cell.Value = "$" + cell.Value.ToString();
                            }
                        }
                    }
                }
            }

            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            layoutFormat.Layout = PdfLayoutType.Paginate;

            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(g.ClientSize.Width, g.ClientSize.Height - 100)), layoutFormat);
            float pos = 0.0f;

            for (int i = 0; i < grid.Columns.Count - 1; i++)
            {
                pos += grid.Columns[i].Width;
            }

            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);

            gridResult.Page.Graphics.DrawString("TOTAL DUE", font, new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 10), new SizeF(grid.Columns[3].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right));
            gridResult.Page.Graphics.DrawString("Thank you for your business!", new PdfStandardFont(PdfFontFamily.TimesRoman, 12), new PdfSolidBrush(new PdfColor(0, 0, 0)), new PointF(pos - 210, gridResult.Bounds.Bottom + 60));
            pos += grid.Columns[4].Width;
            gridResult.Page.Graphics.DrawString("$" + totalDue.ToString("#,###.00", CultureInfo.InvariantCulture), font, new PdfSolidBrush(new PdfColor(0, 0, 0)), new RectangleF(pos, gridResult.Bounds.Bottom + 10, grid.Columns[4].Width - pos, 20), new PdfStringFormat(PdfTextAlignment.Right));
            StorageFile stFile = null;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.DefaultFileExtension = ".pdf";
                savePicker.SuggestedFileName    = "Invoice";
                savePicker.FileTypeChoices.Add("Adobe PDF Document", new List <string>()
                {
                    ".pdf"
                });
                stFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                stFile = await local.CreateFileAsync("Invoice.pdf", CreationCollisionOption.ReplaceExisting);
            }

            if (stFile != null)
            {
                Stream stream = await stFile.OpenStreamForWriteAsync();

                await document.SaveAsync(stream);

                stream.Flush();
                stream.Dispose();
                document.Close(true);

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(stFile);
                }
            }
        }
Esempio n. 55
0
 private async void DisplayErrorMessage(string message)
 {
     var errorDialog = new MessageDialog(message);
     await errorDialog.ShowAsync();
 }
Esempio n. 56
0
        // Double-tap event for DataGrid
        public static async void List_ItemClick(object sender, DoubleTappedRoutedEventArgs e)
        {
            if (page.Name == "GenericItemView")
            {
                var index = GenericFileBrowser.data.SelectedIndex;

                if (index > -1)
                {
                    var clickedOnItem = ItemViewModel.FilesAndFolders[index];

                    if (clickedOnItem.FileExtension == "Folder")
                    {
                        ItemViewModel.TextState.isVisible = Visibility.Collapsed;
                        History.ForwardList.Clear();
                        ItemViewModel.FS.isEnabled = false;
                        ItemViewModel.FilesAndFolders.Clear();
                        if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory))
                        {
                            GenericFileBrowser.P.path = "Desktop";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "DesktopIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.DesktopPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Desktop";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
                        {
                            GenericFileBrowser.P.path = "Documents";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "DocumentsIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.DocumentsPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Documents";
                        }
                        else if (clickedOnItem.FilePath == (Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads"))
                        {
                            GenericFileBrowser.P.path = "Downloads";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "DownloadsIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.DownloadsPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Downloads";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyPictures))
                        {
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "PicturesIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(PhotoAlbum), YourHome.PicturesPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Pictures";
                            GenericFileBrowser.P.path = "Pictures";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyMusic))
                        {
                            GenericFileBrowser.P.path = "Music";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "MusicIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.MusicPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Music";
                        }
                        else if (clickedOnItem.FilePath == (Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\OneDrive"))
                        {
                            GenericFileBrowser.P.path = "OneDrive";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "OneD_IC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.OneDrivePath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search OneDrive";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))
                        {
                            GenericFileBrowser.P.path = "Videos";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "VideosIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.VideosPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Videos";
                        }
                        else
                        {
                            if (clickedOnItem.FilePath.Contains("C:"))
                            {
                                foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                                {
                                    if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "LocD_IC")
                                    {
                                        MainPage.Select.itemSelected = NavItemChoice;
                                        break;
                                    }
                                }
                            }
                            GenericFileBrowser.P.path = clickedOnItem.FilePath;
                            ItemViewModel.ViewModel   = new ItemViewModel(clickedOnItem.FilePath, GenericFileBrowser.GFBPageName);
                        }
                    }
                    else if (clickedOnItem.FileExtension == "Executable")
                    {
                        message       = new MessageDialog("We noticed you’re trying to run an executable file. This type of file may be a security risk to your device, and is not supported by the Universal Windows Platform. If you're not sure what this means, check out the Microsoft Store for a large selection of secure apps, games, and more.");
                        message.Title = "Unsupported Functionality";
                        message.Commands.Add(new UICommand("Continue...", new UICommandInvokedHandler(Interaction.CommandInvokedHandler)));
                        message.Commands.Add(new UICommand("Cancel"));
                        await message.ShowAsync();
                    }
                    else
                    {
                        StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.FilePath);

                        var options = new LauncherOptions
                        {
                            DisplayApplicationPicker = true
                        };
                        await Launcher.LaunchFileAsync(file, options);
                    }
                }
            }
            else if (page.Name == "PhotoAlbumViewer")
            {
                var index = PhotoAlbum.gv.SelectedIndex;

                if (index > -1)
                {
                    var clickedOnItem = ItemViewModel.FilesAndFolders[index];

                    if (clickedOnItem.FileExtension == "Folder")
                    {
                        ItemViewModel.TextState.isVisible = Windows.UI.Xaml.Visibility.Collapsed;
                        History.ForwardList.Clear();
                        ItemViewModel.FS.isEnabled = false;
                        ItemViewModel.FilesAndFolders.Clear();
                        if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory))
                        {
                            GenericFileBrowser.P.path = "Desktop";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "DesktopIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.DesktopPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Desktop";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
                        {
                            GenericFileBrowser.P.path = "Documents";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "DocumentsIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.DocumentsPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Documents";
                        }
                        else if (clickedOnItem.FilePath == (Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads"))
                        {
                            GenericFileBrowser.P.path = "Downloads";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "DownloadsIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.DownloadsPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Downloads";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyPictures))
                        {
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "PicturesIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(PhotoAlbum), YourHome.PicturesPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Pictures";
                            GenericFileBrowser.P.path = "Pictures";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyMusic))
                        {
                            GenericFileBrowser.P.path = "Music";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "MusicIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.MusicPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Music";
                        }
                        else if (clickedOnItem.FilePath == (Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\OneDrive"))
                        {
                            GenericFileBrowser.P.path = "OneDrive";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "OneD_IC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.OneDrivePath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search OneDrive";
                        }
                        else if (clickedOnItem.FilePath == Environment.GetFolderPath(Environment.SpecialFolder.MyVideos))
                        {
                            GenericFileBrowser.P.path = "Videos";
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "VideosIC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            MainPage.accessibleContentFrame.Navigate(typeof(GenericFileBrowser), YourHome.VideosPath, new SuppressNavigationTransitionInfo());
                            MainPage.accessibleAutoSuggestBox.PlaceholderText = "Search Videos";
                        }
                        else
                        {
                            GenericFileBrowser.P.path = clickedOnItem.FilePath;
                            foreach (Microsoft.UI.Xaml.Controls.NavigationViewItemBase NavItemChoice in MainPage.nv.MenuItems)
                            {
                                if (NavItemChoice is Microsoft.UI.Xaml.Controls.NavigationViewItem && NavItemChoice.Name.ToString() == "LocD_IC")
                                {
                                    MainPage.Select.itemSelected = NavItemChoice;
                                    break;
                                }
                            }
                            ItemViewModel.ViewModel = new ItemViewModel(clickedOnItem.FilePath, PhotoAlbum.PAPageName);
                        }
                    }
                    else if (clickedOnItem.FileExtension == "Executable")
                    {
                        Interaction.message       = new MessageDialog("We noticed you’re trying to run an executable file. This type of file may be a security risk to your device, and is not supported by the Universal Windows Platform. If you're not sure what this means, check out the Microsoft Store for a large selection of secure apps, games, and more.");
                        Interaction.message.Title = "Unsupported Functionality";
                        Interaction.message.Commands.Add(new UICommand("Continue...", new UICommandInvokedHandler(Interaction.CommandInvokedHandler)));
                        Interaction.message.Commands.Add(new UICommand("Cancel"));
                        await Interaction.message.ShowAsync();
                    }
                    else
                    {
                        StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.FilePath);

                        var options = new LauncherOptions
                        {
                            DisplayApplicationPicker = true
                        };
                        await Launcher.LaunchFileAsync(file, options);
                    }
                }
            }
        }
Esempio n. 57
0
 private void LevelBrowserDialog_Validating(object sender, System.ComponentModel.CancelEventArgs e)
 {
     MessageDialog.Show(ProjectBrowser.GetSelection());
 }
 private static async Task ShowMessage(string message)
 {
     var msgbox = new MessageDialog(message);
     await msgbox.ShowAsync();
 }
Esempio n. 59
0
 public async Task ComposeEmail(string to, string subject, string body = "")
 {
     var dialog = new MessageDialog(subject);
     await dialog.ShowAsync();
 }
Esempio n. 60
-1
 public async void Execute(object parameter)
 {
     var result = Task.FromResult(default(IUICommand));
     owner.DownloadVisible = false;
     owner.ProgressVisible = true;
     var folder = await downloader.VerifyFolderCreation();
     using (var client = new System.Net.Http.HttpClient())
     {
         // find all selected episodes.
         List<Task> results = new List<Task>();
         foreach (var episode in owner.selectedEpisodes)
         {
             var path = episode.Description;
             var writeTask = downloader.SaveUrlAsync(folder, client, path);
             results.Add(writeTask);
         }
         var allTasks = Task.WhenAll(results.ToArray());
         owner.ActiveDownload = allTasks;
         try
         {
             await allTasks;
         }
         catch (Exception)
         {
             // Umm, some download failed.
             var errMsg = new MessageDialog("One or more downloads failed");
             result = errMsg.ShowAsync().AsTask();
         }
         await result;
     }
     owner.DownloadVisible = true;
     owner.ProgressVisible = false;
     owner.selectedEpisodes.Clear();
 }