//créer dans la liste {0} les élément à partir de {1}
        //à la création d'un enregistrement de {0} compléter la liste {1} :
        private void Info_CloseFromNext(object sender, PageEventArgs e)
        {
            // add insertselect function
            e.Cancel = !WizardSQLHelper.ExecuteFromFile("functions\\insertselect.sql", new string[] { _view.Schema }, Program.AppSet.ConnectionString, this);

            var where = string.IsNullOrEmpty(txtWhere.Text) ? "'1=1'" : txtWhere.Text;

            var dest = ((TabloidConfigJointure)cmbListe.SelectedItem);

            var src = ((TabloidConfigJointure)cmbSrc.SelectedItem);

            var srcFields  = $"concat('{src.DbKey},',New.{_view.DbKey})";
            var destFields = $"'{src.ChampDeRef},{dest.ChampDeRef2}'";

            var function = $"PERFORM {_view.Schema}.insertselect('{_view.Schema}.{src.NomTable}',{where},{srcFields},'{_view.Schema}.{dest.NomTable}',{destFields});";

            if (!string.IsNullOrEmpty(txtIf.Text))
            {
                function = $"if {txtIf.Text} Then " + function + "end if;";
            }


            var param = new string[] {
                _view.Schema,
                triggerName + _view.NomTable,
                _view.NomTable,
                "AFTER INSERT",
                _view.Schema + "." + triggerName + _view.NomTable,
                function
            };

            e.Cancel = !WizardSQLHelper.ExecuteFromFile("trigger.sql", param, Program.AppSet.ConnectionString, this);
        }
        /// <summary>
        ///     Create table in base from a list
        /// </summary>
        /// <param name="tl"></param>
        /// <param name="connectionString"></param>
        public static bool CreateTable(IEnumerable <Table> tl, string connectionString, IWin32Window own)
        {
            foreach (var t in tl)
            {
                if (string.Equals(t.Name, "utilisateurs", StringComparison.InvariantCultureIgnoreCase))
                {
                    var utilFrm = new UtilEditor();
                    utilFrm.btnCancel.Enabled = false;
                    if (utilFrm.ShowDialog() == System.Windows.Forms.DialogResult.OK)//for user table need to ask for user 0
                    {
                        Program.AppSet.grainDeSable = Classes.WizardEvents.GetUniqueKey(7);
                        TabloidConfig.Config.updateCurrentKey(Program.AppSet.grainDeSable);
                        var param = new string[] { utilFrm.txtLogin.Text, utilFrm.txtNom.Text, utilFrm.txtPrenom.Text, utilFrm.txtMail.Text, Tabloid.Classes.Tools.SecurityHelper.EncryptPassword(utilFrm.txtMdp1.Text) };
                        WizardSQLHelper.ExecuteFromFile(t.SqlFile, param, connectionString, own);

                        Program.AppSet.ModeAuthentification = utilFrm.cmbAuth.SelectedIndex == 0 ? AuthenticationHandler.AuthenticationType.Formulaire : AuthenticationHandler.AuthenticationType.Windows;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    SqlCommands.SqlFromFile(t.SqlFile, connectionString, false);
                }
            }
            return(true);
        }
Esempio n. 3
0
        private void Info_CloseFromNext(object sender, PageEventArgs e)
        {
            if (txtGeomFiled.Text == "")
            {
                MetroMessageBox.Show(this, Properties.Resources.FieldNameNeeded, Properties.Resources.Erreur, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            var param = new string[] { _view.Nom, txtGeomFiled.Text, $"geometry({cmbType.SelectedItem},{txtSrid.Text})", _view.Schema };

            WizardSQLHelper.ExecuteFromFile("addField.sql", param, Program.AppSet.ConnectionString, this);

            TabloidConfigGeoLoc.GeoLocType geoLocType;
            Enum.TryParse(cmbType.SelectedItem.ToString(), out geoLocType);

            _view.GeoLoc.Type        = geoLocType;
            _view.GeoLoc.TitreCouche = _view.Titre;
            _view.GeoLoc.Geom        = txtGeomFiled.Text;
            _view.GeoLoc.Srid        = txtSrid.Text;
            _view.GeoLoc.ForcerSRID  = true;

            if (chkAddMenu.Checked)
            {
                WizardSQLHelper.AddToMenu(this, _view, "Carte " + _view.Titre, TabloidConfigMenuItem.MenuType.Carte, null);
            }
        }
 /// <summary>
 /// Build Module base table
 /// </summary>
 public static bool Activate(ModuleTableType moduleType, IWin32Window own)
 {
     foreach (string tableName in TableList[moduleType])
     {
         WizardSQLHelper.ExecuteFromFile(tableName + ".sql", null, Program.AppSet.ConnectionString, own);
     }
     return(true);
 }
Esempio n. 5
0
        private void RenameTable(object sender, EventArgs e)
        {
            var frmRename = new Rename(ParentTableResult.TableName);

            if (frmRename.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var param = new string[] { Program.AppSet.Schema, ParentTableResult.TableName, frmRename.txtNewName.Text };
                WizardSQLHelper.ExecuteFromFile("renameTable.sql", param, Program.AppSet.ConnectionString, _own);
            }
        }
        /// <summary>
        /// Remove Module base table
        /// </summary>
        public static bool Remove(ModuleTableType moduleType, IWin32Window own)
        {
            foreach (string tableName in TableList[moduleType])
            {
                var competedTableName = tableName;
                if (Program.AppSet.ProviderType == Provider.Postgres)
                {
                    competedTableName = CurrentContext.CurrentView.Schema + "." + tableName;
                }

                WizardSQLHelper.ExecuteFromFile("supTable.sql", new string[] { competedTableName }, Program.AppSet.ConnectionString, own);
            }
            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// Delete column in table
        /// Remove constraint if exist
        /// </summary>
        /// <param name="table">Field table name without schema</param>
        /// <param name="schema"></param>
        public static void DropColumn(string table, string column, string schema, IWin32Window own)
        {
            string error;
            var    constraints = DataTools.Data(SqlCommands.SqlGetForeignKey(table, schema), Program.AppSet.ConnectionString, out error);

            var columnConstraints = new DataView(constraints,
                                                 constraints.Columns[0].ColumnName + " like '" + column + "'",
                                                 "", DataViewRowState.Unchanged);

            foreach (DataRowView dr in columnConstraints)
            {
                var param1 = new string[] { schema, dr[3].ToString(), table };
                WizardSQLHelper.ExecuteFromFile("DropForeignKey.sql", param1, Program.AppSet.ConnectionString, own);
            }

            var param = new string[] { schema + "." + table, ChampTools.RemoveTableName(column) };

            WizardSQLHelper.ExecuteFromFile("supField.sql", param, Program.AppSet.ConnectionString, own);
        }
        /// <summary>
        /// Build required task on wizard end
        /// </summary>
        /// <returns></returns>
        bool addField()
        {
            var useJoinName = "";

            if (_iviewFct is TabloidConfigView && !radbutton.Checked)
            {
                var view = (TabloidConfigView)_iviewFct;

                if (_useDatabaseField && //handel label with no database field
                    ((TabloidBaseControl)wzCmbEditeur.SelectedItem).type != TemplateType.Graphique) //no database field for graphic
                {
                    if (radioCrea.Checked)                                                          //field must be created in database
                    {
                        var t       = (DbType)Enum.Parse(typeof(DbType), lstTypeCrea.SelectedItem.ToString());
                        var sqlType = dataHelper.DbTypeConverter.ConvertFromGenericDbType(t, Tools.ConvertProviderType(_provider));

                        var fieldArg = txtLong.Text;
                        if (txtDec.Text != "")
                        {
                            fieldArg = fieldArg + "," + txtDec.Text;
                        }
                        if (fieldArg != "")
                        {
                            fieldArg = "(" + fieldArg + ")";
                        }

                        var param = new string[] { view.NomTable, txtNomCrea.Text, sqlType + fieldArg, view.Schema };

                        if (!WizardSQLHelper.ExecuteFromFile("addField.sql", param, _connectionString, this))
                        {
                            return(true);
                        }
                    }
                    else//use existing field
                    {
                        if (fs.cmbTable.SelectedValue.ToString() != view.NomTable &&
                            ((TabloidBaseControl)wzCmbEditeur.SelectedItem).type != TemplateType.Graphique)//verify if field is in current table
                        {
                            var useJoin = view.Jointures.GetJoinFromTableName(fs.cmbTable.SelectedValue.ToString());
                            if (useJoin == null)//verify if table is in joined table list
                            {
                                if (MetroMessageBox.Show(this, Resources.add_join, Resources.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                                {
                                    var w = new WizardJoin(
                                        view,
                                        null,
                                        Program.AppSet.ConnectionString);

                                    w.ShowDialog();

                                    useJoin = view.Jointures.GetJoinFromTableName(fs.cmbTable.SelectedValue.ToString());
                                    if (useJoin != null)
                                    {
                                        useJoinName = useJoin.Nom;
                                    }
                                }
                            }
                            else
                            {
                                useJoinName = useJoin.Nom;
                            }
                        }
                    }
                }
            }

            if (radbutton.Checked)//add button
            {
                Tc = new TabloidConfigColonne
                {
                    Champ         = fs.lstChamp.Text,
                    Titre         = WzTxtTitre.Text,
                    Editeur       = TemplateType.Btn,
                    Type          = DbType.String,
                    EditeurParam2 = txtIcoBtn.Text,
                    EditeurParam3 = txtUrlBtn.Text,
                    EditeurParam4 = txtToolTipBtn.Text,
                    VisibleDetail = true,
                    Parent        = _parentField,
                    Nom           = "btn"
                }
            }
            ;
            else//add other type field
            {
                Tc = new TabloidConfigColonne
                {
                    Champ   = radioCrea.Checked ? txtNomCrea.Text : fs.lstChamp.Text,
                    Titre   = WzTxtTitre.Text,
                    Editeur = ((TabloidBaseControl)wzCmbEditeur.SelectedItem).type,
                    Type    = radioCrea.Checked ?
                              (DbType)Enum.Parse(typeof(DbType), lstTypeCrea.SelectedItem.ToString()) :
                              DbType.String,
                    EditeurParam1 = txtUrlBtn.Text,
                    Parent        = _parentField,
                    Jointure      = useJoinName,
                    Nom           = "C"
                };

                if (Tc.Editeur == TemplateType.Picture)
                {
                    Tc.EditeurParam1 = "144x200";
                    Tc.EditeurParam2 = "/Tabloid/images/inconnu.png";
                    Tc.EditeurParam3 = "jpg";
                    Tc.EditeurParam4 = "4";
                }

                if (Tc.Editeur == TemplateType.Graphique)
                {
                    Tc.EditeurParam1 = ((TabloidConfigGraph)cmbGraph.SelectedItem).Nom;
                }

                if (_iviewFct is TabloidConfigView)
                {
                    var view = (TabloidConfigView)_iviewFct;

                    if (Tc.Editeur == TemplateType.Mobile)
                    {
                        view.Recherche.ChampMobile = radioCrea.Checked ? txtNomCrea.Text : fs.lstChamp.Text;
                        WizardSQLHelper.SetMobile(view);
                    }
                    if (Tc.Editeur == TemplateType.Mail)
                    {
                        view.Recherche.ChampMail = radioCrea.Checked ? txtNomCrea.Text : fs.lstChamp.Text;
                    }
                }
            }

            WizardSQLHelper.SetFieldVisibilityProperties(Tc, lstVisibilites);

            var parent = _iviewFct.Colonnes;

            if (_parentField != null)
            {
                parent = _parentField.Colonnes;
            }

            Tools.AddWithUniqueName(_iviewFct.Colonnes, Tc, "C", parent);

            return(false);
        }
Esempio n. 9
0
        private void btnGen_Click(object sender, EventArgs e)
        {
            bool result;
            var  createdList = new List <string>();

            var startViewCount = TabloidConfig.Config.Views.Count;

            //clean response list
            foreach (DataRow dr in _tbContainer.Rows)
            {
                if (dr.RowState != DataRowState.Deleted && dr["Réponses"].ToString() != "")
                {
                    var r = dr["Réponses"].ToString().Trim();
                    r = r.Replace('-', ';');
                    dr["Réponses"] = r;
                }
            }

            _tbContainer.AcceptChanges();

            //search duplicate response list for combo box
            _tbContainer.Columns.Add("Liste");
            var list = 0;

            foreach (DataRow dr in _tbContainer.Rows)
            {
                if (dr.RowState != DataRowState.Deleted && dr["Réponses"].ToString() != "" && dr["Liste"] == DBNull.Value)
                {
                    var currentListName = "lr" + list.ToString();

                    dr["Liste"] = currentListName;

                    var dv = new DataView(_tbContainer, string.Format("Réponses like '{0}'", DataTools.ExtendedStringToSql(dr["Réponses"].ToString())), "", DataViewRowState.Unchanged);
                    foreach (DataRowView drv in dv)
                    {
                        drv["Liste"] = currentListName;
                    }

                    list++;
                }
            }

            //add new View
            var param = new string[] { Program.AppSet.Schema, txtVue.Text, "id_" + txtVue.Text };
            var t     = new TabloidConfigView
            {
                Schema          = param[0],
                Nom             = txtVue.Text,
                Titre           = txtVue.Text,
                NomTable        = txtVue.Text,
                DbKey           = param[2],
                Detail          = true,
                DisplayOnTowRow = true
            };

            result = WizardSQLHelper.ExecuteFromFile("table.sql", param, Program.AppSet.ConnectionString, this);
            if (!result)
            {
                return;
            }

            var i = 1;

            param = new string[] { txtVue.Text, "", "", Program.AppSet.Schema };
            foreach (DataRow dr in _tbContainer.Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                {
                    param[1] = "R" + i;
                    var info = dr["Info"].ToString();

                    var Tc = new TabloidConfigColonne
                    {
                        Nom          = "C" + i,
                        Champ        = "r" + i,
                        Groupe       = "!!!" + dr["Groupe"],
                        Titre        = dr["Questions"].ToString(),
                        VisibleListe = false,
                        Information  = info
                    };

                    if (dr["Réponses"].ToString() == "")
                    { //TextBox
                        Tc.Editeur = Tabloid.Classes.Controls.TemplateType.Defaut;
                        Tc.Type    = DbType.String;
                        param[2]   = dataHelper.DbTypeConverter.ConvertFromGenericDbType(DbType.String, Classes.WizardTools.Tools.ConvertProviderType(Program.AppSet.ProviderType));
                        result     = WizardSQLHelper.ExecuteFromFile("addField.sql", param, Program.AppSet.ConnectionString, this);

                        t.Colonnes.Add(Tc);
                    }
                    else
                    {//ComboBox
                        var tableCreationNeeded = !createdList.Contains(dr["Liste"].ToString());

                        result = WizardSQLHelper.SetDataBaseForList(this, false, Program.AppSet.Schema, dr["Liste"].ToString(), dr["Liste"].ToString(), "id_" + dr["Liste"].ToString(), false, t, Tc.Champ, Program.AppSet.ConnectionString, Program.AppSet.ProviderType, true, false, tableCreationNeeded ? "" : "alr" + i, !tableCreationNeeded);

                        var c = t.Colonnes[t.Colonnes.Count - 1];                        //last added column
                        c.Groupe       = "!!!" + dr["Groupe"];
                        c.Editeur      = Tabloid.Classes.Controls.TemplateType.ComboBox; //replace comboboxplus by combobox
                        c.Titre        = dr["Questions"].ToString();
                        c.VisibleListe = false;
                        c.Obligatoire  = true;
                        c.Information  = info;
                        createdList.Add(dr["Liste"].ToString());
                    }

                    i++;
                }
            }

            t.Index = TabloidConfig.Config.Views.Count - startViewCount;
            TabloidConfig.Config.Views.Add(t);

            // fill possible response table (lrx)
            DataView  view           = new DataView(_tbContainer);
            DataTable distinctValues = view.ToTable(true, "Liste", "Réponses");

            foreach (DataRow dr in distinctValues.Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                {
                    var sols   = dr["Réponses"].ToString().Split(';');
                    var values = "";

                    foreach (string sol in sols)
                    {
                        values += $"('{DataTools.StringToSql(sol.Trim())}'),";
                    }


                    values = values.TrimEnd(',');

                    var sql = $"INSERT INTO {Program.AppSet.Schema}.{ dr["Liste"]} (nom_{ dr["Liste"]}) VALUES {values}";

                    string error;
                    DataTools.Command(sql, null, Program.AppSet.ConnectionString, out error);
                }
            }


            //add default url field in user table
            var sqlType      = dataHelper.DbTypeConverter.ConvertFromGenericDbType(DbType.String, Classes.WizardTools.Tools.ConvertProviderType(Program.AppSet.ProviderType));
            var requestParam = new string[] { "roles", "default_url", sqlType + $"(300)", Program.AppSet.Schema };

            WizardSQLHelper.ExecuteFromFile("addField.sql", requestParam, Program.AppSet.ConnectionString, this);

            //add role "sonde"
            var detailURL    = AppSetting.GetDefaultPageURL(t.Nom, TabloidPages.Type.Detail) + "&mode=questionnaire";
            var profileRight = (ulong)Math.Pow(2, t.Index);
            //var profileRight2 = ~profileRight;

            var sql2 = $"insert into roles (titre_role,datemaj_roles,droits_lecture,droits_ecriture,droits_limite,droits_limiteecr,droits_suppression,default_url) values ('Sondé',now(),{profileRight},{profileRight},{profileRight},{profileRight},0,'{detailURL}')";

            sql2 += string.Format(
                SqlConverter.GetSql(SqlConverter.SqlType.InsertCommandKeyOut),
                "id_role");

            string error2;

            var roleId = DataTools.ScalarCommand(sql2, null, Program.AppSet.ConnectionString, out error2);

            //set config
            Program.AppSet.TabloidType = TabloidTypes.Questionnaire;
            AppSetting.setDefaultPage(t.Nom);
            Program.AppSet.champPageDefaut    = "default_url";
            Program.AppSet.AutoenrollmentRole = roleId.ToString();

            DialogResult = DialogResult.OK;
            Close();
        }
Esempio n. 10
0
        private void Button_end(object sender, PageEventArgs e)
        {
            var param = new string[] { txtSchema.Text, txtTable.Text, TxtRef.Text };

            if (radUseExistingTable.Checked)
            {
                string lastError;
                //find db key
                var dc = DataTools.Data(SqlCommands.SqlGetColums(cmbTable.Text), _connectionString, out lastError);//3

                param = new string[] { Program.AppSet.Schema, cmbTable.Text, dc.Select(dc.Columns[3].ColumnName + " like 'PRI%'")[0][0].ToString() };
            }

            var viewName = String.IsNullOrEmpty(txtNomVue.Text) ? param[1] : txtNomVue.Text;

            if (TabloidConfig.Config.Views.Contains(viewName))
            {
                MetroMessageBox.Show(this, TabloidWizard.Properties.Resources.ViewNameAlreadyExist, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
                return;
            }


            //add new View
            CreatedView = new TabloidConfigView
            {
                Schema   = param[0],
                Nom      = viewName,
                Titre    = txtInititView.Text,
                NomTable = param[1],// String.IsNullOrEmpty(txtNomVue.Text) ? "" : txtNomVue.Text,
                DbKey    = param[2]
            };

            if (radUseExistingTable.Checked)
            {
                TabloidConfig.Config.Views.Add(CreatedView);

                //set as default view
                setAsDefaultView(viewName);

                //add to menu
                addToMenu(CreatedView);

                return;
            }

            e.Cancel = !WizardSQLHelper.ExecuteFromFile("table.sql", param, _connectionString, this);
            if (e.Cancel)
            {
                return;
            }

            var Tc = new TabloidConfigColonne
            {
                Champ   = "nom_" + param[1],
                Titre   = "Nom",
                Editeur = TemplateType.TextBox,
                Type    = DbType.String
            };

            Tools.AddWithUniqueName(CreatedView.Colonnes, Tc, "C");

            TabloidConfig.Config.Views.Add(CreatedView);

            //set as default view
            setAsDefaultView(viewName);

            //add to menu
            addToMenu(CreatedView);
        }
Esempio n. 11
0
        public static void onConfigLoaded(string schema, IWin32Window own)
        {
            //for mysql verify if default schema is database name
            if (Program.AppSet.ProviderType == Provider.MySql && Program.AppSet.Schema != getDataBaseNameFromConnectionString(Program.AppSet.ConnectionString))
            {
                if (MetroMessageBox.Show(own, Properties.Resources.MySQLDifferentBaseName, Properties.Resources.Question, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var connectionDataBaseName = getDataBaseNameFromConnectionString(Program.AppSet.ConnectionString);
                    WizardSQLHelper.SetAllViewSchema(connectionDataBaseName);
                    Program.AppSet.Schema = connectionDataBaseName;
                }
            }

            //verify role columun existance
            var tableColumns = new Dictionary <string, Dictionary <string, FieldDescriptionType> > {
                { "roles", new Dictionary <string, FieldDescriptionType> {
                      { "ad_group", new FieldDescriptionType {
                            type = DbType.String, extra = "(255)"
                        } },
                      { "droits_limiteecr", new FieldDescriptionType {
                            type = DbType.Int64, extra = "(20) DEFAULT 0"
                        } },                                                                                  //"numeric(20,0) DEFAULT 0"
                      { "droits_limite", new FieldDescriptionType {
                            type = DbType.Int64, extra = "(20) DEFAULT 1"
                        } }
                  } },
                { "utilisateurs", new Dictionary <string, FieldDescriptionType> {
                      { "theme", new FieldDescriptionType {
                            type = DbType.String, extra = "(100)"
                        } },
                      { "lastchatid", new FieldDescriptionType {
                            type = DbType.Int64, extra = " DEFAULT 0"
                        } },
                      { "password", new FieldDescriptionType {
                            type = DbType.String, extra = "(100)"
                        } },
                      { "token", new FieldDescriptionType {
                            type = DbType.String, extra = "(40)"
                        } },
                      { "ref", new FieldDescriptionType {
                            type = DbType.Boolean
                        } }
                  } }
            };

            foreach (var t in tableColumns)
            {
                string lastError;

                DataTable tableColumnsList = null;

                if (Program.AppSet.ProviderType == Provider.Postgres)
                {
                    foreach (var cschema in WizardTools.Tools.GetSearchPath(Program.AppSet.ConnectionString))
                    {
                        tableColumnsList = DataTools.Data(SqlCommands.SqlGetColums(t.Key, cschema), Program.AppSet.ConnectionString, out lastError);//c0
                        if (!string.IsNullOrEmpty(lastError))
                        {
                            throw new Exception(lastError);
                        }
                        if (tableColumnsList.Rows.Count > 0)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    tableColumnsList = DataTools.Data(SqlCommands.SqlGetColums(t.Key, null), Program.AppSet.ConnectionString, out lastError);//c0
                    if (!string.IsNullOrEmpty(lastError))
                    {
                        throw new Exception(lastError);
                    }
                }

                var fieldColumnName = tableColumnsList.Columns[0].ColumnName;

                foreach (var c in t.Value)
                {
                    if (tableColumnsList.Select(fieldColumnName + "='" + c.Key + "'").Length == 0)//field doesn't exist
                    {
                        var param = new[] { t.Key, c.Key, c.Value.ToString(), Program.AppSet.Schema };

                        var result = WizardSQLHelper.ExecuteFromFile("addField.sql", param, Program.AppSet.ConnectionString, own);
                    }
                }
            }
            //Detect old role implementation
            if (!WizardTools.Tools.isTableExist("lst_roles"))
            {
                var result = MetroMessageBox.Show(own, Properties.Resources.WrongConfigVersion, Properties.Resources.Information, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                if (result == DialogResult.Yes)
                {
                    AutomaticViewBuilder.setOldUtilisateurs(schema);       //.SetTable(schema);

                    var view = TabloidConfig.Config.Views["utilisateurs"]; //Todo role field could not be c4 on manual déclaration

                    WizardSQLHelper.ConvertSimpleList(view, view.Colonnes["c4"], "lst_roles", own);

                    removeView("utilisateurs");
                    removeView("roles");
                    removeView("lst_roles");
                    removeView("perso");
                }
            }

            //Detect roles/utilisateur/perso définition
            if (!TabloidConfig.Config.Views["roles"].AutomaticCreation ||
                !TabloidConfig.Config.Views["utilisateurs"].AutomaticCreation ||
                !TabloidConfig.Config.Views["perso"].AutomaticCreation)
            {
                var dr = MetroMessageBox.Show(own, Properties.Resources.CustumRoleUsed,
                                              Properties.Resources.Information, MessageBoxButtons.YesNo, MessageBoxIcon.Information);


                if (dr == DialogResult.Yes)
                {
                    removeView("roles");
                    removeView("utilisateurs");
                    removeView("perso");
                }
            }
            //Detect empty salt grain
            if (string.IsNullOrEmpty(Program.AppSet.grainDeSable))
            {
                Program.AppSet.grainDeSable = GetUniqueKey(7);
                TabloidConfig.Config.updateCurrentKey(Program.AppSet.grainDeSable);
            }
        }
        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);
            }
        }