void Button_end(object sender, PageEventArgs e)
        {
            var schema = txtSchema.Text == "" ? "public" : txtSchema.Text;
            var importdestinationPath = "";
            var isMySql = cmbType.SelectedIndex == 0;

            string[] param = { txtHote.Text, txtUtil.Text, txtMdp.Text, txtBase.Text, schema };

            var mainConn = new ConnectionProperties
            {
                Host       = txtHote.Text,
                User       = txtUtil.Text,
                Password   = txtMdp.Text,
                Database   = txtBase.Text,
                SearchPath = new string[] { schema, "public" }
            };

            //var connectionString = cmbType.SelectedIndex == 0
            //    ? string.Format("Datasource={0};uid={1};pwd={2};", param)
            //    : string.Format("User ID={1};Password={2};Host={0};Port=5432;Database={3};SearchPath={4},public;", param);

            var tempPath = Path.GetTempPath() + Guid.NewGuid();// used for import only



            if (Program.AppSet == null)
            {
                Program.AppSet = new AppSetting(); //if no default properties
            }
            if (_fromImport)                       //unzip file to temp file and load exported config
            {
                // select file to import
                var fd = new OpenFileDialog
                {
                    Title = Resources.SelectImportFile,

                    CheckFileExists = true,
                    CheckPathExists = true,

                    DefaultExt       = "twz",
                    Filter           = "twz files (*.twz)|*.twz",
                    FilterIndex      = 2,
                    RestoreDirectory = true,

                    ReadOnlyChecked = true,
                    ShowReadOnly    = true
                };

                var result = fd.ShowDialog();
                if (result != DialogResult.OK)
                {
                    return;
                }

                // select destination folder

                var folderDlg = new FolderBrowserDialog
                {
                    Description         = "Selectionnez le répertoire de destination du sit web",
                    ShowNewFolderButton = true
                };

                result = folderDlg.ShowDialog();
                if (result != DialogResult.OK)
                {
                    return;
                }

                importdestinationPath = folderDlg.SelectedPath;


                _waitingForm = new WaitingForm(PrepareImportWorker)
                {
                    Text        = Resources.ImportPrepare,
                    progressBar = { Style = ProgressBarStyle.Marquee }
                };

                _waitingForm.Wr.RunWorkerAsync(new object[] { fd.FileName, tempPath });

                _waitingForm.ShowDialog();

                mainConn.SearchPath = new string[] { Program.AppSet.Schema, "public" };
            }

            //set app setting parameter

            if (!_fromImport)
            {
                Program.AppSet.Titre = cmbType.SelectedIndex == 0 ? txtBase.Text : schema;
            }

            Program.AppSet.ConnectionString = mainConn.GetConnectionString(isMySql);//connectionString;
            Program.AppSet.ProviderType     = cmbType.SelectedIndex == 0 ? Provider.MySql : Provider.Postgres;

            Program.AppSet.identParam = cmbType.SelectedIndex == 0 ? "?" : "@";
            Program.AppSet.sqlDebug   = "oui";

            Tools.SetDefaultProviderFromAppSet();

            SqlCommands.Provider = cmbType.SelectedIndex == 0 ? Provider.MySql : Provider.Postgres;

            //for postgres verify database exist if not create
            if (Program.AppSet.ProviderType == Provider.Postgres)
            {
                var cs = string.Format("User ID={1};Password={2};Host={0};Port=5432;", param);
                if (!dbExist(txtBase.Text, cs))
                {
                    if (MetroMessageBox.Show(this, Resources.DataBaseNotExist, Resources.Erreur, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error)
                        != DialogResult.Yes)
                    {
                        return;
                    }
                    dbCreate(txtBase.Text, cs);
                }
            }


            //Add schema to database

            if (!_fromImport && (Program.AppSet.ProviderType == Provider.Postgres && schemaExist(schema)))
            {
                string err;

                if (MetroMessageBox.Show(this, Resources.SchemaAlreadyExist, Resources.Erreur, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error)
                    != DialogResult.Yes)
                {
                    return;
                }

                if (MetroMessageBox.Show(this, Resources.ConfirmDelete, Resources.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    != DialogResult.Yes)
                {
                    return;
                }

                DataTools.Command($"DROP SCHEMA {schema} CASCADE;", null, Program.AppSet.ConnectionString, out err);

                if (!string.IsNullOrEmpty(err))
                {
                    MetroMessageBox.Show(this, string.Format(Resources.ErrorMessage, err), Resources.Erreur, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            var connectionString = mainConn.GetConnectionString(isMySql);

            if (!_fromImport)
            {
                Program.AppSet.Schema = schema;
            }

            if (Program.AppSet.ProviderType == Provider.Postgres)
            {//postgres
                param    = new string[] { txtSchema.Text };
                e.Cancel = !WizardSQLHelper.ExecuteFromFile("schema.sql", param, connectionString, this);
                if (e.Cancel)
                {
                    return;          // stop on sql error
                }
            }
            else
            {//mysql
                param    = new string[] { txtBase.Text };
                e.Cancel = !WizardSQLHelper.ExecuteFromFile("schema.sql", param, mainConn.GetConnectionString(isMySql), this);
                if (e.Cancel)
                {
                    return;          // stop on sql error
                }
                Program.AppSet.ConnectionString = connectionString + "Database=" + txtBase.Text + ";";;
            }

            // add tabloid table to database
            try
            {
                if (_fromImport)//unzip file to temp file and load exported config
                {
                    _waitingForm = new WaitingForm(ImportWorker)
                    {
                        Text        = Resources.dbImport,
                        progressBar = { Style = ProgressBarStyle.Marquee }
                    };

                    var conn = new ConnectionProperties
                    {
                        Host     = txtHote.Text,
                        Port     = "5432",
                        User     = txtUtil.Text,
                        Password = txtMdp.Text,
                        Database = txtBase.Text
                    };

                    _waitingForm.Wr.RunWorkerAsync(new object[] { tempPath, conn, importdestinationPath });

                    _waitingForm.ShowDialog();
                }
                else
                if (!TabloidTables.CreateTable(TabloidTables.TabloidTablesArray, connectionString, this))//create tabloid table in base
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                MetroMessageBox.Show(this, ex.ToString(), Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //add user
            if (_fromImport)
            {
                var utilFrm = new UtilEditor();

                utilFrm.btnCancel.Enabled     = false;
                utilFrm.cmbAuth.SelectedIndex = 1;
                utilFrm.cmbAuth.Enabled       = false;

                if (utilFrm.ShowDialog() == DialogResult.OK)//for user table need to ask for user 0
                {
                    TabloidConfig.Config.updateCurrentKey(Program.AppSet.grainDeSable);
                    var keyParam = GenericParameter.Get("id_utilisateur", DbType.Int32, null);
                    var sql      = $"INSERT INTO utilisateurs(logon, nom, prenom, mail, password, auteur_utilisateurs, datemaj_utilisateurs, deleted_utilisateurs, debutsession, finsession) VALUES('{utilFrm.txtLogin.Text}', '{utilFrm.txtNom.Text}', '{utilFrm.txtPrenom.Text}', '{utilFrm.txtMail.Text}', '{Tabloid.Classes.Tools.SecurityHelper.EncryptPassword(utilFrm.txtMdp1.Text)}', NULL, NULL, 0, now(), NULL)";
                    sql = sql + string.Format(SqlConverter.GetSql(SqlConverter.SqlType.InsertCommandKeyOut), "id_utilisateur");

                    var id = DataTools.ScalarCommand(sql, new[] { keyParam }, mainConn.GetConnectionString(isMySql));

                    sql = $"INSERT INTO lst_roles(utilisateurs_id, roles_id) VALUES({id}, 1);";

                    DataTools.Command(sql, null, mainConn.GetConnectionString(isMySql));
                }
            }
            else
            {
                //open project properties form
                Tools.EditSetting(_configFiles);
            }
        }
示例#2
0
        private void btn_Click(object sender, EventArgs e)
        {
            var error = false;

            progressBar1.Maximum = 100;
            progressBar1.Value   = 0;

            var schema = txtSchema.Text == "" ? "public" : txtSchema.Text;

            object[] param = { txtHote.Text, txtUtil.Text, txtMdp.Text, txtBase.Text, schema };

            var connectionString = cmbType.SelectedIndex == 0
                ? string.Format("Datasource={0};Database={3};uid={1};pwd={2};", param)
                : string.Format("User ID={1};Password={2};Host={0};Port=5432;Database={3};SearchPath={4},public;", param);

            Program.AppSet = new AppSetting
            {
                ConnectionString = connectionString,
                ProviderType     = cmbType.SelectedIndex == 0 ? Provider.MySql : Provider.Postgres,
                Titre            = txtBase.Text,
                identParam       = cmbType.SelectedIndex == 0 ? "?" : "@",
                sqlDebug         = "oui"
            };

            Tools.SetDefaultProviderFromAppSet();

            lblState.Text = Resources.NewFromBaseForm_btn_Click_Récupération_des_Tables;
            lblState.Refresh();

            SqlCommands.Provider  = cmbType.SelectedIndex == 0 ? Provider.MySql : Provider.Postgres;
            Program.AppSet.Schema = schema;

            string lastError;

            var dt = DataTools.Data(SqlCommands.SqlGetTable(), connectionString, out lastError);

            if (dt == null)
            {
                MetroMessageBox.Show(this, Resources.NewFromBaseForm_btn_Click_ + lastError, Resources.Erreur,
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!string.IsNullOrEmpty(lastError))
            {
                lblState.Text = lastError;
                error         = true;
            }
            else
            {
                TabloidConfig.Config = new TabloidConfig();

                TabloidConfig.Config.TabloidConfigApp.UseLockDatabaseField = chkLockInDB.Checked;

                var avt = new ArrayVerify();

                var config = new BuildFromBase.BaseImporterConfig
                {
                    RemoveTableName    = chkSuppNomTable.Checked,
                    ToUpperCase        = chkCasse.Checked,
                    ReplaceUnderscrore = chkUnderscrore.Checked,

                    ConnectionString = connectionString
                };

                if (dt.Rows.Count > 0)
                {
                    TabloidFields.TabloidFieldsArray = null;
                    //Program.AppSet.pageDefaut = "/tabloid/BSliste.aspx?table=" +
                    AppSetting.setDefaultPage(dt.Rows[0][0].ToString());
                    var delta = 100 / dt.Rows.Count;

                    //read Tables
                    foreach (DataRow dtr in dt.Rows)
                    {
                        progressBar1.Value += delta;
                        progressBar1.Refresh();

                        var dtName = dtr[0].ToString();

                        var tableConfig = new TabloidConfigView();

                        try
                        {
                            BuildFromBase.GetTable(this, dtName, schema, ref tableConfig, ref avt, config);
                            TabloidConfig.Config.Views.Add(tableConfig);
                        }
                        catch (Exception ex)
                        {
                            lblState.Text = ex.ToString();
                        }
                    }

                    if (error)
                    {
                        return;
                    }
                }

                //verify tabloid table existance
                if (!avt.IsThereAll(TabloidTables.TabloidTablesArray.Count()))
                {
                    var l = avt.NotInIndex(TabloidTables.TabloidTablesArray.Count()); //list unaviable tables
                    var r = DialogResult.Yes;

                    if (!chkAutoTable.Checked)
                    {
                        //Show message
                        var strCh = string.Join("\n\t- ",
                                                TabloidTables.TabloidTablesArray
                                                .Where((f, index) => l.Any(i => i == index))
                                                .Select((x, index) => x.Name).ToArray());

                        r = MetroMessageBox.Show(this,
                                                 string.Format(
                                                     Resources.NewFromBaseForm_tables_inutiles,
                                                     strCh),
                                                 Resources.Information,
                                                 MessageBoxButtons.YesNo,
                                                 MessageBoxIcon.Exclamation);
                    }

                    if (r == DialogResult.Yes)
                    {
                        var toCreate = TabloidTables.TabloidTablesArray
                                       .Where((f, index) => l.Any(i => i == index))
                                       .ToList();

                        TabloidTables.CreateTable(
                            toCreate, connectionString, this);

                        foreach (var t in toCreate)// table to config
                        {
                            var tableConfig = new TabloidConfigView();
                            try {
                                BuildFromBase.GetTable(this, t.Name, schema, ref tableConfig, ref avt, config);
                                TabloidConfig.Config.Views.Add(tableConfig);
                            }
                            catch (Exception ex)
                            {
                                lblState.Text = ex.ToString();
                            }
                        }
                    }
                }

                OlStyleCollection.olStyles = new List <OlStyle>();

                DialogResult = DialogResult.OK;
                Close();
            }
        }
示例#3
0
        /// <summary>
        /// verify tabloid table aviability
        /// </summary>
        /// <param name="tableName">table to search</param>
        /// <param name="schema"></param>
        /// <param name="tableConfig"></param>
        /// <param name="avt"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static bool GetTable(IWin32Window own, string tableName, string schema, ref TabloidConfigView tableConfig, ref ArrayVerify avt, BaseImporterConfig config)
        {
            var indexTable = TabloidTables.IsTabloidTable(tableName, ref avt);
            var toShow     = indexTable == -1;

            if (!toShow)                                                       //this is a tabloid table
            {
                toShow = !TabloidTables.TabloidTablesArray[indexTable].Hidden; //for tabloid table verify hidden propertie
            }
            if (toShow)                                                        //this is not a tabloid table
            {
                tableConfig        = new TabloidConfigView();
                tableConfig.Nom    = tableConfig.Titre = tableName;
                tableConfig.Titre  = ModifyTitle(tableConfig.Titre, tableName, config);
                tableConfig.Schema = schema;

                string lastError;

                var dc = DataTools.Data(SqlCommands.SqlGetColums(tableName), config.ConnectionString, out lastError);//013

                if (!string.IsNullOrEmpty(lastError))
                {
                    throw new Exception(lastError);
                    //lblState.Text = lastError;
                    return(false);
                }
                //read Fields
                var avc  = new ArrayVerify();
                var cmpt = 0;

                foreach (DataRow dcr in dc.Rows)
                {
                    cmpt++;

                    if (TabloidFields.IstabloidField(dcr[0].ToString(), ref avc) == -1)
                    {
                        var colonneConfig = new TabloidConfigColonne();

                        if (dcr[3].ToString().StartsWith("PRI", StringComparison.InvariantCulture))
                        {
                            tableConfig.DbKey = dcr[0].ToString();
                        }
                        else
                        {
                            colonneConfig.Nom   = "C" + cmpt;
                            colonneConfig.Champ = colonneConfig.Titre = dcr[0].ToString();

                            colonneConfig.Titre = ModifyTitle(colonneConfig.Titre, tableName, config);



                            colonneConfig.Type = dataHelper.DbTypeConverter.Convert(dcr[1].ToString(), SqlCommands.Provider.ToString());

                            tableConfig.Colonnes.Add(colonneConfig);
                        }
                    }
                }

                if (!avc.IsThereAll(TabloidFields.TabloidFieldsArray.Count()))        //is all tabloid field there?
                {
                    var l = avc.NotInIndex(TabloidFields.TabloidFieldsArray.Count()); //list unaviable fields
                    var r = DialogResult.Yes;

                    if (!config.CreateAuto)
                    {
                        //Show message
                        var strCh = string.Join("\n\t- ",
                                                TabloidFields.TabloidFieldsArray
                                                .Where((f, index) => l.Any(i => i == index))
                                                .Select((x, index) => x.Name + "_" + tableName).ToArray());

                        r = MetroMessageBox.Show(own,
                                                 string.Format(
                                                     Resources.NewFromBaseForm_GetTable_,
                                                     tableName, strCh),
                                                 Resources.Information,
                                                 MessageBoxButtons.YesNo,
                                                 MessageBoxIcon.Exclamation);
                    }

                    if (r == DialogResult.Yes)
                    {
                        TabloidFields.CreateField(
                            TabloidFields.TabloidFieldsArray
                            .Where((f, index) => l.Any(i => i == index))
                            .ToList(), tableName, schema, config.ConnectionString);
                    }
                }

                var jr = WizardSQLHelper.SetJoinFromConstraint(tableConfig, config.ConnectionString, ref lastError); //getting join

                if (jr != null && !string.IsNullOrEmpty(lastError))
                {
                    throw new Exception(lastError);                                               //lblState.Text = lastError;
                }
                return(jr != null);
            }

            return(false);
        }