Esempio n. 1
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;
    }
 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();
 }
Esempio n. 3
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. 4
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. 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
    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. 7
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;
    }
    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. 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
    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. 11
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. 12
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. 13
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. 14
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. 15
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. 16
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 ();
 }
Esempio n. 17
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. 18
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. 19
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();
    }
Esempio n. 20
0
 protected void FinishedAlert()
 {
     var md = new MessageDialog (this,
                                DialogFlags.DestroyWithParent,
                                MessageType.Info,
                                ButtonsType.Ok,
                                "Scraping finished!");
     md.Run ();
     md.Destroy ();
 }
Esempio n. 21
0
 protected void ErrorAlert(string message)
 {
     var md = new MessageDialog (this,
                                DialogFlags.DestroyWithParent,
                                MessageType.Warning,
                                ButtonsType.Ok,
                                message);
     md.Run ();
     md.Destroy ();
 }
Esempio n. 22
0
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();
        mySqlConnection.Open();
        MySqlCommand mySqlCommand=mySqlConnection.CreateCommand();
        mySqlCommand.CommandText= "select * from categoria";
        MySqlDataReader mysqlDataReader= mySqlCommand.ExecuteReader();
        int fieldcount=mysqlDataReader.FieldCount;

        creaColumnas(fieldcount,mysqlDataReader);
        ListStore listStore=new ListStore(creaTipos(fieldcount));
        rellenar(fieldcount,listStore,mysqlDataReader);
        mysqlDataReader.Close();

        removeAction.Sensitive=false;
        treeView.Model=listStore;
        TreeIter iter;

        treeView.Selection.Changed+=delegate{
            bool isSelected=treeView.Selection.GetSelected(out iter);
            if(isSelected)
                removeAction.Sensitive=true;
            else
                removeAction.Sensitive=false;
        };

        removeAction.Activated +=delegate{
            string nombre=listStore.GetValue(iter,1).ToString();
            MessageDialog md2 = new MessageDialog
                        (this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo,"¿Seguro que quieres borrarlo? \n Borrar: "+nombre);

            ResponseType result = (ResponseType)md2.Run ();
            string op=listStore.GetValue(iter,0).ToString();

            if (result == ResponseType.Yes){
                MySqlCommand delete=mySqlConnection.CreateCommand();
                delete.CommandText= "Delete from categoria where id="+op+"";
                delete.ExecuteNonQuery();
                md2.Destroy();

                for (int i=0;i<fieldcount;i++){//elimina columnas
                    treeView.RemoveColumn(treeView.GetColumn(0));
                }
                listStore.Clear();//vacia el modelo
                //volvemos a mostrar treview actualizado
                actualizar(mySqlCommand,listStore);

            }
            else{
                md2.Destroy();

            }
        };
    }
Esempio n. 23
0
 public static void ShowMessage(String messageString)
 {
     Window parentWindow = new Window ("提示");
             MessageDialog messageDialog = new MessageDialog (parentWindow,
                                                            DialogFlags.Modal,
                                                            MessageType.Info,
                                                            ButtonsType.Close, messageString);
             messageDialog.Run ();
             messageDialog.Destroy ();
             parentWindow.Dispose ();
 }
 protected virtual void MesAlterado(object sender, System.EventArgs e)
 {
     var mes = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName (this.calendar1.Date.Month);
     var md = new MessageDialog (null,
                                       DialogFlags.Modal,
                                       MessageType.Info,
                                       ButtonsType.Ok,
                                       mes);
         md.Run ();
         md.Destroy();
 }
Esempio n. 25
0
 private void DisplayError(String errorMessage)
 {
     MessageDialog errorDialog = new MessageDialog(
         this,
         DialogFlags.DestroyWithParent,
         MessageType.Error,
         ButtonsType.Ok,
         errorMessage
     );
     errorDialog.Run();
     errorDialog.Destroy();
 }
Esempio n. 26
0
    protected void OnButton17Clicked(object sender, System.EventArgs e)
    {
        dlgDatabaseConfiguration d = new dlgDatabaseConfiguration();

        d.Response += delegate {
            MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Close, "Test succeeded");
            md.Run();
            md.Destroy();
        };
        d.Run();
        d.Destroy();
    }
Esempio n. 27
0
 // dialogo confirmar eliminar (recibe ventana)
 public static bool ConfirmDelete(Window window)
 {
     MessageDialog messageDialog = new MessageDialog (
         window,
         DialogFlags.DestroyWithParent,
         MessageType.Question,
         ButtonsType.YesNo,
         "¿Quieres eliminar el elemento seleccionado?"
     );
     messageDialog.Title = window.Title;
     ResponseType response = (ResponseType)messageDialog.Run();
     messageDialog.Destroy();
     return response == ResponseType.Yes;
 }
Esempio n. 28
0
	// Muestra un modal de confirmacion y devuelve true si la respuesta del usuario es yes o false si ha sido otra
	public bool confirm(String text){
		MessageDialog messageDialog = new MessageDialog(
			this,
			DialogFlags.Modal,
			MessageType.Question,
			ButtonsType.YesNo,
			text
			);		
		messageDialog.Title = "¿Estás seguro?";
		ResponseType response = (ResponseType)messageDialog.Run ();
		messageDialog.Destroy ();

		return response == ResponseType.Yes; 
	}
 public MainWindow()
     : base(Gtk.WindowType.Toplevel)
 {
     Build ();
     setupui ();
     //Check for Launcher Updates
     if (MainClass.CheckForUpdates () == true) {
         MessageDialog md = new MessageDialog (this,
             DialogFlags.DestroyWithParent, MessageType.Info,
             ButtonsType.Close, "A new update has been released. We will install it for you. The launcher will close. When you run it again, you will be on the updated version." + Environment.NewLine + Environment.NewLine + "Version: " + MainClass.NewVersion + " '" + MainClass.NewCodename + "' ");
         md.Run ();
         md.Destroy ();
         MainClass.RunUpdate ();
     }
 }
Esempio n. 30
0
    protected virtual void OnAboutClicked(object sender, System.EventArgs e)
    {
        string aboutText = "ORU File Parser aka The Anders Program " +
            "v " + asm.GetName().Version.ToString() + Environment.NewLine +
                "(C) Anders Lindén 2008 - 2009. Licenced to Örebro University" + Environment.NewLine +
                "For questions and support, send a mail to: " +
                "*****@*****.**";

        MessageDialog md = new MessageDialog(this, DialogFlags.Modal,
                                             MessageType.Info, ButtonsType.Ok,
                                             aboutText);
        ResponseType res = (ResponseType)md.Run();
        if(res == ResponseType.Ok)
            md.Destroy();
    }
Esempio n. 31
0
        private void HandleInstallerDialog(FileChooserDialog fileChooser)
        {
            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                try
                {
                    string filename = fileChooser.Filename;

                    fileChooser.Dispose();

                    SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);

                    string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";

                    if (firmwareVersion == null)
                    {
                        GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");

                        return;
                    }

                    SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();

                    string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";

                    if (currentVersion != null)
                    {
                        dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
                    }

                    dialogMessage += "\n\nDo you want to continue?";

                    ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();

                    MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");

                    if (responseInstallDialog == ResponseType.Yes)
                    {
                        Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");

                        Thread thread = new Thread(() =>
                        {
                            Application.Invoke(delegate
                            {
                                waitingDialog.Run();
                            });

                            try
                            {
                                _contentManager.InstallFirmware(filename);

                                Application.Invoke(delegate
                                {
                                    waitingDialog.Dispose();

                                    string message = $"System version {firmwareVersion.VersionString} successfully installed.";

                                    GtkDialog.CreateInfoDialog(dialogTitle, message);
                                    Logger.Info?.Print(LogClass.Application, message);
                                });
                            }
                            catch (Exception ex)
                            {
                                Application.Invoke(delegate
                                {
                                    waitingDialog.Dispose();

                                    GtkDialog.CreateErrorDialog(ex.Message);
                                });
                            }
                            finally
                            {
                                RefreshFirmwareLabel();
                            }
                        });

                        thread.Name = "GUI.FirmwareInstallerThread";
                        thread.Start();
                    }
                }
                catch (Exception ex)
                {
                    GtkDialog.CreateErrorDialog(ex.Message);
                }
            }
            else
            {
                fileChooser.Dispose();
            }
        }
Esempio n. 32
0
        public override Widget CreateConfigWidget()
        {
            var container = new VBox();



            var fileHBox = new HBox();

            container.Add(fileHBox);


            // Sudoku index.
            var indexHBox = new HBox();

            fileHBox.Add(indexHBox);
            var indexLabel = new Label {
                Text = "Sudoku index"
            };

            indexHBox.Add(indexLabel);

            var indexButton = new SpinButton(1, _sudokuList.Count, 1)
            {
                Value = 1
            };

            indexButton.ValueChanged += delegate
            {
                _sudokuIndex = (int)indexButton.Value - 1;

                OnReconfigured();
            };
            indexHBox.Add(indexButton);

            // File support

            var selectImageButton = new Button {
                Label = "Load sudoku(s) file"
            };

            selectImageButton.Clicked += delegate
            {
                Gtk.FileChooserDialog filechooser =
                    new Gtk.FileChooserDialog(
                        "Select the sudoku to use",
                        Context.GtkWindow,
                        FileChooserAction.Open,
                        "Cancel",
                        ResponseType.Cancel,
                        "Open",
                        ResponseType.Accept);

                if (filechooser.Run() == (int)ResponseType.Accept)
                {
                    _sudokuList = SudokuBoard.ParseFile(filechooser.Filename);
                    indexButton.SetRange(1, _sudokuList.Count);
                }

                filechooser.Destroy();

                OnReconfigured();
            };
            fileHBox.Add(selectImageButton);
            var helpImageButton = new Button {
                Label = "?"
            };

            helpImageButton.Clicked += delegate
            {
                var msg = new MessageDialog(
                    Context.GtkWindow,
                    DialogFlags.Modal,
                    MessageType.Info,
                    ButtonsType.Ok,
                    "Accepted formats represent Sudokus on one or several lines," +
                    "\n with characters '.', '-', or 'X' for empty cells and digits otherwise." +
                    "\n Lines starting with other characters are ignored such as '#' for comments on the common sdk format.");
                msg.Run();

                msg.Destroy();
            };
            fileHBox.Add(helpImageButton);



            // Genetics selector.

            var geneticsHBox = new HBox();

            geneticsHBox.Spacing += 2;

            var geneticsLabel = new Label {
                Text = "Genetics"
            };

            geneticsHBox.Add(geneticsLabel);

            var chromosomeTypes = new string[] {
                nameof(SudokuChromosomeType.RowsPermutations)
                , nameof(SudokuChromosomeType.Cells)
                , nameof(SudokuChromosomeType.RandomRowsPermutations)
                , nameof(SudokuChromosomeType.RowsWithoutMask)
                , nameof(SudokuChromosomeType.CellsWithoutMask)
            };

            _nbPermsHBox = new HBox
            {
                Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations)
            };


            var nbPermsLabel = new Label {
                Text = "Nb Permutations"
            };

            _nbPermsHBox.Add(nbPermsLabel);

            var nbPermsButton = new SpinButton(1, 1000, 1);

            _nbPermsHBox.Add(nbPermsButton);
            nbPermsButton.Value         = _nbPermutations;
            nbPermsButton.ValueChanged += delegate
            {
                _nbPermutations = (int)nbPermsButton.Value;

                OnReconfigured();
            };

            var nbSudokusLabel = new Label {
                Text = "Nb Sudokus"
            };

            _nbPermsHBox.Add(nbSudokusLabel);

            var nbSudokusButton = new SpinButton(1, 1000, 1);

            _nbPermsHBox.Add(nbSudokusButton);
            nbSudokusButton.Value         = _nbSudokus;
            nbSudokusButton.ValueChanged += delegate
            {
                _nbSudokus = (int)nbSudokusButton.Value;

                OnReconfigured();
            };



            var selectorCombo = new ComboBox(chromosomeTypes)
            {
                Active = 0
            };

            selectorCombo.Changed += delegate
            {
                _ChromosomeType      = selectorCombo.ActiveText;
                _nbPermsHBox.Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations);
                OnReconfigured();
            };
            geneticsHBox.Add(selectorCombo);
            container.Add(geneticsHBox);
            container.Add(_nbPermsHBox);

            //Multi check
            var multiHBox  = new HBox();
            var multiCheck = new CheckButton("Multi-Solutions")
            {
                Active = _multipleChromosome
            };

            _nbChromosomesHBox          = new HBox();
            _nbChromosomesHBox.Spacing += 2;
            _nbChromosomesHBox.Visible  = _multipleChromosome;

            var nbChromosomesLabel = new Label {
                Text = "Nb Chrom."
            };

            _nbChromosomesHBox.Add(nbChromosomesLabel);

            var nbChromosomesButton = new SpinButton(1, 1000, 1);

            _nbChromosomesHBox.Add(nbChromosomesButton);
            nbChromosomesButton.Value         = _nbChromosomes;
            nbChromosomesButton.ValueChanged += delegate
            {
                _nbChromosomes = (int)nbChromosomesButton.Value;

                OnReconfigured();
            };

            multiCheck.Toggled += delegate
            {
                _multipleChromosome        = multiCheck.Active;
                _nbChromosomesHBox.Visible = _multipleChromosome;

                OnReconfigured();
            };

            multiHBox.Add(multiCheck);
            multiHBox.Add(_nbChromosomesHBox);

            container.Add(multiHBox);

            return(container);
        }
Esempio n. 33
0
    protected void OnButtonHitungClicked(object sender, EventArgs e)
    {
        bool isPermutation = radiobuttonP.Active;

        Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "OnButtonHitungClicked Event fired");

        //Check for user error
        if (!isPermutation && !radiobuttonC.Active)
        {
            ErrorDialog("Anda belum memilih operasi perhitungan.\nSilahkan pilih operasi Permutasi atau Kombinasi.");
            return;
        }

        int n, r;

        try
        {
            n = Convert.ToInt32(spinN.Text);
            r = Convert.ToInt32(spinR.Text);
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "Value of N: " + n);
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "Value of R: " + r);
        }
        catch (System.FormatException)
        {
            ErrorDialog("Hanya bisa memasukkan angka (berupa bilangan bulat).");
            return;
        }
        catch (Exception ex)
        {
            ErrorDialog("Terjadi kesalahan!\n" + ex);
            return;
        }

        if (r > n)
        {
            ErrorDialog("Nilai sub-set (r) tidak bisa lebih besar dari nilai set (n)");
            return;
        }

        if (r < 0 || n < 0)
        {
            ErrorDialog("Anda tidak bisa memasukkan bilangan negatif.");
            return;
        }

        buttonHitung.Sensitive = false;
        buttonHitung.Label     = "Menghitung hasil...";

        string result            = isPermutation ? CountPermutation(n, r).Result.ToString("R") : CountCombination(n, r).Result.ToString("R"); //preserve the whole BigInteger value
        string text              = "Hasil " + (isPermutation ? "permutasi:" : "kombinasi:") + "\n";
        string result_normalized = result;                                                                                                    //long numbers have enter to prevent message dialog width too wide
        bool   lihatRumus        = false;
        int    countLine         = 1;

        for (int i = 200; i < result.Length; i += 200)
        {
            if (countLine > 40)
            {
                result_normalized = result_normalized.Remove(i + 1) + "...\nHasil terlalu panjang. Tekan tombol Copy Hasil untuk mengcopy hasil utuhnya.";
                break;
            }
            result_normalized = result_normalized.Insert(i, "\n");
            countLine++;
        }
        text += result_normalized + "\n\n";

        MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.None, text);

        Button b0 = (Button)md.AddButton("Lihat Rumus", 0);
        Button b1 = (Button)md.AddButton("Copy Hasil", 1);
        Button b2 = (Button)md.AddButton("Tutup", 2);

        b0.Clicked     += ButtonDialogRumusClicked;
        b0.WidthRequest = 160;
        b1.Clicked     += ButtonDialogCopyClicked;
        b2.Clicked     += ButtonDialogTutupClicked;

        md.Run();
        buttonHitung.Label = "Hitung";
        Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "Result message dialog fired:\n" + text);

        void ButtonDialogRumusClicked(object senderr, EventArgs ee)
        {
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "ButtonDialogRumusClicked event fired");
            if (!lihatRumus)
            {
                text      += isPermutation ? "n! / (n-r)!" : "n! / (r! * (n-r)!)";
                md.Text    = text;
                lihatRumus = true;
                b0.Label   = "Sembunyikan Rumus";
            }
            else
            {
                text       = isPermutation ? text.Replace("n! / (n-r)!", "") : text.Replace("n! / (r! * (n-r)!)", "");
                md.Text    = text;
                lihatRumus = false;
                b0.Label   = "Lihat Rumus";
            }
        }

        void ButtonDialogCopyClicked(object senderr, EventArgs ee)
        {
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "ButtonDialogCopyClicked event fired");
            Clipboard clipboard = Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false));

            clipboard.Text = result;
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "Copied result to clipboard. Value: \n" + result);
        }

        void ButtonDialogTutupClicked(object senderr, EventArgs ee)
        {
            Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss.fff] ") + "ButtonDialogTutupClicked event fired");
            buttonHitung.Sensitive = true;
            md.Destroy();
        }
    }
    protected void OnStartStreamButtonClicked(object sender, EventArgs e)
    {
        bool vlcError = false;

        if (rtspTunnel != null && rtspTunnel.Running)
        {
            SpawnThread(delegate()
            {
                vlcWindow.Kill();
            });
            return;
        }
        else
        {
            SpawnThread(delegate()
            {
                int stepTimeOut             = 10000;
                bool hasError               = false;
                Gtk.ProgressBar progressBar = new Gtk.ProgressBar();
                progressBar.WidthRequest    = 170;
                Label label = new Label("Opening RTSP Connection");
                //label.HeightRequest = 10;
                Dialog dialog   = new Dialog("Starting video stream", this, Gtk.DialogFlags.DestroyWithParent);
                dialog.TypeHint = WindowTypeHint.Splashscreen;
                dialog.Modal    = true;
                dialog.VBox.Add(label);
                dialog.VBox.Add(progressBar);
                dialog.HasSeparator       = false;
                System.Timers.Timer timer = new System.Timers.Timer(100);
                timer.Elapsed            += delegate {
                    Gtk.Application.Invoke(delegate {
                        progressBar.Pulse();
                    });
                };
                Gtk.Application.Invoke(delegate {
                    dialog.ShowAll();
                });
                timer.Start();
                if (brickType == BrickType.NXT)
                {
                    rtspTunnel = new RtspTunnel(rtspPort, imagePort, brick.Connection);
                }
                else
                {
                    throw new NotImplementedException("What to do with EV3");
                }
                rtspTunnel.Start();
                string errorMessage = "";
                if (rtspTunnel.RTSPWaitHandle.WaitOne(stepTimeOut))
                {
                    Gtk.Application.Invoke(delegate {
                        label.Text = "Starting stream";
                    });
                    vlcWindow       = new Process();
                    string argument = "rtsp://127.0.0.1:" + rtspPort + " --network-caching=" + networkCachingCombobox.GetActiveValue();
                    Console.WriteLine(argument);
                    vlcWindow.StartInfo = new ProcessStartInfo(settings.Path,
                                                               argument);
                    try{
                        vlcError  = false;
                        vlcWindow = Process.Start(new ProcessStartInfo(settings.Path, argument));

                        /*if(vlcWindow.Start()){
                         *      vlcError = false;
                         * }*/
                    }
                    catch {
                        vlcError = true;
                    }
                    if (!vlcError)
                    {
                        Gtk.Application.Invoke(delegate {
                            label.Text = "Waiting for image stream";
                        });
                        if (rtspTunnel.StreamWaitHandle.WaitOne(stepTimeOut))
                        {
                            //Everything is ok
                            rtspTunnel.Stopped          += OnRTSPTunnelStopped;
                            rtspTunnel.NewImageDataRate += OnUpdateStreamRate;
                            OnRTSPTunnelStarted();
                        }
                        else
                        {
                            errorMessage = "Failed to receive image data";
                            hasError     = true;
                        }
                    }
                    else
                    {
                        errorMessage = "Failed to start vlc window";
                        hasError     = true;
                    }
                }
                else
                {
                    errorMessage = "Failed to start remote RTSP-server";
                    hasError     = true;
                }
                timer.Stop();
                Gtk.Application.Invoke(delegate {
                    dialog.Destroy();
                });
                if (hasError && !vlcError)
                {
                    if (rtspTunnel != null && rtspTunnel.Running)
                    {
                        rtspTunnel.Stop();
                    }
                    Gtk.Application.Invoke(delegate {
                        MessageDialog md  = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "\n" + errorMessage);
                        md.Icon           = global::Gdk.Pixbuf.LoadFromResource(MessageDialogIconName);
                        md.WindowPosition = Gtk.WindowPosition.CenterOnParent;
                        md.Run();
                        md.Destroy();
                    });
                }
                if (vlcError)
                {
                    rtspTunnel.Stop();
                    Gtk.Application.Invoke(delegate {
                        /*if(Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix){
                         *      //Mac OS and Linux
                         *      MessageDialog md = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok,
                         *                                            "\n" + "Failed to start VLC\n" +
                         *                                            "Make sure you have installed VLC");
                         *      md.Icon = global::Gdk.Pixbuf.LoadFromResource (MessageDialogIconName);
                         *      md.WindowPosition = Gtk.WindowPosition.CenterOnParent;
                         *      md.Run();
                         *      md.Destroy();
                         *
                         * }
                         * else{*/
                        //windows
                        MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.YesNo,
                                                             "\n" + "Failed to start VLC\n" +
                                                             "VLC executable path is currently set to:\n"
                                                             + settings.Path + "\n" +
                                                             "Do you want to change this");
                        md.Icon           = global::Gdk.Pixbuf.LoadFromResource(MessageDialogIconName);
                        md.WindowPosition = Gtk.WindowPosition.CenterOnParent;
                        if (md.Run() == (int)ResponseType.Yes)
                        {
                            md.Destroy();

                            Gtk.FileChooserDialog fc =
                                new Gtk.FileChooserDialog("Locate VLC executable",
                                                          this,
                                                          FileChooserAction.Open,
                                                          Gtk.Stock.Cancel, ResponseType.Cancel,
                                                          Gtk.Stock.Ok, ResponseType.Accept);
                            if (fc.Run() == (int)ResponseType.Accept)
                            {
                                settings.Path = fc.Filename;
                                settings.Save();
                            }
                            fc.Destroy();
                        }
                        else
                        {
                            md.Destroy();
                        }
                        //}
                    });
                }
            });
        }
    }
Esempio n. 35
0
        private bool SaveFile(Document document, string file, FormatDescriptor format, Window parent)
        {
            if (string.IsNullOrEmpty(file))
            {
                file = document.PathAndFileName;
            }

            if (format == null)
            {
                format = PintaCore.System.ImageFormats.GetFormatByFile(file);
            }

            if (format == null || format.IsReadOnly())
            {
                MessageDialog md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Catalog.GetString("Pinta does not support saving images in this file format."), file);
                md.Title = Catalog.GetString("Error");

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

            // If the user tries to save over a read only file, give a more informative error message than "Unhandled Exception"
            FileInfo file_info = new FileInfo(file);

            if (file_info.Exists && file_info.IsReadOnly)
            {
                MessageDialog md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error,
                                                     ButtonsType.Ok, Catalog.GetString("Cannot save read only file."));
                md.Title = Catalog.GetString("Error");

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

            // Commit any pending changes
            PintaCore.Tools.Commit();

            try {
                format.Exporter.Export(document, file, parent);
            } catch (GLib.GException e) {             // Errors from GDK
                if (e.Message == "Image too large to be saved as ICO")
                {
                    string primary   = Catalog.GetString("Image too large");
                    string secondary = Catalog.GetString("ICO files can not be larger than 255 x 255 pixels.");
                    string message   = string.Format(markup, primary, secondary);

                    MessageDialog md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error,
                                                         ButtonsType.Ok, message);

                    md.Run();
                    md.Destroy();
                    return(false);
                }
                else
                {
                    throw e;                     // Only catch exceptions we know the reason for
                }
            } catch (OperationCanceledException) {
                return(false);
            }

            document.Filename = Path.GetFileName(file);
            document.IsDirty  = false;

            PintaCore.Tools.CurrentTool.DoAfterSave();

            //Now the Document has been saved to the file it's associated with in this session.
            document.HasBeenSavedInSession = true;

            return(true);
        }
Esempio n. 36
0
        private void AddBtn_Clicked(object sender, EventArgs e)
        {
            Transaction t = new Transaction();

            t.id = Guid.NewGuid();
            t.exchangeSnapshot = Tools.ExchangeRateSnapshot();

            if (db.accounts[ac].transactions == null)
            {
                db.accounts[ac].transactions = new List <Transaction>();
            }

            if (tabControl.CurrentPage == 1)
            {
                t.amount = decimal.Parse(amountE.Text);
                t.desc   = descE.Text;

                TreeIter tree;
                payeeE.GetActiveIter(out tree);
                String selectedText = (String)payeeE.Model.GetValue(tree, 0);
                t.payee = selectedText;

                t.dateTime = transactionDateE;
                t.type     = TransactionType.Expense;

                currencyComboE.GetActiveIter(out tree);
                selectedText      = (String)currencyComboE.Model.GetValue(tree, 0);
                t.currencyISO4217 = selectedText;
            }
            else
            {
                t.amount = decimal.Parse(amountI.Text);
                t.desc   = descI.Text;

                TreeIter tree;
                payeeI.GetActiveIter(out tree);
                String selectedText = (String)payeeI.Model.GetValue(tree, 0);
                t.payee = selectedText;

                t.dateTime = transactionDateI;
                t.type     = TransactionType.Income;

                currencyComboI.GetActiveIter(out tree);
                selectedText      = (String)currencyComboI.Model.GetValue(tree, 0);
                t.currencyISO4217 = selectedText;
            }

            t.status = TransactionStatus.Scheduled;

            if (t.dateTime.Date == DateTime.Now.Date)
            {
                string        msg     = "Transaction date is today, do you want to execute this transaction now? Clicking `No` will set the status to: `OnHold`";
                MessageDialog msgdiag = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, false, msg);
                ResponseType  r       = (ResponseType)msgdiag.Run();
                msgdiag.Destroy();

                if (r == ResponseType.Yes)
                {
                    t.status = TransactionStatus.Completed;
                }
                else if (r == ResponseType.No)
                {
                    t.status = TransactionStatus.OnHold;
                }
                else
                {
                    return;
                }
            }

            if (t.payee.StartsWith("[Internal]"))
            {
                string payee = t.payee.Replace("[Internal]", "");

                Transaction flip = new Transaction();

                flip.id               = Guid.NewGuid();
                flip.amount           = t.amount * -1;
                flip.desc             = t.desc;
                flip.payee            = t.payee;
                flip.dateTime         = t.dateTime;
                flip.type             = t.type;
                flip.status           = t.status;
                flip.exchangeSnapshot = t.exchangeSnapshot;
                flip.currencyISO4217  = t.currencyISO4217;

                t.intern    = flip.id;
                flip.intern = t.id;

                if (db.accounts[db.AccountIdFromName(payee)].transactions == null)
                {
                    db.accounts[db.AccountIdFromName(payee)].transactions = new List <Transaction>();
                }

                db.accounts[db.AccountIdFromName(payee)].transactions.Add(flip);
            }

            db.accounts[ac].transactions.Add(t);
            db.Save(dbPath);
            this.Destroy();
        }
Esempio n. 37
0
    protected void BuildButtonClick(object sender, EventArgs e)
    {
        MessageDialog delegateddialog;

        if (string.IsNullOrWhiteSpace(GameConfig.OutputDirectoryPath))
        {
            Console.WriteLine("Please specify an output directory in the settings.");
            delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "Please specify an output directory in the settings.");
            delegateddialog.Run();
            delegateddialog.Destroy();
            //MessageBox.Show(this, "Please specify an output directory in the settings.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        if (Mods.Count == 0)
        {
            Console.WriteLine("No mods are available.");
            delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "No mods are available.");
            delegateddialog.Run();
            delegateddialog.Destroy();
            //MessageBox.Show(this, "No mods are available.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        if (!UpdateGameConfigEnabledMods())
        {
            Console.WriteLine("No mods are enabled.");
            delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "No mods are enabled.");
            delegateddialog.Run();
            delegateddialog.Destroy();
            // MessageBox.Show(this, "No mods are enabled.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }


        var task = Task.Factory.StartNew(() =>
        {
            var enabledMods = GameConfig.ModConfigs.Where(x => x.Enabled)
                              .OrderBy(x => x.Priority)
                              .Select(x => x.ModId)
                              .Select(x => ModDatabase.Get(x))
                              .ToList();

            Log.General.Info("Building mods:");
            foreach (var enabledMod in enabledMods)
            {
                Log.General.Info($"\t{enabledMod.Title}");
            }

            // Run prebuild scripts
            RunModScripts(enabledMods, "prebuild.bat");

            var merger = new TopToBottomModMerger();
            var merged = merger.Merge(enabledMods);

            // Todo
            var builder = ModBuilderManager.GetCompatibleModBuilders(SelectedGame).First().Create();
            if (UltraISOUtility.Available)
            {
                if (SelectedGame == Game.Persona3)
                {
                    builder = new Persona3IsoModBuilder();
                }
                else if (SelectedGame == Game.Persona4)
                {
                    builder = new Persona4IsoModBuilder();
                }
            }

            Log.General.Info($"Output path: {GameConfig.OutputDirectoryPath}");

#if !DEBUG
            try
#endif
            {
                builder.Build(merged, GameConfig.OutputDirectoryPath);
            }
#if !DEBUG
            catch (InvalidConfigException exception)
            {
                Gtk.Application.Invoke(delegate
                {
                    delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, $"SelectedGame configuration is invalid.\n{exception.Message}");
                    delegateddialog.Run();
                    delegateddialog.Destroy();
                });
                return(false);
            }
            catch (MissingFileException exception)
            {
                Gtk.Application.Invoke(delegate
                {
                    delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, $"A file is missing:\n{exception.Message}");
                    delegateddialog.Run();
                    delegateddialog.Destroy();
                });


                return(false);
            }
            catch (Exception exception)
            {
                Gtk.Application.Invoke(delegate
                {
                    delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, $"Unhandled exception occured while building:\n{exception.Message}\n{exception.StackTrace}");
                    delegateddialog.Run();
                    delegateddialog.Destroy();
                });


#if DEBUG
                throw;
#endif

#pragma warning disable 162
                return(false);

#pragma warning restore 162
            }
#endif

            return(true);
        }, TaskCreationOptions.AttachedToParent);

        task.ContinueWith((t) =>
        {
            if (t.Result)
            {
                Gtk.Application.Invoke(delegate {
                    delegateddialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Done building!");
                    delegateddialog.Run();
                    delegateddialog.Destroy();
                });

                RunPostBuildScript("postbuild.bat");
            }
        });
    }
Esempio n. 38
0
        private async void btnSend_Click(Object sender, EventArgs e)
        {
            var str = txtSend.Buffer.Text;

            if (String.IsNullOrEmpty(str))
            {
                var md = new MessageDialog(this.TooltipWindow,
                                           DialogFlags.DestroyWithParent, MessageType.Warning,
                                           ButtonsType.Close, "发送内容不能为空!");
                md.Run();
                md.Dispose();
                // MessageBox.Show("发送内容不能为空!", Text);
                // txtSend.Focus();
                return;
            }

            // 多次发送
            var count = (Int32)numMutilSend.Value;
            var sleep = (Int32)numSleep.Value;
            var ths   = (Int32)numThreads.Value;

            if (count <= 0)
            {
                count = 1;
            }
            if (sleep <= 0)
            {
                sleep = 1;
            }

            SaveConfig();

            var uri = new NetUri(cbAddr.ActiveText);
            var cfg = ApiConfig.Current;

            // 处理换行
            str = str.Replace("\n", "\r\n");

            var act    = cbAction.ActiveText;
            var action = act.Substring(" ", "(");

            if (action.IsNullOrEmpty())
            {
                return;
            }

            var rtype = act.Substring(null, " ").GetTypeEx();

            if (rtype == null)
            {
                rtype = typeof(Object);
            }
            var ps = act.Substring("(", ")").Split(",");

            // 构造消息,二进制优先
            Object args = null;

            if (ps.Length == 1 && ps[0].StartsWith("Packet "))
            {
                args = new Packet(str.GetBytes());
            }
            else
            {
                var dic = new JsonParser(str).Decode() as IDictionary <String, Object>;
                if (dic == null || dic.Count == 0)
                {
                    dic = null;
                }
                args = dic;
            }

            if (_Client == null)
            {
                return;
            }

            _Invoke    = 0;
            _Cost      = 0;
            _TotalCost = 0;

            //var ct = _Client.Client;
            var list = new List <ApiClient> {
                _Client
            };

            for (var i = 0; i < ths - 1; i++)
            {
                var client = new ApiClient(uri + "");
                //var ct2 = client.Client;
                //ct2.Log = ct.Log;
                //ct2.LogSend = ct.LogSend;
                //ct2.LogReceive = ct.LogReceive;
                //ct2.StatSend = ct.StatSend;
                //ct2.StatReceive = ct.StatReceive;

                client.StatSend    = _Client.StatSend;
                client.StatReceive = _Client.StatReceive;

                list.Add(client);
            }
            //Parallel.ForEach(list, k => OnSend(k, act, args, count));
            var sw = Stopwatch.StartNew();
            var ts = list.Select(k => OnSend(k, rtype, action, args, count, sleep)).ToList();

            await TaskEx.WhenAll(ts);

            sw.Stop();
            _TotalCost = sw.Elapsed.TotalMilliseconds;
        }
Esempio n. 39
0
        internal void LoadApplication(string path)
        {
            if (_gameLoaded)
            {
                GtkDialog.CreateInfoDialog("Ryujinx", "A game has already been loaded", "Please close it first and try again.");
            }
            else
            {
                if (ConfigurationState.Instance.Logger.EnableDebug.Value)
                {
                    MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
                    {
                        Title         = "Ryujinx - Warning",
                        Text          = "You have debug logging enabled, which is designed to be used by developers only.",
                        SecondaryText = "For optimal performance, it's recommended to disable debug logging. Would you like to disable debug logging now?"
                    };

                    if (debugWarningDialog.Run() == (int)ResponseType.Yes)
                    {
                        ConfigurationState.Instance.Logger.EnableDebug.Value = false;
                        SaveConfig();
                    }

                    debugWarningDialog.Dispose();
                }

                if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
                {
                    MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
                    {
                        Title         = "Ryujinx - Warning",
                        Text          = "You have shader dumping enabled, which is designed to be used by developers only.",
                        SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
                    };

                    if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
                    {
                        ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
                        SaveConfig();
                    }

                    shadersDumpWarningDialog.Dispose();
                }

                Logger.RestartTime();

                HLE.Switch device = InitializeSwitchInstance();

                // TODO: Move this somewhere else + reloadable?
                Graphics.Gpu.GraphicsConfig.MaxAnisotropy   = ConfigurationState.Instance.Graphics.MaxAnisotropy;
                Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;

                Logger.PrintInfo(LogClass.Application, $"Using Firmware Version: {_contentManager.GetCurrentFirmwareVersion()?.VersionString}");

                if (Directory.Exists(path))
                {
                    string[] romFsFiles = Directory.GetFiles(path, "*.istorage");

                    if (romFsFiles.Length == 0)
                    {
                        romFsFiles = Directory.GetFiles(path, "*.romfs");
                    }

                    if (romFsFiles.Length > 0)
                    {
                        Logger.PrintInfo(LogClass.Application, "Loading as cart with RomFS.");
                        device.LoadCart(path, romFsFiles[0]);
                    }
                    else
                    {
                        Logger.PrintInfo(LogClass.Application, "Loading as cart WITHOUT RomFS.");
                        device.LoadCart(path);
                    }
                }
                else if (File.Exists(path))
                {
                    switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
                    {
                    case ".xci":
                        Logger.PrintInfo(LogClass.Application, "Loading as XCI.");
                        device.LoadXci(path);
                        break;

                    case ".nca":
                        Logger.PrintInfo(LogClass.Application, "Loading as NCA.");
                        device.LoadNca(path);
                        break;

                    case ".nsp":
                    case ".pfs0":
                        Logger.PrintInfo(LogClass.Application, "Loading as NSP.");
                        device.LoadNsp(path);
                        break;

                    default:
                        Logger.PrintInfo(LogClass.Application, "Loading as homebrew.");
                        try
                        {
                            device.LoadProgram(path);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            Logger.PrintError(LogClass.Application, "The file which you have specified is unsupported by Ryujinx.");
                        }
                        break;
                    }
                }
                else
                {
                    Logger.PrintWarning(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
                    device.Dispose();

                    return;
                }

                _emulationContext = device;

                _deviceExitStatus.Reset();

#if MACOS_BUILD
                CreateGameWindow(device);
#else
                Thread windowThread = new Thread(() =>
                {
                    CreateGameWindow(device);
                })
                {
                    Name = "GUI.WindowThread"
                };

                windowThread.Start();
#endif

                _gameLoaded = true;
                _stopEmulation.Sensitive = true;

                _firmwareInstallFile.Sensitive      = false;
                _firmwareInstallDirectory.Sensitive = false;

                DiscordIntegrationModule.SwitchToPlayingState(device.System.TitleIdText, device.System.TitleName);

                ApplicationLibrary.LoadAndSaveMetaData(device.System.TitleIdText, appMetadata =>
                {
                    appMetadata.LastPlayed = DateTime.UtcNow.ToString();
                });
            }
        }
        protected override void Run()
        {
            DotNetProject project = IdeApp.ProjectOperations.CurrentSelectedProject as DotNetProject;

            if (project == null)
            {
                return;
            }
            INativeTypesHandler nativeTypesHandler = null;

            //SupportedLanguage names currently returns an empty item and the 'languageName' the DotNetProject
            //is initialized with. This might be an array to enable extension for other projects? DotNetProject
            //only returns an empty and languageName. See source link.
            // https://github.com/mono/monodevelop/blob/dcafac668cbe8f63b4e42ea7f8f032f13aba8221/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProject.cs#L198
            if (project.SupportedLanguages.Contains("C#"))
            {
                nativeTypesHandler = NativeTypeHandlers.CSharpNativeTypesHandler;
            }

            if (project.SupportedLanguages.Contains("F#"))
            {
                nativeTypesHandler = NativeTypeHandlers.FSharpNativeTypesHandler;
            }

            if (project.SupportedLanguages.Contains("VBNet"))
            {
                nativeTypesHandler = NativeTypeHandlers.VbNetNativeTypesHandler;
            }

            if (nativeTypesHandler == null)
            {
                throw new ArgumentNullException("No supported languages found");
            }

            string fileName = "ServiceReference";

            int  count  = 0;
            bool exists = true;

            while (exists)
            {
                count++;
                var existingFile = project.Files.FirstOrDefault(x => x.FilePath.FileName == fileName + count.ToString() + nativeTypesHandler.CodeFileExtension);
                exists = existingFile != null;
            }

            var dialog = new AddReferenceDialog(fileName + count.ToString(), nativeTypesHandler);

            dialog.Run();
            string finalFileName = dialog.ReferenceName + nativeTypesHandler.CodeFileExtension;
            string code          = dialog.CodeTemplate;

            dialog.Destroy();
            if (!dialog.AddReferenceSucceeded)
            {
                return;
            }
            IdeApp.Workbench.StatusBar.ShowReady();
            IdeApp.Workbench.StatusBar.ShowMessage("Adding ServiceStack Reference...");
            IdeApp.Workbench.StatusBar.Pulse();
            string fullPath = Path.Combine(project.BaseDirectory.FullPath.ToString(), finalFileName);

            using (var streamWriter = File.CreateText(fullPath)) {
                streamWriter.Write(code);
                streamWriter.Flush();
            }

            project.AddFile(fullPath, BuildAction.Compile);

            try {
                Task.Run(() => {
                    AddNuGetPackageReference(project, "ServiceStack.Client");
                    AddNuGetPackageReference(project, "ServiceStack.Interfaces");
                    AddNuGetPackageReference(project, "ServiceStack.Text");
                }).ContinueWith(task => {
                    IdeApp.Workbench.StatusBar.ShowReady();
                    IdeApp.Workbench.StatusBar.Pulse();
                }, TaskScheduler.FromCurrentSynchronizationContext());
            } catch (Exception ex) {
                //TODO Error message for user
                var messageDialog = new MessageDialog(
                    (Gtk.Window)IdeApp.Workbench.RootWindow.Toplevel,
                    DialogFlags.Modal,
                    MessageType.Warning,
                    ButtonsType.Close,
                    "An error occurred trying to add required NuGet packages. Error : " + ex.Message +
                    "\r\n\r\nGenerated service reference will require ServiceStack.Interfaces as a minimum.");
                messageDialog.Run();
                messageDialog.Destroy();
                IdeApp.Workbench.StatusBar.ShowReady();
                IdeApp.Workbench.StatusBar.Pulse();
            }
        }
Esempio n. 41
0
        void ejecutar_consulta_reporte(PrintContext context)
        {
            Cairo.Context cr     = context.CairoContext;
            Pango.Layout  layout = context.CreatePangoLayout();

            char[]   delimiterChars = { '\n' };         // delimitador de Cadenas
            string[] words;
            string   textnote = "";

            NpgsqlConnection conexion;

            conexion = new NpgsqlConnection(connectionString + nombrebd);
            // Verifica que la base de datos este conectada
            try{
                conexion.Open();
                NpgsqlCommand comando;
                comando = conexion.CreateCommand();

                // asigna el numero de folio de ingreso de paciente (FOLIO)
                comando.CommandText = query_notas;
                //Console.WriteLine(comando.CommandText);
                NpgsqlDataReader lector = comando.ExecuteReader();
                if (lector.Read())
                {
                    PidPaciente       = (string)lector["pid_paciente"].ToString().Trim();
                    nombrecompletopac = (string)lector["nombre1_paciente"].ToString().Trim() + " " + (string)lector["nombre2_paciente"].ToString().Trim() + " " +
                                        (string)lector["apellido_paterno_paciente"].ToString().Trim() + " " + (string)lector["apellido_materno_paciente"].ToString().Trim();
                    fechnacimintopac = (string)lector["fechanacimiento_pac"].ToString().Trim();
                    edadpac          = (string)lector["edad"].ToString().Trim();
                    fechingreso      = (string)lector["fechadeingreso"].ToString().Trim();

                    if ((string)lector["fechadeegreso"].ToString().Trim() == "02-01-2000 00:00")
                    {
                        fechegreso = "";
                    }
                    else
                    {
                        fechegreso = (string)lector["fechadeegreso"].ToString().Trim();
                    }
                    if ((string)lector["sexo_paciente"].ToString().Trim() == "H")
                    {
                        sexopaciente = "MASCULINO";
                    }
                    else
                    {
                        sexopaciente = "FEMENINO";
                    }
                    alergiaconocida   = (string)lector["alegias_paciente"].ToString().Trim();
                    descripcioncuarto = (string)lector["descripcion_cuarto"].ToString().Trim() + "/" + (string)lector["numero_cuarto"].ToString().Trim();
                    if (titulo_rpt == "NOTAS_DE_ENFERMERIA")
                    {
                        nombreempleadoreponsable = (string)lector["nombreempleado"].ToString().Trim();
                    }
                    else
                    {
                        nombreempleadoreponsable = "";
                    }
                    imprime_encabezado(cr, layout);
                    fontSize  = 7.0;                 layout = null;                  layout = context.CreatePangoLayout();
                    desc.Size = (int)(fontSize * pangoScale);               layout.FontDescription = desc;
                    layout.FontDescription.Weight = Weight.Normal;                              // Letra normal
                    if ((string)lector[name_field].ToString() != "")
                    {
                        layout.FontDescription.Weight = Weight.Bold;                                    // Letra negrita
                        cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText("Fecha de Nota: " + (string)lector["fechaanotacion"].ToString().Trim() + "      " + "Hora de Nota : " + (string)lector["horaanotacion"].ToString().Trim() + "     Nº de NOTA :" + (string)lector["id_secuencia"].ToString().Trim());      Pango.CairoHelper.ShowLayout(cr, layout);
                        layout.FontDescription.Weight = Weight.Normal;                                  // Letra normal
                        comienzo_linea += separacion_linea;
                        salto_de_pagina(cr, layout);
                        comienzo_linea += separacion_linea;
                        salto_de_pagina(cr, layout);
                        textnote = (string)lector[name_field].ToString().ToUpper();
                        words    = textnote.Split(delimiterChars);                       // Separa las Cadenas
                        // Recorre la variable
                        foreach (string s in words)
                        {
                            if (s.Length > 0 && s.Length <= 120)
                            {
                                cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText(s.ToString());   Pango.CairoHelper.ShowLayout(cr, layout);
                                comienzo_linea += separacion_linea;
                                salto_de_pagina(cr, layout);
                            }
                            else
                            {
                                int inicio_string_linea   = 0;
                                int total_string_x_lineas = 130;
                                for (int i = 1; i <= s.Length / total_string_x_lineas; i++)
                                {
                                    cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText(s.ToString().Substring(inicio_string_linea, total_string_x_lineas));     Pango.CairoHelper.ShowLayout(cr, layout);
                                    comienzo_linea += separacion_linea;
                                    salto_de_pagina(cr, layout);
                                    inicio_string_linea += total_string_x_lineas;
                                }
                                if (s.Length > (s.Length / total_string_x_lineas) * total_string_x_lineas)
                                {
                                    Console.WriteLine(s.Length.ToString());
                                    Console.WriteLine(inicio_string_linea);
                                    cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText(s.ToString().Substring(inicio_string_linea, (s.Length - inicio_string_linea)));    Pango.CairoHelper.ShowLayout(cr, layout);
                                    comienzo_linea += separacion_linea;
                                    salto_de_pagina(cr, layout);
                                }
                            }
                        }
                        comienzo_linea += separacion_linea;
                        salto_de_pagina(cr, layout);
                        comienzo_linea += separacion_linea;
                        salto_de_pagina(cr, layout);
                        cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText("Nombre :" + nombreempleadoreponsable);    Pango.CairoHelper.ShowLayout(cr, layout);
                        comienzo_linea += separacion_linea;
                        salto_de_pagina(cr, layout);
                        cr.MoveTo(565 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);
                        cr.LineTo(05, comienzo_linea);             // Linea Horizontal 1
                        cr.FillExtents();                          //. FillPreserve();
                        cr.SetSourceRGB(0, 0, 0);
                        cr.LineWidth = 0.3;
                        cr.Stroke();
                    }
                    while (lector.Read())
                    {
                        if (titulo_rpt == "NOTAS_DE_ENFERMERIA")
                        {
                            nombreempleadoreponsable = (string)lector["nombreempleado"].ToString().Trim();
                        }
                        else
                        {
                            nombreempleadoreponsable = "";
                        }
                        if ((string)lector[name_field].ToString() != "")
                        {
                            layout.FontDescription.Weight = Weight.Bold;                                        // Letra negrita
                            cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText("Fecha de Nota: " + (string)lector["fechaanotacion"].ToString().Trim() + "      " + "Hora de Nota : " + (string)lector["horaanotacion"].ToString().Trim() + "     Nº de NOTA :" + (string)lector["id_secuencia"].ToString().Trim());      Pango.CairoHelper.ShowLayout(cr, layout);
                            layout.FontDescription.Weight = Weight.Normal;                                      // Letra normal
                            comienzo_linea += separacion_linea;
                            salto_de_pagina(cr, layout);
                            comienzo_linea += separacion_linea;
                            salto_de_pagina(cr, layout);
                            textnote = (string)lector[name_field].ToString().ToUpper();
                            words    = textnote.Split(delimiterChars);                           // Separa las Cadenas
                            // Recorre la variable
                            foreach (string s in words)
                            {
                                if (s.Length > 0 && s.Length <= 120)
                                {
                                    cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText(s.ToString());   Pango.CairoHelper.ShowLayout(cr, layout);
                                    comienzo_linea += separacion_linea;
                                    salto_de_pagina(cr, layout);
                                }
                                else
                                {
                                    int inicio_string_linea   = 0;
                                    int total_string_x_lineas = 130;
                                    for (int i = 1; i <= s.Length / total_string_x_lineas; i++)
                                    {
                                        cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText(s.ToString().Substring(inicio_string_linea, total_string_x_lineas));     Pango.CairoHelper.ShowLayout(cr, layout);
                                        comienzo_linea += separacion_linea;
                                        salto_de_pagina(cr, layout);
                                        inicio_string_linea += total_string_x_lineas;
                                    }
                                    if (s.Length > (s.Length / total_string_x_lineas) * total_string_x_lineas)
                                    {
                                        Console.WriteLine(s.Length.ToString());
                                        Console.WriteLine(inicio_string_linea);
                                        cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText(s.ToString().Substring(inicio_string_linea, (s.Length - inicio_string_linea)));    Pango.CairoHelper.ShowLayout(cr, layout);
                                        comienzo_linea += separacion_linea;
                                        salto_de_pagina(cr, layout);
                                    }
                                }
                            }
                            comienzo_linea += separacion_linea;
                            salto_de_pagina(cr, layout);
                            comienzo_linea += separacion_linea;
                            salto_de_pagina(cr, layout);
                            cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);  layout.SetText("Nombre :" + nombreempleadoreponsable);    Pango.CairoHelper.ShowLayout(cr, layout);
                            comienzo_linea += separacion_linea;
                            salto_de_pagina(cr, layout);
                            cr.MoveTo(565 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);
                            cr.LineTo(05, comienzo_linea);                 // Linea Horizontal 1
                            cr.FillExtents();                              //. FillPreserve();
                            cr.SetSourceRGB(0, 0, 0);
                            cr.LineWidth = 0.3;
                            cr.Stroke();
                        }
                    }
                }
            }catch (NpgsqlException ex) {
                MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.Modal,
                                                              MessageType.Error,
                                                              ButtonsType.Close, "PostgresSQL error: {0}", ex.Message);
                msgBoxError.Run();                             msgBoxError.Destroy();
            }
            conexion.Close();
        }
Esempio n. 42
0
        private void on_DeletePhonebookButton_clicked(object o, EventArgs args)
        {
            if (myPhoneBooks.Length > 0)
            {
                string[] list = new string[myPhoneBooks.Length];

                if (myPhoneBooks != null)
                {
                    // populate the list
                    int i = 0;
                    foreach (Phonebook pb in myPhoneBooks)
                    {
                        list[i++] = pb.Name;
                    }
                }
                string book = list[PhonebookComboBox.Active];

                MessageDialog md = new MessageDialog(
                    null,
                    DialogFlags.DestroyWithParent,
                    MessageType.Question,
                    ButtonsType.YesNo,
                    Catalog.GetString("Are you sure you want to delete the phone book?")
                    );

                ResponseType result = (ResponseType)md.Run();

                if (result == ResponseType.Yes)
                {
                    md.Destroy();

                    if (book == null)
                    {
                        return;
                    }
                    Phonetools.delete_book(book);

                    PhonebookComboBox.RemoveText(PhonebookComboBox.Active);
                    ItemStore.Clear();

                    myPhoneBooks = Phonetools.get_phonebooks();

                    if (myPhoneBooks.Length > 0)
                    {
                        // now reload
                        PhonebookComboBox.Active = 0;
                        on_PhonebookComboBox_changed(null, null);
                    }
                    else
                    {
                        DeletePhonebookButton.Sensitive = false;
                        PhonebookComboBox.InsertText(0, " ");
                    }
                    PhonebookComboBox.Active = 0;
                }
                else
                {
                    md.Destroy();
                }
            }
        }
Esempio n. 43
0
        private void DeleteCategory_Clicked(object sender, EventArgs e)
        {
            var selection = _categoryTreeView.Selection;

            if (!selection.GetSelected(out var model, out var iter))
            {
                return;
            }

            var item = model.GetValue(iter, 0);

            // ensure category isn't null before continuing.
            if (!(item is Category category))
            {
                return;
            }
            if (new Guid(category.Id) == Guid.Empty)
            {
                return;
            }

            var del = 0;

            // check through TaskItem list if there are any tasks which fall under the category
            _taskStore.Foreach(delegate(ITreeModel taskModel, TreePath path, TreeIter taskIter)
            {
                var taskItem = (Activity)taskModel.GetValue(taskIter, 0);
#if DEBUG
                Console.WriteLine(taskItem.Category);
                Console.WriteLine(category.Id);
#endif
                // Check Category id is matching an id used by a task item.
                if (taskItem.Category == category.Id)
                {
                    ++del;
                }
                return(false);
            });

            // if there any tasks which meet the above criteria, stop user from deleting it
            if (del > 0)
            {
                using (var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error,
                                                  ButtonsType.Close,
                                                  $"Cannot delete category '{category.CategoryName}'.\nThere are task items which use it."))
                {
                    md.Run();
                    md.Destroy();
                }
                return;
            }

            category.Delete();

            if (CheckStatus(category))
            {
                _sqlItems.Add(category);
            }

            _categoryStore.Remove(ref iter);
        }
Esempio n. 44
0
        private void RealEditValidator(object sender, EventArgs e)
        {
            Entry tb = sender as Entry;

            if (tb != null)
            {
                TSupplement.TSuppAttribute tagEnum;
                if (entryLookup.TryGetValue(tb, out tagEnum))
                {
                    double maxVal = 0.0;
                    double scale  = 1.0;
                    switch (tagEnum)
                    {
                    case TSupplement.TSuppAttribute.spaDMP:
                    case TSupplement.TSuppAttribute.spaDMD:
                    case TSupplement.TSuppAttribute.spaEE:
                    case TSupplement.TSuppAttribute.spaDG:
                        maxVal = 100.0;
                        scale  = 0.01;
                        break;

                    case TSupplement.TSuppAttribute.spaMEDM:
                        maxVal = 20.0;
                        break;

                    case TSupplement.TSuppAttribute.spaCP:
                        maxVal = 300.0;
                        scale  = 0.01;
                        break;

                    case TSupplement.TSuppAttribute.spaPH:
                    case TSupplement.TSuppAttribute.spaSU:
                    case TSupplement.TSuppAttribute.spaADIP:
                        maxVal = 200.0;      // Why 200?
                        scale  = 0.01;
                        break;

                    default:
                        maxVal = 100.0;
                        break;
                    }
                    double value;
                    bool   cancel = false;
                    if (string.IsNullOrWhiteSpace(tb.Text)) // Treat blank as a value of 0.
                    {
                        value = 0.0;
                    }
                    else if (!Double.TryParse(tb.Text, out value) || value < 0.0 || value > maxVal)
                    {
                        /// e.Cancel = true;
                        cancel = true;
                        MessageDialog md = new MessageDialog(MainWidget.Toplevel as Window, DialogFlags.Modal, MessageType.Warning, ButtonsType.Ok,
                                                             String.Format("Value should be a number in the range 0 to {0:F2}", maxVal));
                        md.Title = "Invalid entry";
                        md.Run();
                        md.Destroy();
                    }
                    if (!cancel)
                    {
                        if (SuppAttrChanged != null)
                        {
                            TSuppAttrArgs args = new TSuppAttrArgs();
                            args.attr    = (int)tagEnum;
                            args.attrVal = value * scale;
                            SuppAttrChanged.Invoke(sender, args);
                        }
                    }
                }
            }
        }
Esempio n. 45
0
    protected void buttonSave_Click(object sender, EventArgs e)
    {
        int error = 0;

        if (entryName.Text == string.Empty)
        {
            error++;
        }

        if (entryAddress.Text == string.Empty)
        {
            error++;
        }

        if (entryCity.Text == string.Empty)
        {
            error++;
        }

        if (entryCEP.Text == string.Empty)
        {
            error++;
        }

        if (entryTelephone.Text == string.Empty)
        {
            error++;
        }

        if (error > 0)
        {
            MessageDialog messageDialogError = new MessageDialog(this,
                                                                 DialogFlags.Modal,
                                                                 MessageType.Error,
                                                                 ButtonsType.Ok,
                                                                 "Preencha todos os campos"
                                                                 );

            messageDialogError.Run();
            messageDialogError.Destroy();
        }



        if (error == 0)
        {
            MessageDialog messageDialog = new MessageDialog(this,
                                                            DialogFlags.Modal,
                                                            MessageType.Info,
                                                            ButtonsType.Ok,
                                                            "Pessoa cadastrada com sucesso!"
                                                            );
            messageDialog.Run();
            messageDialog.Destroy();

            id++;
            string name      = entryName.Text;
            string address   = entryAddress.Text;
            string city      = entryCity.Text;
            string cep       = entryCEP.Text;
            string telephone = entryTelephone.Text;

            people.AppendValues(
                id,
                name,
                address,
                city,
                cep,
                telephone
                );
            this.treeViewPeople.Model = people;
        }
    }
Esempio n. 46
0
        private void ImportProject()
        {
            Project           project;
            bool              isFake, exists;
            int               res;
            string            fileName;
            FileFilter        filter;
            NewProjectDialog  npd;
            FileChooserDialog fChooser;

            Log.Debug("Importing project");
            /* Show a file chooser dialog to select the file to import */
            fChooser = new FileChooserDialog(Catalog.GetString("Import Project"),
                                             mainWindow,
                                             FileChooserAction.Open,
                                             "gtk-cancel", ResponseType.Cancel,
                                             "gtk-open", ResponseType.Accept);
            fChooser.SetCurrentFolder(Config.HomeDir());
            filter      = new FileFilter();
            filter.Name = Constants.PROJECT_NAME;
            filter.AddPattern("*.lpr");
            fChooser.AddFilter(filter);


            res      = fChooser.Run();
            fileName = fChooser.Filename;
            fChooser.Destroy();
            /* return if the user cancelled */
            if (res != (int)ResponseType.Accept)
            {
                return;
            }

            /* try to import the project and show a message error is the file
             * is not a valid project */
            try {
                project = Project.Import(fileName);
            }
            catch (Exception ex) {
                MessagePopup.PopupMessage(mainWindow, MessageType.Error,
                                          Catalog.GetString("Error importing project:") +
                                          "\n" + ex.Message);
                Log.Exception(ex);
                return;
            }

            isFake = (project.Description.File.FilePath == Constants.FAKE_PROJECT);

            /* If it's a fake live project prompt for a video file and
             * create a new PreviewMediaFile for this project */
            if (isFake)
            {
                Log.Debug("Importing fake live project");
                project.Description.File = null;
                npd = new NewProjectDialog();
                npd.TransientFor = mainWindow;
                npd.Use          = ProjectType.EditProject;
                npd.Project      = project;
                int response = npd.Run();
                while (true)
                {
                    if (response != (int)ResponseType.Ok)
                    {
                        npd.Destroy();
                        return;
                    }
                    else if (npd.Project == null)
                    {
                        MessagePopup.PopupMessage(mainWindow, MessageType.Info,
                                                  Catalog.GetString("Please, select a video file."));
                        response = npd.Run();
                    }
                    else
                    {
                        project = npd.Project;
                        npd.Destroy();
                        break;
                    }
                }
            }

            /* If the project exists ask if we want to overwrite it */
            if (Core.DB.Exists(project))
            {
                MessageDialog md = new MessageDialog(mainWindow,
                                                     DialogFlags.Modal,
                                                     MessageType.Question,
                                                     Gtk.ButtonsType.YesNo,
                                                     Catalog.GetString("A project already exists for the file:") +
                                                     project.Description.File.FilePath + "\n" +
                                                     Catalog.GetString("Do you want to overwrite it?"));
                md.Icon = Gtk.IconTheme.Default.LoadIcon("longomatch", 48, 0);
                res     = md.Run();
                md.Destroy();
                if (res != (int)ResponseType.Yes)
                {
                    return;
                }
                exists = true;
            }
            else
            {
                exists = false;
            }

            if (isFake)
            {
                CreateThumbnails(project);
            }
            if (exists)
            {
                Core.DB.UpdateProject(project);
            }
            else
            {
                Core.DB.AddProject(project);
            }


            MessagePopup.PopupMessage(mainWindow, MessageType.Info,
                                      Catalog.GetString("Project successfully imported."));
        }
Esempio n. 47
0
        private void HandleInstallerDialog(FileChooserDialog fileChooser)
        {
            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                MessageDialog dialog = null;

                try
                {
                    string filename = fileChooser.Filename;

                    fileChooser.Dispose();

                    var firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);

                    if (firmwareVersion == null)
                    {
                        dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                        dialog.Text = "Firmware not found.";

                        dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";

                        Logger.PrintError(LogClass.Application, $"A valid system firmware was not found in {filename}.");

                        dialog.Run();
                        dialog.Hide();
                        dialog.Dispose();

                        return;
                    }

                    var currentVersion = _contentManager.GetCurrentFirmwareVersion();

                    string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";

                    if (currentVersion != null)
                    {
                        dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
                    }

                    dialogMessage += "Do you want to continue?";

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");

                    dialog.Text          = $"Install Firmware {firmwareVersion.VersionString}";
                    dialog.SecondaryText = dialogMessage;

                    int response = dialog.Run();

                    dialog.Dispose();

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");

                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";

                    dialog.SecondaryText = "Installing firmware...";

                    if (response == (int)ResponseType.Yes)
                    {
                        Logger.PrintInfo(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");

                        Thread thread = new Thread(() =>
                        {
                            GLib.Idle.Add(new GLib.IdleHandler(() =>
                            {
                                dialog.Run();
                                return(false);
                            }));

                            try
                            {
                                _contentManager.InstallFirmware(filename);

                                GLib.Idle.Add(new GLib.IdleHandler(() =>
                                {
                                    dialog.Dispose();

                                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";

                                    dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";

                                    Logger.PrintInfo(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");

                                    dialog.Run();
                                    dialog.Dispose();

                                    return(false);
                                }));
                            }
                            catch (Exception ex)
                            {
                                GLib.Idle.Add(new GLib.IdleHandler(() =>
                                {
                                    dialog.Dispose();

                                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";

                                    dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
                                                           " Please check logs for more info.";

                                    Logger.PrintError(LogClass.Application, ex.Message);

                                    dialog.Run();
                                    dialog.Dispose();

                                    return(false);
                                }));
                            }
                            finally
                            {
                                RefreshFirmwareLabel();
                            }
                        });

                        thread.Name = "GUI.FirmwareInstallerThread";
                        thread.Start();
                    }
                    else
                    {
                        dialog.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    if (dialog != null)
                    {
                        dialog.Dispose();
                    }

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                    dialog.Text = "Parsing Firmware Failed.";

                    dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";

                    Logger.PrintError(LogClass.Application, ex.Message);

                    dialog.Run();
                    dialog.Dispose();
                }
            }
            else
            {
                fileChooser.Dispose();
            }
        }
Esempio n. 48
0
        internal static void RunGui(bool isLinux)
        {
            var stream = typeof(Program).Assembly.GetManifestResourceStream("AmongUsModLoaderInstaller.Window.glade");

            if (stream == null)
            {
                return;
            }
            using var reader = new StreamReader(stream);
            Application.Init();
            var builder = new Builder();

            builder.AddFromString(reader.ReadToEnd());
            var window         = Get <ApplicationWindow>("main_container");
            var typeSelector   = Get <ComboBox>("type_selector");
            var path           = Get <FileChooserButton>("path");
            var pathText       = Get <Label>("path_label");
            var prefixPath     = Get <FileChooserButton>("wine_prefix");
            var prefixText1    = Get <Label>("wine_prefix_label1");
            var prefixText2    = Get <Label>("wine_prefix_label2");
            var installButton  = Get <Button>("install_button");
            var clientPathText = pathText.Text;
            var winePrefix1    = prefixText1.Text;
            var winePrefix2    = prefixText2.Text;
            var server         = false;

            T Get <T>(string name) where T : Widget => (T)builder.GetObject(name);

            void SetText(bool steam)
            {
                if (steam)
                {
                    prefixText1.Text = "";
                    prefixText2.Text = "Steam Directory";
                }
                else
                {
                    prefixText1.Text = winePrefix1;
                    prefixText2.Text = winePrefix2;
                }
            }

            const string relativeGameSteamLocation = "steamapps/common/Among Us/";
            var          steamCheck = Get <CheckButton>("steam_check");

            steamCheck.Active = true;

            ToggleHandler(window, EventArgs.Empty);
            steamCheck.Toggled += ToggleHandler;
            prefixPath.CurrentFolderChanged += (sender, args) =>
            {
                if (steamCheck.Active)
                {
                    path.SetCurrentFolder(prefixPath.CurrentFolder + "/" + relativeGameSteamLocation);
                }
            };

            typeSelector.Changed += (sender, args) =>
            {
                if (!typeSelector.GetActiveIter(out var iter))
                {
                    return;
                }
                var value = (string)typeSelector.Model.GetValue(iter, 0);
                if (value == "Server")
                {
                    server        = true;
                    pathText.Text = "Installation Directory";
                    prefixPath.Hide();
                    prefixText1.Hide();
                    prefixText2.Hide();
                    steamCheck.Hide();
                }
                else
                {
                    server        = false;
                    pathText.Text = clientPathText;
                    steamCheck.Show();
                    if (!steamCheck.Active && !isLinux)
                    {
                        return;
                    }
                    prefixPath.Show();
                    prefixText1.Show();
                    prefixText2.Show();
                }
            };

            void ToggleHandler(object?sender, EventArgs args)
            {
                if (steamCheck.Active)
                {
                    var steam = isLinux
                        ? Environment.GetEnvironmentVariable("HOME") + "/.local/share/Steam/"
                        : Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "/Steam/";
                    path.SetCurrentFolder(steam + relativeGameSteamLocation);

                    if (isLinux)
                    {
                        prefixText1.Show();
                        prefixText2.Show();
                        SetText(true);
                    }
                    else
                    {
                        prefixText1.Hide();
                        prefixText2.Hide();
                        prefixPath.Hide();
                    }

                    prefixPath.SetCurrentFolder(steam);
                }
                else
                {
                    path.UnselectAll();
                    path.Show();
                    pathText.Show();

                    if (isLinux)
                    {
                        SetText(false);
                        prefixText1.Show();
                        prefixText2.Show();
                        prefixPath.Show();
                        prefixPath.SetCurrentFolder(Environment.GetEnvironmentVariable("HOME") + "/.wine/");
                    }
                    else
                    {
                        prefixText1.Hide();
                        prefixText2.Hide();
                        prefixPath.Hide();
                    }
                }
            }

            installButton.Clicked += async(sender, args) =>
            {
                try
                {
                    await Installer.Run(isLinux, server, steamCheck.Active, true, path.CurrentFolder, prefixPath.CurrentFolder);
                }
                catch (Exception e)
                {
                    using var dialog = new MessageDialog(window, DialogFlags.Modal, MessageType.Error,
                                                         ButtonsType.Close, false, "{0}: {1}\n{2}", e, e.Message, e.StackTrace);
                    dialog.Run();
                    throw;
                }
            };
            window.DeleteEvent += (sender, args) => Application.Quit();
            window.ShowAll();
            Application.Run();
        }
Esempio n. 49
0
    protected void CalibrateHandler(object sender, EventArgs e)
    {
        /* Calibrate the thresholds to user's movements */

        int md_result = 0;

        // Image with instructions on how to execute the movements
        Gtk.Image down_mvmnt_img = new Gtk.Image();
        Gtk.Image side_mvmnt_img = new Gtk.Image();
        down_mvmnt_img.PixbufAnimation = new Gdk.PixbufAnimation(null, "TRAB_IHC.res.DownMvmnt.gif");
        side_mvmnt_img.PixbufAnimation = new Gdk.PixbufAnimation(null, "TRAB_IHC.res.SideMvmnt.gif");

        // Calibrate downward movement

        // Show message with instructions for first move
        MessageDialog downfirst_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.OkCancel,
                                                       "Calibration for down movements will now begin.\n\nPlease press OK and make the movement shown with your controller.")
        {
            Image = down_mvmnt_img
        };

        downfirst_md.ShowAll();
        md_result = downfirst_md.Run();
        downfirst_md.Destroy();

        if (md_result == -5) // Dialog OK
        {
            // Reset result
            md_result = 0;

            // Record user movements after OK is pressed
            CalibrateForce(0, 0);

            down_mvmnt_img.PixbufAnimation = new Gdk.PixbufAnimation(null, "TRAB_IHC.res.DownMvmnt.gif");

            // Show message with instructions for second move
            MessageDialog downsecond_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                            "Very good, now a second time.")
            {
                Image = down_mvmnt_img
            };
            downsecond_md.ShowAll();
            md_result = downsecond_md.Run();
            downsecond_md.Destroy();

            if (md_result == -5)
            {
                // Reset result
                md_result = 0;

                // Record user movements after OK is pressed
                CalibrateForce(0, 1);

                down_mvmnt_img.PixbufAnimation = new Gdk.PixbufAnimation(null, "TRAB_IHC.res.DownMvmnt.gif");

                // Show message with instructions for third move
                MessageDialog downthird_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                               "And lastly a third time.")
                {
                    Image = down_mvmnt_img
                };
                downthird_md.ShowAll();
                md_result = downthird_md.Run();
                downthird_md.Destroy();

                if (md_result == -5)
                {
                    // Reset result
                    md_result = 0;

                    // Record user movements after OK is pressed
                    CalibrateForce(0, 2);

                    // Calibrate sideways movement

                    // Show message with instructions for the first move
                    MessageDialog sidefirst_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                                   "Calibration for sideways movements will now begin.\n\nPlease press OK and and make the movement shown with your controller.")
                    {
                        Image = side_mvmnt_img
                    };
                    sidefirst_md.ShowAll();
                    md_result = sidefirst_md.Run();
                    sidefirst_md.Destroy();

                    if (md_result == -5)
                    {
                        // Reset result
                        md_result = 0;

                        // Record user movements after OK is pressed
                        CalibrateForce(1, 0);

                        side_mvmnt_img.PixbufAnimation = new Gdk.PixbufAnimation(null, "TRAB_IHC.res.SideMvmnt.gif");

                        MessageDialog sidesecond_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                                        "Very good, now a second time.")
                        {
                            Image = side_mvmnt_img
                        };
                        sidesecond_md.ShowAll();
                        md_result = sidesecond_md.Run();
                        sidesecond_md.Destroy();

                        if (md_result == -5)
                        {
                            // Record user movements affter OK is pressed
                            CalibrateForce(1, 1);

                            side_mvmnt_img.PixbufAnimation = new Gdk.PixbufAnimation(null, "TRAB_IHC.res.SideMvmnt.gif");

                            MessageDialog sidethird_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                                           "And lastly a third time.")
                            {
                                Image = side_mvmnt_img
                            };
                            sidethird_md.ShowAll();
                            md_result = sidethird_md.Run();
                            sidethird_md.Destroy();

                            if (md_result == -5)
                            {
                                // Record user movements after OK is pressed
                                CalibrateForce(1, 2);
                            }
                        }
                    }
                }
            }
        }
    }
Esempio n. 50
0
    static Settings()
    {
        String SettingsPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Constants.PACKAGE_NAME);

        SettingsFile = System.IO.Path.Combine(SettingsPath, "settings.xml");

        StreamReader reader = null;

        try {
            LogManager.Log(LogLevel.Info, "Using configfile: " + SettingsFile);
            reader   = new StreamReader(SettingsFile);
            Instance = (Settings)settingsSerializer.Deserialize(reader);
        } catch (Exception e) {
            LogManager.Log(LogLevel.Error, "Couldn't load configfile: " + e.Message);
            LogManager.Log(LogLevel.Info, "Creating new config from scratch");
            Instance = new Settings();
        } finally {
            if (reader != null)
            {
                reader.Close();
            }
        }

        LogManager.Log(LogLevel.Info, "Supertux is run as: " + Instance.SupertuxExe);
        if (Instance.SupertuxData != null)
        {
            LogManager.Log(LogLevel.Info, "Data files are in: " + Instance.SupertuxData);
        }
        else
        {
            LogManager.Log(LogLevel.Info, "Unable to find data files when querying supertux.");
        }

        // If data path does not exist, prompt user to change it before we try continue initializing
        if (Instance.SupertuxData == null ||
            !new DirectoryInfo(System.IO.Path.GetDirectoryName(Instance.SupertuxData)).Exists)
        {
            LogManager.Log(LogLevel.Error, "Data path does not exist.");

            String bad_data_path_msg;
            if (Instance.SupertuxData == null)
            {
                bad_data_path_msg = "The data path could not be calculated." + Environment.NewLine
                                    + Environment.NewLine
                                    + "You must install a newer version of Supertux to use this version of the editor or specify the correct path to the supertux2 binary.";
            }
            else
            {
                bad_data_path_msg = "The current data path, `"
                                    + Instance.SupertuxData + "', does not exist." + Environment.NewLine
                                    + Environment.NewLine
                                    + "This means that your supertux installation (`" + Instance.SupertuxExe + "') is corrupted or incomplete.";
            }

            MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.None, bad_data_path_msg);
            md.AddButton(Gtk.Stock.No, ResponseType.No);
            md.AddButton(Gtk.Stock.Edit, ResponseType.Yes);
            if (md.Run() == (int)ResponseType.Yes)
            {
                new SettingsDialog(true);
            }
            md.Destroy();
        }

        Resources.ResourceManager.Instance = new Resources.DefaultResourceManager(Instance.SupertuxData + "/");
    }
Esempio n. 51
0
        public void SaveChanges(MySqlTransaction trans)
        {
            logger.Info("Записывам изменения в списке файлов...");
            string sql = String.Format("INSERT INTO {0} (name, item_group, item_id, size, file) " +
                                       "VALUES (@name, @item_group, @item_id, @size, @file)", TableName);
            MySqlCommand cmd = new MySqlCommand(sql, (MySqlConnection)QSMain.ConnectionDB, trans);

            cmd.Prepare();
            cmd.Parameters.AddWithValue("@name", "");
            cmd.Parameters.AddWithValue("@item_group", AttachToTable);
            cmd.Parameters.AddWithValue("@item_id", ItemId);
            cmd.Parameters.AddWithValue("@size", 0);
            cmd.Parameters.AddWithValue("@file", null);
            foreach (object[] row in FilesStore)
            {
                if ((int)row [(int)FilesCol.id] > 0)
                {
                    continue;
                }
                logger.Info("Отправляем {0}...", row [(int)FilesCol.name]);
                byte[] file = (byte[])row [(int)FilesCol.file];
                cmd.Parameters ["@name"].Value = row [(int)FilesCol.name];
                cmd.Parameters ["@size"].Value = file.LongLength;
                cmd.Parameters ["@file"].Value = file;
                try {
                    cmd.ExecuteNonQuery();
                } catch (MySqlException ex) {
                    if (ex.Number == 1153)
                    {
                        logger.Warn(ex, "Превышен максимальный размер пакета для передачи на сервер.");
                        string Text = String.Format("При передачи файла {0}, " +
                                                    "превышен максимальный размер пакета для передачи на сервер базы данных. " +
                                                    "Файл не будет сохранен. " +
                                                    "Это значение настраивается на сервере, по умолчанию для MySQL оно равняется 1Мб. " +
                                                    "Максимальный размер файла поддерживаемый программой составляет 16Мб, мы рекомендуем " +
                                                    "установить в настройках сервера параметр <b>max_allowed_packet=16M</b>. Подробнее о настройке здесь " +
                                                    "http://dev.mysql.com/doc/refman/5.6/en/packet-too-large.html", row [(int)FilesCol.name]);
                        MessageDialog md = new MessageDialog((Gtk.Window) this.Toplevel, DialogFlags.Modal,
                                                             MessageType.Error,
                                                             ButtonsType.Ok, Text);
                        md.Run();
                        md.Destroy();
                    }
                    else if (ex.Number == 1118)
                    {
                        logger.Warn(ex, "Ошибка: превышена допустимая длина строки.");
                        string Text = String.Format("При передачи файла {0} была превышена максимально допустимая " +
                                                    "длина строки в БД MySQL. Файл не будет сохранен. Также эта ошибка может " +
                                                    "возникать при отсутствии возможности записи в log файл. В качестве возможного решения данной " +
                                                    "проблемы мы рекомендуем установить в настройках сервера следующие параметры: " +
                                                    "<b>\ninnodb_log_file_size = 499M" +
                                                    "\ninnodb_log_buffer_size = 499M</b>.",
                                                    row [(int)FilesCol.name]);
                        MessageDialog md = new MessageDialog((Gtk.Window) this.Toplevel, DialogFlags.Modal,
                                                             MessageType.Error,
                                                             ButtonsType.Ok, Text);
                        md.Run();
                        md.Destroy();
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }

            if (deletedItems.Count > 0)
            {
                logger.Info("Удаляем удаленные файлы на сервере...");
                DBWorks.SQLHelper sqld = new DBWorks.SQLHelper("DELETE FROM {0} WHERE id IN ", TableName);
                sqld.QuoteMode = DBWorks.QuoteType.SingleQuotes;
                sqld.StartNewList("(", ", ");
                deletedItems.ForEach(delegate(int obj) {
                    sqld.AddAsList(obj.ToString());
                });
                sqld.Add(")");
                cmd = new MySqlCommand(sqld.Text, (MySqlConnection)QSMain.ConnectionDB, trans);
                cmd.ExecuteNonQuery();
            }
        }
Esempio n. 52
0
        void llenado_de_devoluciones()
        {
            string toma_idproducto          = "";
            string toma_descripcionproducto = "";
            string toma_productosaplicados  = "";
            string toma_subalmacen          = "";
            int    toma_idsubalmacen;

            treeViewEngine1.Clear();
            treeViewEngine2.Clear();
            treeViewEngine3.Clear();

            NpgsqlConnection conexion;

            conexion = new NpgsqlConnection(connectionString + nombrebd);
            NpgsqlConnection conexion1;

            conexion1 = new NpgsqlConnection(connectionString + nombrebd);

            informacion_paciente();

            // Cargos desde el stock del sub-almacen
            // Verifica que la base de datos este conectada
            try{
                conexion.Open();
                NpgsqlCommand comando;
                comando = conexion.CreateCommand();

                // asigna el numero de folio de ingreso de paciente (FOLIO)
                comando.CommandText = "SELECT to_char(SUM(cantidad_aplicada),'999999999.99') AS cantidadaplicada,osiris_erp_cobros_deta.id_producto AS idproducto," +
                                      "osiris_erp_cobros_deta.id_almacen,descripcion_almacen,osiris_productos.descripcion_producto,osiris_erp_cobros_deta.id_almacen AS idalmacen " +
                                      "FROM osiris_erp_cobros_deta,osiris_productos,osiris_almacenes " +
                                      "WHERE osiris_erp_cobros_deta.id_producto = osiris_productos.id_producto " +
                                      "AND osiris_erp_cobros_deta.id_almacen = osiris_almacenes.id_almacen " +
                                      "AND folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                      "GROUP BY osiris_erp_cobros_deta.id_producto,osiris_productos.descripcion_producto,osiris_erp_cobros_deta.id_almacen,descripcion_almacen " +
                                      "ORDER BY osiris_erp_cobros_deta.id_almacen,osiris_productos.descripcion_producto;";
                //Console.WriteLine(comando.CommandText);
                NpgsqlDataReader lector = comando.ExecuteReader();
                if (lector.Read())
                {
                    toma_idproducto          = (string)lector["idproducto"].ToString().Trim();
                    toma_descripcionproducto = (string)lector["descripcion_producto"].ToString().Trim();
                    toma_productosaplicados  = (string)lector["cantidadaplicada"].ToString();
                    toma_subalmacen          = (string)lector["descripcion_almacen"].ToString();
                    toma_idsubalmacen        = (int)lector["idalmacen"];
                    conexion1.Open();
                    NpgsqlCommand comando1;
                    comando1 = conexion.CreateCommand();

                    // asigna el numero de folio de ingreso de paciente (FOLIO)
                    comando1.CommandText = "SELECT osiris_erp_cobros_deta.id_producto AS idproducto,SUM(osiris_erp_cobros_deta.cantidad_aplicada) AS cantidad_aplicada," +
                                           "osiris_his_solicitudes_deta.id_producto,SUM(osiris_his_solicitudes_deta.cantidad_autorizada) AS cantidad_autorizada," +
                                           "osiris_productos.descripcion_producto AS descripcionproducto " +
                                           "FROM osiris_erp_cobros_deta,osiris_his_solicitudes_deta,osiris_productos " +
                                           "WHERE osiris_erp_cobros_deta.folio_de_servicio = osiris_his_solicitudes_deta.folio_de_servicio " +
                                           "AND osiris_erp_cobros_deta.id_producto = osiris_his_solicitudes_deta.id_producto " +
                                           "AND osiris_erp_cobros_deta.id_producto = osiris_productos.id_producto " +
                                           //"AND osiris_erp_cobros_deta.id_almacen = osiris_his_solicitudes_deta.id_almacen "+
                                           "AND osiris_erp_cobros_deta.folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                           "AND osiris_erp_cobros_deta.id_producto = '" + toma_idproducto + "' " +
                                           "AND osiris_erp_cobros_deta.id_almacen = '" + toma_idsubalmacen.ToString().Trim() + "' " +
                                           "AND osiris_his_solicitudes_deta.surtido = 'true' " +
                                           "GROUP BY osiris_erp_cobros_deta.id_producto,osiris_his_solicitudes_deta.id_producto,osiris_productos.descripcion_producto;";
                    //"ORDER BY osiris_productos.descripcion_producto;";
                    //Console.WriteLine(comando1.CommandText);
                    NpgsqlDataReader lector1 = comando1.ExecuteReader();
                    if (lector1.Read() == false)
                    {
                        treeViewEngine1.AppendValues(toma_idproducto, toma_descripcionproducto, toma_productosaplicados, "0.00", "0.00", toma_subalmacen);
                    }
                    conexion1.Close();
                    while (lector.Read())
                    {
                        toma_idproducto          = (string)lector["idproducto"].ToString().Trim();
                        toma_descripcionproducto = (string)lector["descripcion_producto"].ToString().Trim();
                        toma_productosaplicados  = (string)lector["cantidadaplicada"].ToString();
                        toma_subalmacen          = (string)lector["descripcion_almacen"].ToString();
                        toma_idsubalmacen        = (int)lector["idalmacen"];
                        conexion1.Open();
                        comando1 = conexion1.CreateCommand();
                        // asigna el numero de folio de ingreso de paciente (FOLIO)
                        comando1.CommandText = "SELECT osiris_erp_cobros_deta.id_producto AS idproducto,SUM(osiris_erp_cobros_deta.cantidad_aplicada) AS cantidad_aplicada," +
                                               "osiris_his_solicitudes_deta.id_producto,SUM(osiris_his_solicitudes_deta.cantidad_autorizada) AS cantidad_autorizada," +
                                               "osiris_productos.descripcion_producto AS descripcionproducto " +
                                               "FROM osiris_erp_cobros_deta,osiris_his_solicitudes_deta,osiris_productos " +
                                               "WHERE osiris_erp_cobros_deta.folio_de_servicio = osiris_his_solicitudes_deta.folio_de_servicio " +
                                               "AND osiris_erp_cobros_deta.id_producto = osiris_his_solicitudes_deta.id_producto " +
                                               "AND osiris_erp_cobros_deta.id_producto = osiris_productos.id_producto " +
                                               "AND osiris_erp_cobros_deta.id_almacen = osiris_his_solicitudes_deta.id_almacen " +
                                               "AND osiris_erp_cobros_deta.folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                               "AND osiris_erp_cobros_deta.id_producto = '" + toma_idproducto + "' " +
                                               "AND osiris_erp_cobros_deta.id_almacen = '" + toma_idsubalmacen.ToString().Trim() + "' " +
                                               "AND osiris_his_solicitudes_deta.surtido = 'true' " +
                                               "GROUP BY osiris_erp_cobros_deta.id_producto,osiris_his_solicitudes_deta.id_producto,osiris_productos.descripcion_producto;";
                        //"ORDER BY osiris_productos.descripcion_producto;";
                        //Console.WriteLine(comando1.CommandText);
                        lector1 = comando1.ExecuteReader();
                        if (lector1.Read() == false)
                        {
                            treeViewEngine1.AppendValues(toma_idproducto, toma_descripcionproducto, toma_productosaplicados, "0.00", "0.00", toma_subalmacen);
                        }
                        conexion1.Close();
                    }
                }
                else
                {
                    MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.DestroyWithParent, MessageType.Error,
                                                                  ButtonsType.Close, "Este numero de atencion tiene solo cargos desde STOCK de Sub-Almacene");
                    msgBoxError.Run();                     msgBoxError.Destroy();
                }
            }catch (NpgsqlException ex) {
                MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.Modal,
                                                              MessageType.Error,
                                                              ButtonsType.Close, "PostgresSQL error: {0}", ex.Message);
                msgBoxError.Run();                             msgBoxError.Destroy();
            }
            conexion.Close();
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Verifica que la base de datos este conectada
            try{
                conexion.Open();
                NpgsqlCommand comando;
                comando = conexion.CreateCommand();

                // asigna el numero de folio de ingreso de paciente (FOLIO)
                comando.CommandText = "SELECT to_char(SUM(cantidad_autorizada),'999999999.99') AS cantidadautorizada,osiris_his_solicitudes_deta.id_producto AS idproducto," +
                                      "osiris_his_solicitudes_deta.id_almacen AS idalmacen,descripcion_almacen,osiris_productos.descripcion_producto " +
                                      "FROM osiris_his_solicitudes_deta,osiris_productos,osiris_almacenes " +
                                      "WHERE osiris_his_solicitudes_deta.id_producto = osiris_productos.id_producto " +
                                      "AND osiris_his_solicitudes_deta.id_almacen = osiris_almacenes.id_almacen " +
                                      "AND folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                      "AND osiris_his_solicitudes_deta.surtido = 'true' " +
                                      "GROUP BY osiris_his_solicitudes_deta.id_producto,osiris_productos.descripcion_producto,osiris_his_solicitudes_deta.id_almacen,descripcion_almacen " +
                                      "ORDER BY osiris_his_solicitudes_deta.id_almacen,osiris_productos.descripcion_producto;";
                //Console.WriteLine(comando.CommandText);
                NpgsqlDataReader lector = comando.ExecuteReader();
                if (lector.Read())
                {
                    toma_idproducto          = (string)lector["idproducto"].ToString().Trim();
                    toma_descripcionproducto = (string)lector["descripcion_producto"].ToString().Trim();
                    toma_productosaplicados  = (string)lector["cantidadautorizada"].ToString();
                    toma_subalmacen          = (string)lector["descripcion_almacen"].ToString();
                    toma_idsubalmacen        = (int)lector["idalmacen"];
                    conexion1.Open();
                    NpgsqlCommand comando1;
                    comando1 = conexion.CreateCommand();

                    // asigna el numero de folio de ingreso de paciente (FOLIO)
                    comando1.CommandText = "SELECT osiris_erp_cobros_deta.id_producto AS idproducto,SUM(osiris_erp_cobros_deta.cantidad_aplicada) AS cantidad_aplicada," +
                                           "osiris_his_solicitudes_deta.id_producto,SUM(osiris_his_solicitudes_deta.cantidad_autorizada) AS cantidad_autorizada," +
                                           "osiris_productos.descripcion_producto AS descripcionproducto " +
                                           "FROM osiris_erp_cobros_deta,osiris_his_solicitudes_deta,osiris_productos " +
                                           "WHERE osiris_erp_cobros_deta.folio_de_servicio = osiris_his_solicitudes_deta.folio_de_servicio " +
                                           "AND osiris_erp_cobros_deta.id_producto = osiris_his_solicitudes_deta.id_producto " +
                                           "AND osiris_erp_cobros_deta.id_producto = osiris_productos.id_producto " +
                                           "AND osiris_erp_cobros_deta.folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                           "AND osiris_erp_cobros_deta.id_producto = '" + toma_idproducto + "' " +
                                           "AND osiris_erp_cobros_deta.id_almacen = '" + toma_idsubalmacen.ToString().Trim() + "' " +
                                           "AND osiris_his_solicitudes_deta.surtido = 'true' " +
                                           "GROUP BY osiris_erp_cobros_deta.id_producto,osiris_his_solicitudes_deta.id_producto,osiris_productos.descripcion_producto;";
                    //"ORDER BY osiris_productos.descripcion_producto;";
                    //Console.WriteLine(comando1.CommandText);
                    NpgsqlDataReader lector1 = comando1.ExecuteReader();
                    if (lector1.Read() == false)
                    {
                        treeViewEngine2.AppendValues(toma_idproducto, toma_descripcionproducto, "0.00", toma_productosaplicados, toma_productosaplicados, toma_subalmacen);
                    }
                    conexion1.Close();
                    while (lector.Read())
                    {
                        toma_idproducto          = (string)lector["idproducto"].ToString().Trim();
                        toma_descripcionproducto = (string)lector["descripcion_producto"].ToString().Trim();
                        toma_productosaplicados  = (string)lector["cantidadautorizada"].ToString();
                        toma_subalmacen          = (string)lector["descripcion_almacen"].ToString();
                        toma_idsubalmacen        = (int)lector["idalmacen"];
                        conexion1.Open();
                        comando1 = conexion1.CreateCommand();
                        // asigna el numero de folio de ingreso de paciente (FOLIO)
                        comando1.CommandText = "SELECT osiris_erp_cobros_deta.id_producto AS idproducto,SUM(osiris_erp_cobros_deta.cantidad_aplicada) AS cantidad_aplicada," +
                                               "osiris_his_solicitudes_deta.id_producto,SUM(osiris_his_solicitudes_deta.cantidad_autorizada) AS cantidad_autorizada," +
                                               "osiris_productos.descripcion_producto AS descripcionproducto " +
                                               "FROM osiris_erp_cobros_deta,osiris_his_solicitudes_deta,osiris_productos " +
                                               "WHERE osiris_erp_cobros_deta.folio_de_servicio = osiris_his_solicitudes_deta.folio_de_servicio " +
                                               "AND osiris_erp_cobros_deta.id_producto = osiris_his_solicitudes_deta.id_producto " +
                                               "AND osiris_erp_cobros_deta.id_producto = osiris_productos.id_producto " +
                                               "AND osiris_erp_cobros_deta.folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                               "AND osiris_erp_cobros_deta.id_producto = '" + toma_idproducto + "' " +
                                               "AND osiris_erp_cobros_deta.id_almacen = '" + toma_idsubalmacen.ToString().Trim() + "' " +
                                               "AND osiris_his_solicitudes_deta.surtido = 'true' " +
                                               "GROUP BY osiris_erp_cobros_deta.id_producto,osiris_his_solicitudes_deta.id_producto,osiris_productos.descripcion_producto;";
                        //"ORDER BY osiris_productos.descripcion_producto;";
                        //Console.WriteLine(comando1.CommandText);
                        lector1 = comando1.ExecuteReader();
                        if (lector1.Read() == false)
                        {
                            treeViewEngine2.AppendValues(toma_idproducto,
                                                         toma_descripcionproducto,
                                                         "0.00",
                                                         toma_productosaplicados,
                                                         toma_productosaplicados,
                                                         toma_subalmacen);
                        }
                        conexion1.Close();
                    }
                }
                else
                {
                    MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.DestroyWithParent, MessageType.Error,
                                                                  ButtonsType.Close, "Este numero de atencion tiene solo cargos desde STOCK de Sub-Almacene");
                    msgBoxError.Run();                     msgBoxError.Destroy();
                }
            }catch (NpgsqlException ex) {
                MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.Modal,
                                                              MessageType.Error,
                                                              ButtonsType.Close, "PostgresSQL error: {0}", ex.Message);
                msgBoxError.Run();                             msgBoxError.Destroy();
            }
            conexion.Close();

            try{
                conexion.Open();
                NpgsqlCommand comando;
                comando = conexion.CreateCommand();

                // asigna el numero de folio de ingreso de paciente (FOLIO)
                comando.CommandText = "SELECT to_char(SUM(cantidad_aplicada),'999999999.99') AS cantidadaplicada,osiris_erp_cobros_deta.id_producto AS idproducto," +
                                      "osiris_erp_cobros_deta.id_almacen,descripcion_almacen,osiris_productos.descripcion_producto,osiris_erp_cobros_deta.id_almacen AS idalmacen " +
                                      "FROM osiris_erp_cobros_deta,osiris_productos,osiris_almacenes " +
                                      "WHERE osiris_erp_cobros_deta.id_producto = osiris_productos.id_producto " +
                                      "AND osiris_erp_cobros_deta.id_almacen = osiris_almacenes.id_almacen " +
                                      "AND folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                      "GROUP BY osiris_erp_cobros_deta.id_producto,osiris_productos.descripcion_producto,osiris_erp_cobros_deta.id_almacen,descripcion_almacen " +
                                      "ORDER BY osiris_erp_cobros_deta.id_almacen,osiris_productos.descripcion_producto;";
                //Console.WriteLine(comando.CommandText);
                NpgsqlDataReader lector = comando.ExecuteReader();

                while (lector.Read() == true)
                {
                    toma_idproducto          = (string)lector["idproducto"].ToString().Trim();
                    toma_descripcionproducto = (string)lector["descripcion_producto"].ToString().Trim();
                    toma_productosaplicados  = (string)lector["cantidadaplicada"].ToString();
                    toma_subalmacen          = (string)lector["descripcion_almacen"].ToString();
                    toma_idsubalmacen        = (int)lector["idalmacen"];

                    try{
                        conexion1.Open();
                        NpgsqlCommand comando1;
                        comando1 = conexion.CreateCommand();

                        // asigna el numero de folio de ingreso de paciente (FOLIO)
                        comando1.CommandText = "SELECT to_char(SUM(cantidad_autorizada),'999999999.99') AS cantidadautorizada,osiris_his_solicitudes_deta.id_producto AS idproducto," +
                                               "osiris_his_solicitudes_deta.id_almacen AS idalmacen,descripcion_almacen,osiris_productos.descripcion_producto " +
                                               "FROM osiris_his_solicitudes_deta,osiris_productos,osiris_almacenes " +
                                               "WHERE osiris_his_solicitudes_deta.id_producto = osiris_productos.id_producto " +
                                               "AND osiris_his_solicitudes_deta.id_almacen = osiris_almacenes.id_almacen " +
                                               "AND folio_de_servicio = '" + (string)entry_folio_servicio.Text.ToString().Trim() + "' " +
                                               "AND osiris_his_solicitudes_deta.id_producto = '" + toma_idproducto + "' " +
                                               "AND osiris_his_solicitudes_deta.id_almacen = '" + toma_idsubalmacen.ToString().Trim() + "' " +
                                               "AND osiris_his_solicitudes_deta.surtido = 'true' " +
                                               "GROUP BY osiris_his_solicitudes_deta.id_producto,osiris_productos.descripcion_producto,osiris_his_solicitudes_deta.id_almacen,descripcion_almacen " +
                                               "ORDER BY osiris_his_solicitudes_deta.id_almacen,osiris_productos.descripcion_producto;";
                        //Console.WriteLine(comando1.CommandText);
                        NpgsqlDataReader lector1 = comando1.ExecuteReader();
                        if (lector1.Read() == true)
                        {
                            treeViewEngine3.AppendValues(toma_idproducto, toma_descripcionproducto, toma_productosaplicados, (string)lector1["cantidadautorizada"], Convert.ToDouble(float.Parse((string)lector1["cantidadautorizada"]) - float.Parse(toma_productosaplicados)).ToString("F"), toma_subalmacen);
                        }
                    }catch (NpgsqlException ex) {
                        MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.Modal,
                                                                      MessageType.Error,
                                                                      ButtonsType.Close, "PostgresSQL error: {0}", ex.Message);
                        msgBoxError.Run();                             msgBoxError.Destroy();
                    }
                    conexion1.Close();
                }
            }catch (NpgsqlException ex) {
                MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.Modal,
                                                              MessageType.Error,
                                                              ButtonsType.Close, "PostgresSQL error: {0}", ex.Message);
                msgBoxError.Run();                             msgBoxError.Destroy();
            }
            conexion.Close();
        }
Esempio n. 53
0
        void CellRendererEdited(CellRendererTextAdv sender,
                                string pathStr, string newText, int colNum)
        {
            TreeModelSort model = (TreeModelSort)treeDebaters.Model;
            TreePath      path  = new TreePath(pathStr);
            TreeIter      iter  = TreeIter.Zero;

            model.GetIter(out iter, path);

            EditableDebater d = (EditableDebater)model.GetValue(iter, 0);


            try {
                ColumnInfo prop = columns[treeDebaters.Columns[colNum].Title];
                // This parses the given new string,
                // and updates the data in store
                prop.parseAndSet(d, newText);

                // existing Debater: Update Data in (possibly) existing Rounds
                // tries to keep data consisting, but there's no guarantee
                // BlackList/WhiteList and ExtraInfo are not
                // used in RoundDebater, so skip this by condition colNum<4
                if (newDebaterPath == null && colNum < 4)
                {
                    var rd = new EditableDebater(d);
                    var p  = prop.get(d);

                    // Only simple Renaming of Role is possible if Rounds exist
                    if (colNum == 3 &&
                        Tournament.I.Rounds.Count > 0 &&
                        ((d.Role.IsTeamMember != rd.Role.IsTeamMember) ||
                         (d.Role.IsJudge != rd.Role.IsJudge)))
                    {
                        MiscHelpers.ShowMessage(this, "Changing Role from Judge to TeamMember (or vice versa)" +
                                                " is not possible since Rounds are already set.", MessageType.Error);
                        // reset to old role...
                        d.Role = rd.Role;
                        return;
                    }

                    // check if new TeamName is already present
                    if (colNum == 3 && d.Role.IsTeamMember)
                    {
                        int n = 0;
                        foreach (object[] row in store)
                        {
                            EditableDebater d_ = (EditableDebater)row[0];
                            if (!d.Equals(d_) && d_.Role.TeamName == d.Role.TeamName)
                            {
                                n++;
                            }
                        }
                        if (n == 3)
                        {
                            MiscHelpers.ShowMessage(this, "New TeamName is already present in three other Debaters.",
                                                    MessageType.Error);
                            // reset to old role...
                            d.Role = rd.Role;
                            return;
                        }
                    }

                    // check for duplicate
                    if (colNum < 3)
                    {
                        // need a temporary flag, throwing exceptions in delegates doesnt work...
                        // the following flag stuff isn't elegant, but it should work
                        bool flag = false;
                        model.Foreach((model_, _, iter_) => {
                            if (!iter.Equals(iter_))
                            {
                                EditableDebater d_ = (EditableDebater)model_.GetValue(iter_, 0);
                                if (d_.Equals(d))
                                {
                                    // reset to old value...
                                    prop.get(rd).Set(d);
                                    flag = true;
                                    return(true);
                                }
                            }
                            return(false);
                        });
                        if (flag)
                        {
                            throw new TargetInvocationException(new Exception("Debater exists."));
                        }
                    }

                    // keep data consistent in existing rounds
                    foreach (RoundData round in Tournament.I.Rounds)
                    {
                        foreach (RoomData room in round.Rooms)
                        {
                            foreach (RoundDebater rd_ in room.GetRoomMembers())
                            {
                                if (rd_ == null)
                                {
                                    continue;
                                }
                                if (rd_.Equals(rd))
                                {
                                    p.UnsafeSetRoundDebater(rd_);
                                }
                                if (rd_.Role.TeamName == rd.Role.TeamName)
                                {
                                    rd_.Role.TeamName = d.Role.TeamName;
                                }
                            }
                        }
                        if (rd.Role.IsTeamMember)
                        {
                            foreach (TeamData team in round.AllTeams)
                            {
                                foreach (RoundDebater rd_ in team)
                                {
                                    if (rd_.Equals(rd))
                                    {
                                        p.UnsafeSetRoundDebater(rd_);
                                    }
                                    if (rd_.Role.TeamName == rd.Role.TeamName)
                                    {
                                        rd_.Role.TeamName = d.Role.TeamName;
                                    }
                                }
                            }
                        }
                        else if (rd.Role.IsJudge)
                        {
                            foreach (RoundDebater rd_ in round.AllJudges)
                            {
                                if (rd_.Equals(rd))
                                {
                                    p.UnsafeSetRoundDebater(rd_);
                                }
                            }
                        }
                    }

                    // Renaming TeamName needs extra Handling
                    if (colNum == 3 && rd.Role.IsTeamMember && d.Role.IsTeamMember)
                    {
                        foreach (object[] row in store)
                        {
                            EditableDebater d_ = (EditableDebater)row[0];
                            if (d_.Role.TeamName == rd.Role.TeamName)
                            {
                                d_.Role.TeamName = d.Role.TeamName;
                            }
                        }
                    }
                }
                // newDebater is entered...
                else if (newDebaterPath != null && colNum < 3)
                {
                    // continue with entering data (goto next column)
                    // as idle so that cells are resized
                    GLib.Idle.Add(delegate {
                        treeDebaters.SetCursor(ConvertStorePathToModelPath(newDebaterPath),
                                               treeDebaters.Columns[colNum + 1], true);
                        return(false);
                    });
                }
                else if (newDebaterPath != null)
                {
                    // new Debater entered completely (at least all necessary data)
                    iter = TreeIter.Zero;
                    if (store.GetIter(out iter, newDebaterPath))
                    {
                        // as idle to prevent gtk critical (no idea why this happens)
                        GLib.Idle.Add(delegate {
                            store.Remove(ref iter);
                            newDebaterPath = null;
                            if (IsNotInStore(d))
                            {
                                store.AppendValues(d);
                                SaveDebaters();
                            }
                            else
                            {
                                MiscHelpers.ShowMessage(this, "Debater exists.", MessageType.Error);
                            }
                            UpdateDebatersInfo();
                            btnDebaterAdd.GrabFocus();
                            return(false);
                        });
                    }
                }

                // Gui stuff
                treeDebaters.ColumnsAutosize();
                // ugly method of resorting the TreeSortModel...
                SortType st;
                int      sortColumn;
                model.GetSortColumnId(out sortColumn,
                                      out st);
                if (st == SortType.Descending)
                {
                    model.SetSortColumnId(sortColumn, SortType.Ascending);
                    model.SetSortColumnId(sortColumn, SortType.Descending);
                }
                else
                {
                    model.SetSortColumnId(sortColumn, SortType.Descending);
                    model.SetSortColumnId(sortColumn, SortType.Ascending);
                }

                // save data from store if not adding new debater
                if (newDebaterPath == null)
                {
                    SaveDebaters();
                }
            }
            catch (TargetInvocationException e) {
                MessageDialog md = new MessageDialog(this, DialogFlags.Modal,
                                                     MessageType.Error,
                                                     ButtonsType.OkCancel,
                                                     e.InnerException.Message + ". Try again?");
                md.DefaultResponse = ResponseType.Ok;
                ResponseType r = (ResponseType)md.Run();
                md.Destroy();
                if (r == ResponseType.Ok)
                {
                    // As Idle otherwise Editable isn't destroyed correctly
                    GLib.Idle.Add(delegate {
                        sender.TempEditString = newText;
                        treeDebaters.SetCursor(path, treeDebaters.Columns[colNum], true);
                        return(false);
                    });
                }
                else
                {
                    if (newDebaterPath == null)
                    {
                        return;
                    }
                    iter = TreeIter.Zero;
                    if (store.GetIter(out iter, newDebaterPath))
                    {
                        // remove not finished new debater,
                        // with idle call,
                        // prevents Gtk critical filter model assertion.
                        GLib.Idle.Add(delegate {
                            newDebaterPath = null;
                            store.Remove(ref iter);
                            return(false);
                        });
                    }
                }
            }
        }
        private bool SaveFile(Document document, string?file, FormatDescriptor?format, Window parent)
        {
            if (string.IsNullOrEmpty(file))
            {
                file = document.PathAndFileName;
            }

            if (format == null)
            {
                format = PintaCore.System.ImageFormats.GetFormatByFile(file);
            }

            if (format == null || format.IsReadOnly())
            {
                using var md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, Translations.GetString("Pinta does not support saving images in this file format."), file);
                md.Title     = Translations.GetString("Error");

                md.Run();
                return(false);
            }

            // Commit any pending changes
            PintaCore.Tools.Commit();

            try {
                format.Exporter.Export(document, file, parent);
            } catch (GLib.GException e) {             // Errors from GDK
                if (e.Message == "Image too large to be saved as ICO")
                {
                    string primary   = Translations.GetString("Image too large");
                    string secondary = Translations.GetString("ICO files can not be larger than 255 x 255 pixels.");
                    string message   = string.Format(markup, primary, secondary);

                    using var md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error,
                                                     ButtonsType.Ok, message);

                    md.Run();
                    return(false);
                }
                else if (e.Message.Contains("Permission denied") && e.Message.Contains("Failed to open"))
                {
                    string primary = Translations.GetString("Failed to save image");
                    // Translators: {0} is the name of a file that the user does not have write permission for.
                    string secondary = Translations.GetString("You do not have access to modify '{0}'. The file or folder may be read-only.", file);
                    string message   = string.Format(markup, primary, secondary);

                    using var md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, message);

                    md.Run();
                    return(false);
                }
                else
                {
                    throw;                     // Only catch exceptions we know the reason for
                }
            } catch (OperationCanceledException) {
                return(false);
            }

            document.Filename = Path.GetFileName(file);

            PintaCore.Tools.DoAfterSave(document);

            // Mark the document as clean following the tool's after-save handler, which might
            // adjust history (e.g. undo changes that were committed before saving).
            document.Workspace.History.SetClean();

            //Now the Document has been saved to the file it's associated with in this session.
            document.HasBeenSavedInSession = true;

            return(true);
        }
Esempio n. 55
0
        /// <summary>Función que se ejecuta cuando se pulsa sobre el botón
        /// ok del selector de ficheros a guardar. Pregunta el nombre del
        /// archivo en el que queremos guardar el texto y lo guarda.
        /// </summary>
        /// <param name="o"></param>
        /// <param name="args"></param>

        private void SelectorGuardarOKPulsado(object o, EventArgs args)
        {
            if (Directory.Exists(selectorGuardar.Filename))
            {
                MessageDialog m =
                    new MessageDialog(this,
                                      Gtk.DialogFlags.Modal,
                                      Gtk.MessageType.Warning,
                                      Gtk.ButtonsType.Close,
                                      GetText("Ventana_SeleccionarFichero"));
                m.Run();
                m.Hide();
                return;
            }
            if (File.Exists(selectorGuardar.Filename))
            {
                MessageDialog m =
                    new MessageDialog(this,
                                      Gtk.DialogFlags.Modal,
                                      Gtk.MessageType.Question,
                                      Gtk.ButtonsType.YesNo,
                                      GetText("Ventana_SobreescribirArchivo"));
                int respuesta = m.Run();
                m.Hide();
                if (!
                    (respuesta == (int)Gtk.ResponseType.Yes))
                {
                    return;
                }
            }
            try
            {
                if (!File.Exists(selectorGuardar.Filename))
                {
                    FileStream f = File.Create(selectorGuardar.Filename);
                    f.Close();
                }
            }
            catch (Exception)
            {
                MessageDialog m1 =
                    new MessageDialog(this,
                                      Gtk.DialogFlags.Modal,
                                      Gtk.MessageType.Error,
                                      Gtk.ButtonsType.Close,
                                      GetText("Ventana_ErrorCrearFichero"));
                m1.Run();
                m1.Hide();
                return;
            }
            try
            {
                File.SetCreationTime(selectorGuardar.Filename, DateTime.Now);
            }
            catch (Exception)
            {
                MessageDialog m2 =
                    new MessageDialog(this,
                                      Gtk.DialogFlags.Modal,
                                      Gtk.MessageType.Error,
                                      Gtk.ButtonsType.Close,
                                      GetText("Ventana_ErrorEscritura"));
                m2.Run();
                m2.Hide();
                return;
            }

            //Guardar el texto donde nos digan y poner nombre fichero a eso.
            nombreFichero = selectorGuardar.Filename;

            selectorGuardar.Hide();
            textoCodigo.Modified = true;
            this.VentanaGuardar();
        }
Esempio n. 56
0
        void ejecutar_consulta_reporte(PrintContext context)
        {
            string  tomovalor1             = "";
            int     contadorprocedimientos = 0;
            decimal total = 0;

            Cairo.Context cr     = context.CairoContext;
            Pango.Layout  layout = context.CreatePangoLayout();
            desc      = Pango.FontDescription.FromString("Sans");
            fontSize  = 7.0;                                                                                 layout = context.CreatePangoLayout();
            desc.Size = (int)(fontSize * pangoScale);                                       layout.FontDescription = desc;

            NpgsqlConnection conexion;

            conexion = new NpgsqlConnection(connectionString + nombrebd);
            // Verifica que la base de datos este conectada
            try{
                conexion.Open();
                NpgsqlCommand comando;
                comando             = conexion.CreateCommand();
                comando.CommandText = "SELECT to_char(osiris_erp_abonos.folio_de_servicio,'9999999999') AS folio, " +
                                      "to_char(osiris_erp_abonos.id_abono,'9999999999') AS idabono, " +
                                      "to_char(numero_recibo_caja,'9999999999') AS recibocaja, " +
                                      "id_quien_creo, " +
                                      "to_char(osiris_erp_abonos.monto_de_abono_procedimiento,'9,999,999,999.99') AS abono, " +
                                      "osiris_erp_abonos.concepto_del_abono AS concepto, " +
                                      "osiris_erp_abonos.eliminado, " +
                                      "osiris_erp_abonos.id_quien_elimino, " +
                                      "osiris_erp_abonos.fechahora_eliminado, " +
                                      "to_char(osiris_erp_abonos.fecha_abono,'yyyy-MM-dd') AS fechaabono, " +
                                      "osiris_erp_abonos.id_forma_de_pago, " +
                                      "osiris_erp_forma_de_pago.id_forma_de_pago,descripcion_forma_de_pago AS descripago, " +
                                      "osiris_his_paciente.pid_paciente || '   ' || nombre1_paciente || ' ' || nombre2_paciente || ' ' || apellido_paterno_paciente || ' ' || apellido_materno_paciente AS nombre_completo " +
                                      "FROM osiris_erp_abonos,osiris_erp_forma_de_pago,osiris_erp_cobros_enca,osiris_his_paciente " +
                                      "WHERE osiris_erp_abonos.eliminado = false " +
                                      "AND osiris_erp_abonos.id_forma_de_pago = osiris_erp_forma_de_pago.id_forma_de_pago " +
                                      "AND osiris_erp_abonos.folio_de_servicio = osiris_erp_cobros_enca.folio_de_servicio " +
                                      "AND osiris_erp_cobros_enca.pid_paciente = osiris_his_paciente.pid_paciente " +
                                      " " + query_fechas + " " +
                                      "ORDER BY osiris_erp_abonos.folio_de_servicio;";
                //Console.WriteLine(comando.CommandText);
                NpgsqlDataReader lector = comando.ExecuteReader();
                imprime_encabezado(cr, layout);
                while (lector.Read())
                {
                    cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);           layout.SetText((string)lector["folio"].ToString().Trim());     Pango.CairoHelper.ShowLayout(cr, layout);
                    cr.MoveTo(40 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);           layout.SetText(string.Format("{0:C}", decimal.Parse(lector["abono"].ToString())));       Pango.CairoHelper.ShowLayout(cr, layout);
                    cr.MoveTo(93 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);           layout.SetText(lector["fechaabono"].ToString());        Pango.CairoHelper.ShowLayout(cr, layout);
                    cr.MoveTo(125 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);          layout.SetText(lector["recibocaja"].ToString());        Pango.CairoHelper.ShowLayout(cr, layout);
                    cr.MoveTo(171 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);          layout.SetText(lector["nombre_completo"].ToString().Trim());    Pango.CairoHelper.ShowLayout(cr, layout);

                    comienzo_linea         += separacion_linea;
                    total                  += decimal.Parse((string)lector["abono"]);
                    contadorprocedimientos += 1;

                    /*
                     * tomovalor1 = (string) lector["concepto"];
                     * if(tomovalor1.Length > 40)
                     * {
                     *      tomovalor1 = tomovalor1.Substring(0,40);
                     * }
                     * ContextoImp.MoveTo(351, filas);		ContextoImp.Show(tomovalor1);
                     * ContextoImp.MoveTo(501, filas);		ContextoImp.Show((string) lector["descripago"]);
                     */
                }
                comienzo_linea += separacion_linea;
                cr.MoveTo(300 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);          layout.SetText("TOTAL DE PAGOS/ABONOS " + string.Format("{0:C}", decimal.Parse(total.ToString())));        Pango.CairoHelper.ShowLayout(cr, layout);
                comienzo_linea += separacion_linea;
                cr.MoveTo(300 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows);          layout.SetText("TOTAL N° ATENCION " + contadorprocedimientos.ToString()); Pango.CairoHelper.ShowLayout(cr, layout);
            }catch (NpgsqlException ex) {
                Console.WriteLine("PostgresSQL error: {0}", ex.Message);
                MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.DestroyWithParent,
                                                              MessageType.Error, ButtonsType.Close, "PostgresSQL error: {0}", ex.Message);
                msgBoxError.Run();             msgBoxError.Destroy();
            }
        }
Esempio n. 57
0
        public string GetPatchPoint()
        {
            string   newWeatherPath = null;
            string   dest           = PathUtilities.GetAbsolutePath(entryFilePath.Text, this.explorerPresenter.ApsimXFile.FileName);
            DateTime startDate      = calendarStart.Date;

            if (startDate.Year < 1889)
            {
                ShowMessage(MessageType.Warning, "SILO data is not available before 1889", "Invalid start date");
                return(null);
            }
            DateTime endDate = calendarEnd.Date;

            if (endDate.CompareTo(DateTime.Today) >= 0)
            {
                ShowMessage(MessageType.Warning, "SILO data end date can be no later than yesterday", "Invalid end date");
                return(null);
            }
            if (endDate.CompareTo(startDate) < 0)
            {
                ShowMessage(MessageType.Warning, "The end date must be after the start date!", "Invalid dates");
                return(null);
            }
            if (String.IsNullOrWhiteSpace(entryEmail.Text))
            {
                ShowMessage(MessageType.Warning, "The SILO data API requires you to provide your e-mail address", "E-mail address required");
                return(null);
            }

            // Patch point get a bit complicated. We need a BOM station number, but can't really expect the user
            // to know that in advance. So what we can attempt to do is use the provided lat and long in the geocoding service
            // to get us a placename, then use the SILO name search API to find a list of stations for us.
            // If we get multiple stations, we let the user choose the one they wish to use.

            string url = googleGeocodingApi + "latlng=" + entryLatitude.Text + ',' + entryLongitude.Text;

            try
            {
                MemoryStream stream = WebUtilities.ExtractDataFromURL(url);
                stream.Position = 0;
                JsonTextReader reader = new JsonTextReader(new StreamReader(stream));
                // Parsing the JSON gets a little tricky with a forward-reading parser. We're trying to track
                // down a "short_name" address component of "locality" type (I guess).
                string locName = "";
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.PropertyName && reader.Value.Equals("address_components"))
                    {
                        reader.Read();
                        if (reader.TokenType == JsonToken.StartArray)
                        {
                            JArray arr = JArray.Load(reader);
                            foreach (JToken token in arr)
                            {
                                JToken typesToken = token.Last;
                                JArray typesArray = typesToken.First as JArray;
                                for (int i = 0; i < typesArray.Count; i++)
                                {
                                    if (typesArray[i].ToString() == "locality")
                                    {
                                        locName = token["short_name"].ToString();
                                        break;
                                    }
                                }
                                if (!string.IsNullOrEmpty(locName))
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(locName))
                    {
                        break;
                    }
                }
                if (string.IsNullOrEmpty(locName))
                {
                    ShowMessage(MessageType.Error, "Unable to find a name key for the specified location", "Error determining location");
                    return(null);
                }
                int stationNumber = -1;
                if (locName.Contains(" ")) // the SILO API doesn't handle spaces well
                {
                    Regex regex = new Regex(" .");
                    locName = regex.Replace(locName, "_");
                }
                string       stationUrl    = String.Format("https://www.longpaddock.qld.gov.au/cgi-bin/silo/PatchedPointDataset.php?format=name&nameFrag={0}", locName);
                MemoryStream stationStream = WebUtilities.ExtractDataFromURL(stationUrl);
                stationStream.Position = 0;
                StreamReader streamReader = new StreamReader(stationStream);
                string       stationInfo  = streamReader.ReadToEnd();
                string[]     stationLines = stationInfo.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                if (stationLines.Length == 0)
                {
                    ShowMessage(MessageType.Error, "Unable to find a BOM station for this location", "Cannot find station");
                    return(null);
                }
                if (stationLines.Length == 1)
                {
                    string[] lineInfo = stationLines[0].Split('|');
                    stationNumber = Int32.Parse(lineInfo[0]);
                }
                else
                {
                    MessageDialog md = new MessageDialog(owningView.MainWidget.Toplevel as Window, DialogFlags.Modal, MessageType.Question, ButtonsType.OkCancel,
                                                         "Which station do you wish to use?");
                    md.Title = "Select BOM Station";
                    Gtk.TreeView tree = new Gtk.TreeView();
                    ListStore    list = new ListStore(typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string));
                    tree.AppendColumn("Number", new CellRendererText(), "text", 0);
                    tree.AppendColumn("Name", new CellRendererText(), "text", 1);
                    tree.AppendColumn("Latitude", new CellRendererText(), "text", 2);
                    tree.AppendColumn("Longitude", new CellRendererText(), "text", 3);
                    tree.AppendColumn("State", new CellRendererText(), "text", 4);
                    tree.AppendColumn("Elevation", new CellRendererText(), "text", 5);
                    tree.AppendColumn("Notes", new CellRendererText(), "text", 6);
                    foreach (string stationLine in stationLines)
                    {
                        string[] lineInfo = stationLine.Split('|');
                        list.AppendValues(lineInfo);
                    }
                    tree.Model         = list;
                    tree.RowActivated += OnPatchPointSoilSelected;

                    Box box = md.ContentArea;

                    box.PackStart(tree, true, true, 5);
                    box.ShowAll();

                    ResponseType result = (ResponseType)md.Run();
                    if (result == ResponseType.Ok)
                    {
                        TreeIter iter;
                        tree.Selection.GetSelected(out iter);
                        string stationString = (string)list.GetValue(iter, 0);
                        stationNumber = Int32.Parse(stationString);
                    }
                    md.Dispose();
                }
                if (stationNumber >= 0) // Phew! We finally have a station number. Now fetch the data.
                {
                    string pointUrl = String.Format("https://www.longpaddock.qld.gov.au/cgi-bin/silo/PatchedPointDataset.php?start={0:yyyyMMdd}&finish={1:yyyyMMdd}&station={2}&format=apsim&username={3}",
                                                    startDate, endDate, stationNumber, System.Net.WebUtility.UrlEncode(entryEmail.Text));
                    MemoryStream pointStream = WebUtilities.ExtractDataFromURL(pointUrl);
                    pointStream.Seek(0, SeekOrigin.Begin);
                    string headerLine = new StreamReader(pointStream).ReadLine();
                    pointStream.Seek(0, SeekOrigin.Begin);
                    if (headerLine.StartsWith("[weather.met.weather]"))
                    {
                        using (FileStream fs = new FileStream(dest, FileMode.Create))
                        {
                            pointStream.CopyTo(fs);
                            fs.Flush();
                        }
                        if (File.Exists(dest))
                        {
                            newWeatherPath = dest;
                        }
                    }
                    else
                    {
                        ShowMessage(MessageType.Error, new StreamReader(pointStream).ReadToEnd(), "Not valid APSIM weather data");
                    }
                }
            }
            catch (Exception err)
            {
                ShowMessage(MessageType.Error, err.Message, "Error");
            }
            return(newWeatherPath);
        }
Esempio n. 58
0
        private void transactionList_ButtonPress(object o, ButtonPressEventArgs e)
        {
            if (e.Event.Button == 3)
            {
                Gtk.TreeIter selected;
                if (transactionList.Selection.GetSelected(out selected))
                {
                    string transactionStatus = (string)transactionListStore.GetValue(selected, 0);
                    Guid   transactionGuid   = Guid.Parse((string)transactionListStore.GetValue(selected, 5));

                    Menu m = new Menu();

                    MenuItem executeItem = new MenuItem("Execute");
                    executeItem.ButtonPressEvent += new ButtonPressEventHandler(delegate(object sender, ButtonPressEventArgs ee)
                    {
                        for (int i = 0; i < db.accounts[ac].transactions.Count; i++)
                        {
                            Transaction t = db.accounts[ac].transactions[i];
                            if (t.id == transactionGuid)
                            {
                                t.status = TransactionStatus.Completed;

                                if (t.intern != Guid.Empty)
                                {
                                    int account         = 0;
                                    Transaction internT = null;
                                    foreach (Account a in db.accounts)
                                    {
                                        if (a.GetTransaction(t.intern) != null)
                                        {
                                            internT = a.GetTransaction(t.intern);
                                            break;
                                        }
                                        account++;
                                    }
                                    internT.status = TransactionStatus.Completed;
                                }

                                foreach (Account ac in db.accounts)
                                {
                                    ac.RecalculateBalance();
                                }

                                UpdateUI();
                                parent.updateUi = true;
                                db.Save(dbPath);
                                return;
                            }
                        }
                    });

                    MenuItem skipItem = new MenuItem("Skip");
                    skipItem.ButtonPressEvent += new ButtonPressEventHandler(delegate(object sender, ButtonPressEventArgs ee)
                    {
                        for (int i = 0; i < db.accounts[ac].transactions.Count; i++)
                        {
                            Transaction t = db.accounts[ac].transactions[i];
                            if (t.id == transactionGuid)
                            {
                                t.status = TransactionStatus.Skipped;

                                if (t.intern != Guid.Empty)
                                {
                                    int account         = 0;
                                    Transaction internT = null;
                                    foreach (Account a in db.accounts)
                                    {
                                        if (a.GetTransaction(t.intern) != null)
                                        {
                                            internT = a.GetTransaction(t.intern);
                                            break;
                                        }
                                        account++;
                                    }
                                    internT.status = TransactionStatus.Skipped;
                                }

                                foreach (Account ac in db.accounts)
                                {
                                    ac.RecalculateBalance();
                                }

                                UpdateUI();
                                parent.updateUi = true;
                                db.Save(dbPath);
                                return;
                            }
                        }
                    });

                    SeparatorMenuItem s = new SeparatorMenuItem();

                    MenuItem editItem = new MenuItem("Edit");
                    editItem.ButtonPressEvent += new ButtonPressEventHandler(delegate(object sender, ButtonPressEventArgs ee)
                    {
                        //TODO: Make this work
                    });

                    MenuItem deleteItem = new MenuItem("Delete");
                    deleteItem.ButtonPressEvent += new ButtonPressEventHandler(delegate(object sender, ButtonPressEventArgs ee)
                    {
                        string msg            = "Are you sure you want to delete this transaction?";
                        MessageDialog msgdiag = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, false, msg);
                        ResponseType r        = (ResponseType)msgdiag.Run();
                        msgdiag.Destroy();

                        if (r == ResponseType.Yes)
                        {
                            for (int i = 0; i < db.accounts[ac].transactions.Count; i++)
                            {
                                Transaction t = db.accounts[ac].transactions[i];
                                if (t.id == transactionGuid)
                                {
                                    if (t.intern != Guid.Empty)
                                    {
                                        msg     = "The payee in this transaction is internal, do you want to delete the payee transaction too?";
                                        msgdiag = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, false, msg);
                                        r       = (ResponseType)msgdiag.Run();
                                        msgdiag.Destroy();

                                        if (r == ResponseType.Yes)
                                        {
                                            int account         = 0;
                                            Transaction internT = null;
                                            foreach (Account a in db.accounts)
                                            {
                                                if (a.GetTransaction(t.intern) != null)
                                                {
                                                    internT = a.GetTransaction(t.intern);
                                                    break;
                                                }
                                                account++;
                                            }

                                            if (internT != null)
                                            {
                                                db.accounts[account].transactions.Remove(internT);
                                            }
                                            else
                                            {
                                                msg     = "Linked transaction could not be found, it's probably already gone.";
                                                msgdiag = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, false, msg);
                                                r       = (ResponseType)msgdiag.Run();
                                                msgdiag.Destroy();
                                            }
                                        }
                                        else if (r == ResponseType.No)
                                        {
                                            int account         = 0;
                                            Transaction internT = null;
                                            foreach (Account a in db.accounts)
                                            {
                                                if (a.GetTransaction(t.intern) != null)
                                                {
                                                    internT = a.GetTransaction(t.intern);
                                                    break;
                                                }
                                                account++;
                                            }
                                            internT.intern = Guid.Empty;
                                        }
                                    }

                                    db.accounts[ac].transactions.Remove(t);

                                    foreach (Account ac in db.accounts)
                                    {
                                        ac.RecalculateBalance();
                                    }

                                    UpdateUI();
                                    parent.updateUi = true;
                                    db.Save(dbPath);
                                    return;
                                }
                            }
                        }
                    });

                    executeItem.Sensitive = false;
                    skipItem.Sensitive    = false;

                    if (transactionStatus == "OnHold")
                    {
                        executeItem.Sensitive = true;
                    }
                    else
                    {
                        executeItem.Sensitive = false;
                    }

                    if (transactionStatus == "Scheduled")
                    {
                        executeItem.Sensitive = true;
                        skipItem.Sensitive    = true;
                    }
                    else
                    {
                        skipItem.Sensitive = false;
                    }

                    m.Add(executeItem);
                    m.Add(skipItem);
                    m.Add(s);
                    m.Add(editItem);
                    m.Add(deleteItem);

                    m.ShowAll();
                    m.Popup();
                }
            }
            else if (((Gdk.EventButton)e.Event).Type == Gdk.EventType.TwoButtonPress)
            {
            }
        }
Esempio n. 59
0
        protected void OnBtnDatabaseClicked(object sender, EventArgs e)
        {
            FileChooserDialog dlgFile =
                new FileChooserDialog("Choose database to open/create", this, FileChooserAction.Save, "Cancel",
                                      ResponseType.Cancel, "Choose", ResponseType.Accept)
            {
                SelectMultiple = false
            };

            dlgFile.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            dlgFile.SetFilename("Core.db");

            if (dlgFile.Run() == (int)ResponseType.Accept)
            {
                if (File.Exists(dlgFile.Filename))
                {
                    DbCore dbCore = new SQLite();
                    bool   notDb  = false;

                    try { notDb |= !dbCore.OpenDb(dlgFile.Filename, null, null, null); }
                    catch { notDb = true; }

                    if (notDb)
                    {
                        MessageDialog dlgMsg = new MessageDialog(this, DialogFlags.Modal, MessageType.Error,
                                                                 ButtonsType.Ok,
                                                                 "Cannot open specified file as a database, please choose another.");
                        dlgMsg.Run();
                        dlgMsg.Destroy();
                        dlgFile.Destroy();
                        return;
                    }

                    dbCore.CloseDb();
                }
                else
                {
                    DbCore dbCore = new SQLite();
                    bool   notDb  = false;

                    try { notDb |= !dbCore.CreateDb(dlgFile.Filename, null, null, null); }
                    catch { notDb = true; }

                    if (notDb)
                    {
                        MessageDialog dlgMsg = new MessageDialog(this, DialogFlags.Modal, MessageType.Error,
                                                                 ButtonsType.Ok,
                                                                 "Cannot create a database in the specified file as a database.");
                        dlgMsg.Run();
                        dlgMsg.Destroy();
                        dlgFile.Destroy();
                        return;
                    }

                    dbCore.CloseDb();
                }

                txtDatabase.Text = dlgFile.Filename;
            }

            dlgFile.Destroy();
        }
Esempio n. 60
0
    protected void ConnectHandler(object sender, EventArgs e)
    {
        // Show message to user with instructions on connecting the wiimote
        MessageDialog connect_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.OkCancel,
                                                     "Please put your wiimote in discovery mode.\n\nPress 1 + 2 and press OK, then wait for LED 1 to light up.\n\nThis action will take up to 10 seconds.\n\nPlease make sure that your bluetooth adapter is turned ON.");

        connect_md.Title = "Connect";
        connect_md.Image = new Image(Gdk.Pixbuf.LoadFromResource("TRAB_IHC.res.ConnectInstruction.png"));
        connect_md.ShowAll();
        int cd_result = connect_md.Run(); // Get user selection

        connect_md.Destroy();

        if (cd_result == -5) // Dialog OK
        {
            // Show message informing user that the wiimote is being searched
            MessageDialog searching_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.None, "Searching...")
            {
                Title = "Searching..."
            };

            // Start thread to connect to wiimotes
            Thread connect_manager = new Thread(() => { connection_status = ConnectWiimotes(); });
            connect_manager.Start();

            // While still attempting to connect
            while (connection_status == -5)
            {
                searching_md.ShowAll();
            }
            searching_md.Destroy();

            // If connection sucessful
            if (connection_status > 0)
            {
                // Show message to user with instructions on calibrating the gyroscope
                MessageDialog gyro_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                          "Gyroscope calibration will now begin.\n\nPlease place your wiimote face up on a flat surface and press OK.\n\nThis action will take up to 3 seconds.\n\nPlease do not touch or move the wiimote during this process.");
                gyro_md.Title = "Gyroscope calibration";
                gyro_md.Image = new Gtk.Image(Gdk.Pixbuf.LoadFromResource("TRAB_IHC.res.CalibrateInstruction.png"));

                gyro_md.ShowAll();
                gyro_md.Run();
                gyro_md.Destroy();

                // Enable motion sensing and calibrate the gyroscope
                int status = EnableMotionSensing();

                // Show success message to user
                MessageDialog success_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok,
                                                             "Wiimote connected!\n\nYou can now switch to game window and start playing!");
                success_md.ShowAll();
                success_md.Run();
                success_md.Destroy();

                // Enable the calibration and disconnect buttons, as well as the feedback frame
                // Disable the connect button
                calibrateButton.Sensitive  = true;
                disconnectButton.Sensitive = true;
                feedbackFrame.Sensitive    = true;
                connectButton.Sensitive    = false;
                DisconnectAction.Sensitive = true;
                ConnectAction.Sensitive    = false;

                // Spawn a thread to update the graphics for the taiko drum
                ThreadStart work2        = UpdateDrumGraphic;
                Thread      drum_updater = new Thread(work2);
                drum_updater.Start();
            }
            else
            {
                // Show message to user informing that no wiimotes were detected / connected
                MessageDialog error_md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok,
                                                           "No wiimotes were detected.\n\nPlease make sure that your bluetooth adapter is turned ON.");
                error_md.Title = "Connection error";
                error_md.Image = new Gtk.Image(Gdk.Pixbuf.LoadFromResource("TRAB_IHC.res.BluetoothError.png"));

                error_md.ShowAll();
                error_md.Run();
                error_md.Destroy();

                // Reset connected wiimotes to searching
                connection_status = -5;
            }
        }
    }