/// <summary> /// play sql script from file /// </summary> /// <param name="file">file path</param> /// <param name="connectionString"></param> /// <returns></returns> public static void SqlFromFile(string file, string connectionString, bool silentMode = true) { var path = AppDomain.CurrentDomain.BaseDirectory; path += "sources\\sql\\"; path += (Provider == Provider.MySql ? "mySql\\" : "Postgres\\") + file; var sr = new StreamReader(path); var sql = sr.ReadToEnd().Split(';'); foreach (var cmd in sql) { var cmd2 = cmd.TrimEnd(new char[] { '\r', '\n' }); if (!string.IsNullOrEmpty(cmd2)) { string lastError; DataTools.Command(cmd2, null, connectionString, out lastError); if (!silentMode & !string.IsNullOrEmpty(lastError)) { throw new Exception(lastError); } if (!string.IsNullOrEmpty(lastError)) { break; } } } sr.Close(); }
/// <summary> /// Create field in base from a list /// </summary> /// <param name="fl"></param> /// <param name="table"></param> /// <param name="schema"></param> /// <param name="connectionString"></param> public static void CreateField(IEnumerable <Field> fl, string table, string schema, string connectionString) { foreach (var f in fl) { Log.Write(string.Format("Ajout de la colone {0} à la table {1}", f.Name, table)); string lastError; DataTools.Command(SqlCommands.SqlSetColumn(table, schema, f), null, connectionString, out lastError); if (!string.IsNullOrEmpty(lastError)) { Log.Write("Erreur:" + lastError); } } }
/// <summary> /// Verify for postgres if database exist /// </summary> /// <returns></returns> private void dbCreate(string dbName, string cs) { string err; var sql = "Create database {0};"; sql = string.Format(sql, dbName); DataTools.Command(sql, null, cs, out err); if (!string.IsNullOrEmpty(err)) { MetroMessageBox.Show(this, string.Format(Resources.ErrorMessage, err), Resources.Erreur, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
internal static void afterViewPropertyChange(object s, PropertyValueChangedEventArgs e, IWin32Window own) { switch (e.ChangedItem.PropertyDescriptor.Name) { case "Corbeille": if (!(bool)e.ChangedItem.Value) //disable trash requested { var result = MetroMessageBox.Show(own, Properties.Resources.EmptyTrash, Properties.Resources.Information, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { DataTools.Command( $"Delete from {CurrentContext.CurrentView.Schema}.{CurrentContext.CurrentView.NomTable} where deleted_{CurrentContext.CurrentView.NomTable}=1", null, Program.AppSet.ConnectionString); } } break; } afterViewModified(CurrentContext.CurrentView); }
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(); }
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); } }