Ejemplo n.º 1
0
        public void BatchUpdate(Expression <Func <T, bool> > expression, object data)
        {
            OpenConnection();
            var converter = new SqlConverter(typeof(T), Connection.GetType());

            var where = converter.ExpressionToWhere(expression);
            var param      = converter.DynamicParameters;
            var dictionary = ObjectUtility.ObjectToDictionary(data);

            var valueStr    = new StringBuilder();
            var columnCount = EntityContext <T> .Columns.Count();

            foreach (var currColumn in dictionary)
            {
                valueStr.Append(string.Format("{0}=@{0},", currColumn.Key));
                param.Add(currColumn.Key, currColumn.Value);
            }
            if (valueStr.Length > 0)
            {
                valueStr.Remove(valueStr.Length - 1, 1);
            }
            var sql = string.Format("update {0} set {1} where {2}", EntityContext <T> .TableName, valueStr.ToString(), where);

            Connection.Execute(sql, param);
        }
        public static bool InsertData(object sqlSet, object keysNames, out object outKeysValues)
        {
            string error;
            var    sql = ((SqLcommandSet)sqlSet).Insert.Command +
                         string.Format(
                SqlConverter.GetSql(SqlConverter.SqlType.InsertCommandKeyOut),
                ((string[])keysNames)[0]);
            var id = DataTools.ScalarCommand(
                sql,
                ((SqLcommandSet)sqlSet).Insert.Parameteredfields.Values.ToList(),
                WebConfigurationManager.ConnectionStrings["TabloidConnection"].ConnectionString,
                out error);

            if (id is bool)
            {
                id = null;
            }
            if (id == null)
            {
                throw new Exception(error);
            }

            outKeysValues = new[] { id.ToString() };
            return(true);
        }
Ejemplo n.º 3
0
        protected override void BeginProcessing()
        {
            try
            {
                var currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE",
                                                Path.Combine(currentDirectory, "Sitecore.Courier.dll.config"));
                ResetConfigMechanism();
                string version = Guid.NewGuid().ToString();

                Console.WriteLine("Source: {0}", Source);
                Console.WriteLine("Target: {0}", Target);
                Console.WriteLine("Output: {0}", Output);
                Console.WriteLine("SerializationProvider: {0}", SerializationProvider);
                Console.WriteLine("CollisionBehavior: {0}", CollisionBehavior);
                Console.WriteLine("IncludeFiles: {0}", IncludeFiles);
                Console.WriteLine("DacPac: {0}", DacPac);

                RainbowSerializationProvider.Enabled        = SerializationProvider == SerializationProvider.Rainbow;
                RainbowSerializationProvider.IncludeFiles   = IncludeFiles;
                RainbowSerializationProvider.EnsureRevision = EnsureRevision;

                var diff = new DiffInfo(
                    DiffGenerator.GetDiffCommands(Source, Target, IncludeSecurity, version, CollisionBehavior),
                    "Sitecore Courier Package",
                    string.Empty,
                    string.Format("Diff between serialization folders '{0}' and '{1}'.", Source, Target));

                if (IncludeSecurity)
                {
                    diff.Commands.Add(new PostStepFileSystemDataItem(currentDirectory, string.Empty, PostDeployDll)
                                      .GenerateAddCommand().FirstOrDefault());
                    diff.PostStep = PostStep;
                    diff.Version  = version;
                }

                if (DacPac)
                {
                    SqlConverter c = new SqlConverter();
                    c.ConvertPackage(diff, Output);

                    var           builder = new DacPacBuilder();
                    DirectoryInfo d       = new DirectoryInfo(Output);
                    foreach (var file in d.GetFiles("*.sql"))
                    {
                        builder.ConvertToDacPac(file.FullName, Path.Combine(file.DirectoryName, $"{Path.GetFileNameWithoutExtension(file.Name)}.dacpac"));
                    }
                }
                else
                {
                    PackageGenerator.GeneratePackage(diff, string.Empty, Output);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw ex;
            }
        }
Ejemplo n.º 4
0
 public static List <T> Query <T>(string wherestr = null) where T : class
 {
     using (MySqlConnection conn = new MySqlConnection(ConnectStr))
     {
         string sql = SqlConverter.ToSelectSQL(typeof(T), wherestr);
         return(conn.Query <T>(sql).ToList());
     }
 }
Ejemplo n.º 5
0
        public void BatchDelete(Expression <Func <T, bool> > expression)
        {
            OpenConnection();
            var converter = new SqlConverter(typeof(T), Connection.GetType());

            var where = converter.ExpressionToWhere(expression);
            var param = converter.DynamicParameters;
            var sql   = string.Format("delete from {0}{1}", EntityContext <T> .TableName, where);

            Connection.Execute(sql, param);
        }
Ejemplo n.º 6
0
 public static T Get <T>(int id)
 {
     if (id <= 0)
     {
         return(default(T));
     }
     using (MySqlConnection conn = new MySqlConnection(ConnectStr))
     {
         string sql = SqlConverter.ToSelectSQL(typeof(T), "ID=" + id);
         return(conn.Query <T>(sql).FirstOrDefault());
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Search for a field name for a given table
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="tableName"></param>
        /// <param name="schema"></param>
        /// <returns>true if exist</returns>
        public static bool isConstraintExist(string constraintName, string schema)
        {
            string lastError;
            var    ConstraintList = DataTools.Data(SqlCommands.SqlGetForeignKey(null, schema), Program.AppSet.ConnectionString, out lastError);//c0

            if (!string.IsNullOrEmpty(lastError))
            {
                throw new Exception(lastError);
            }

            var constraintColumnName = ConstraintList.Columns[3].ColumnName;

            return(ConstraintList.Select($"{constraintColumnName} {SqlConverter.GetSql(SqlConverter.SqlType.Ilike)} '{constraintName}'").Length > 0);
        }
Ejemplo n.º 8
0
 public static bool Delete(Type type, int key, string wherestr = null)
 {
     using (MySqlConnection conn = new MySqlConnection(ConnectStr))
     {
         string sql = SqlConverter.ToDeleteSQL(type, key, wherestr);
         int    ret = conn.Execute(sql);
         if (ret > 0)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
Ejemplo n.º 9
0
 public static object Create(object obj)
 {
     if (obj == null)
     {
         return(null);
     }
     using (MySqlConnection conn = new MySqlConnection(ConnectStr))
     {
         string insertSql = SqlConverter.ToInsertSQL(obj);
         insertSql += ";SELECT @@IDENTITY as id;";
         var newrow = conn.Query(insertSql).FirstOrDefault() as IDictionary <string, object>;
         int newid  = newrow["id"].ToInt();
         obj.SetProperty("ID", newid);
         return(obj);
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes the SQL binding rules
        /// </summary>
        /// <param name="context"> The config context </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if context is null
        /// </exception>
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            ILogger logger = this._loggerFactory.CreateLogger(LogCategories.Bindings);

            TelemetryInstance.Initialize(this._configuration, logger);
#pragma warning disable CS0618 // Fine to use this for our stuff
            FluentBindingRule <SqlAttribute> inputOutputRule = context.AddBindingRule <SqlAttribute>();
            var converter = new SqlConverter(this._configuration);
            inputOutputRule.BindToInput(converter);
            inputOutputRule.BindToInput <string>(typeof(SqlGenericsConverter <string>), this._configuration, logger);
            inputOutputRule.BindToCollector <OpenType>(typeof(SqlAsyncCollectorBuilder <>), this._configuration, logger);
            inputOutputRule.BindToInput <OpenType>(typeof(SqlGenericsConverter <>), this._configuration, logger);
        }
        /// <summary>
        /// Initializes the SQL binding rules
        /// </summary>
        /// <param name="context"> The config context </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if context is null
        /// </exception>
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var inputOutputRule = context.AddBindingRule <SqlAttribute>();
            var converter       = new SqlConverter(_configuration);

            inputOutputRule.BindToInput <SqlCommand>(converter);
            inputOutputRule.BindToInput <string>(typeof(SqlGenericsConverter <string>), _configuration);
            inputOutputRule.BindToCollector <OpenType>(typeof(SqlAsyncCollectorBuilder <>), _configuration, _loggerFactory);
            inputOutputRule.BindToInput <OpenType>(typeof(SqlGenericsConverter <>), _configuration);

            var triggerRule = context.AddBindingRule <SqlTriggerAttribute>();

            triggerRule.BindToTrigger(new SqlTriggerAttributeBindingProvider(_configuration, _loggerFactory));
        }
Ejemplo n.º 12
0
        public static Mapper RegisterMappings(Func <Type, object> serviceConstructor)
        {
            var mapperConfiguration = new MapperConfiguration(mapper =>
            {
                mapper.ConstructServicesUsing(serviceConstructor);
                mapper.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();

                mapper.CreateMap <sysjob, Job>();
                mapper.CreateMap <sysjobstep, JobStep>();
                mapper.CreateMap <sysjobhistory, JobHistory>()
                .ForMember(history => history.RunDate,
                           expression => expression.MapFrom(sysjobhistory => GetNullableDateTime(SqlConverter.GetDateTimeFromInt(sysjobhistory.run_date, sysjobhistory.run_time, DateTimeKind.Utc))))
                .ForMember(history => history.RunDuration,
                           expression => expression.MapFrom(sysjobhistory => SqlConverter.GetRunDurationFromInt(sysjobhistory.run_duration)));
                mapper.CreateMap <sysschedule, SystemSchedule>()
                .ForMember(schedule => schedule.ActiveStartDate,
                           expression =>
                           expression.MapFrom(
                               sysschedule =>
                               GetNullableDateTime(SqlConverter.GetDateTimeFromInt(sysschedule.active_start_date,
                                                                                   sysschedule.active_start_time, DateTimeKind.Utc))))
                .ForMember(schedule => schedule.ActiveEndDate,
                           expression =>
                           expression.MapFrom(
                               sysschedule =>
                               GetNullableDateTime(SqlConverter.GetDateTimeFromInt(sysschedule.active_end_date,
                                                                                   sysschedule.active_end_time, DateTimeKind.Utc))))
                .ForMember(systemSchedule => systemSchedule.Enabled,
                           expression => expression.MapFrom(sysschedule => sysschedule.enabled == 1));
                mapper.CreateMap <sysjobschedule, SystemJobSchedule>().ForMember(schedule => schedule.NextRunDate,
                                                                                 expression =>
                                                                                 expression.MapFrom(
                                                                                     sysschedule =>
                                                                                     GetNullableDateTime(SqlConverter.GetDateTimeFromInt(sysschedule.next_run_date,
                                                                                                                                         sysschedule.next_run_time, DateTimeKind.Utc))));
                mapper.CreateMap <SystemJobSchedule, JobSchedule>();
                mapper.CreateMap <SystemSchedule, JobSchedule>();
//                mapper.CreateMap<sysjobactivity, RunningJobActivity>();
//                mapper.CreateMap<Job, RunningJobActivity>();
            });

            return(new Mapper(mapperConfiguration));
        }
Ejemplo n.º 13
0
        private string GenSelectCommand(bool count)
        {
            var result = ""; // body;

            _from = From;

            SetFromSqlJoinParameter();

            if (!string.IsNullOrEmpty(Distinct))
            {
                result = SqlConverter.GetSql(SqlConverter.SqlType.Distinct, new string[] { Distinct }) + " ";
            }

            //

            //var countField = string.IsNullOrEmpty(Distinct) ? "*" : Distinct;
            //result += count
            //    ? "Count(" + countField + ")"
            //    : string.Join(",", _fields.FindAll(s => !String.IsNullOrEmpty(s)));

            result += string.Join(",", _fields.FindAll(s => !String.IsNullOrEmpty(s)));
            result  = SqLcommandType.Select + " " + result;

            result += addPart(_from, "From");
            result += addPart(Where, "Where");
            result += addPart(GroupBy, "Group By");

            if (!count)
            {
                result += addPart(OrderBy, "Order By");
                result += addPart(Limit, "Limit");
                result += addPart(Offset, "Offset");
            }

            if (count)
            {
                result = "SELECT COUNT(*) FROM (" + result + ") AS temp;";
            }

            return(result);
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            var    converterConfigs = ConfigurationManager.GetSection("converterConfigs") as ConverterConfigurationSection;
            string outPath          = converterConfigs.OuputFilesPath;

            IConverter <string, TableClassRepresentation> converter =
                new SqlConverter(converterConfigs.DomainNamespace, SQLTypes.MSSQLTypes);
            DirectoryInfo directory = new DirectoryInfo(converterConfigs.SqlFilesPath);

            if (!new DirectoryInfo(outPath).Exists)
            {
                Directory.CreateDirectory(outPath);
            }

            foreach (var sqlDefinition in directory.GetFiles())
            {
                var cstable = converter.Convert(File.ReadAllText(sqlDefinition.FullName));
                using (StreamWriter streamWriter = new StreamWriter(outPath + cstable.TableDefinition.TableName + ".cs"))
                    streamWriter.Write(cstable);
            }
        }
Ejemplo n.º 15
0
        public static object Change(object obj, string wherestr = null)
        {
            if (obj == null)
            {
                return(null);
            }
            int id = obj.GetProperty("ID").ToInt();

            using (MySqlConnection conn = new MySqlConnection(ConnectStr))
            {
                string sql = SqlConverter.ToUpdateSQL(obj, wherestr);
                int    ret = conn.Execute(sql);
                if (ret > 0)
                {
                    return(obj);
                }
                else
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Console.WriteLine("Source: {0}", options.Source);
                Console.WriteLine("Target: {0}", options.Target);
                Console.WriteLine("Output: {0}", options.Output);
                Console.WriteLine("Collision behavior: {0}", options.CollisionBehavior);
                Console.WriteLine("Use Rainbow: {0}", options.UseRainbow);
                Console.WriteLine("Include Security: {0}", options.IncludeSecurity);
                Console.WriteLine("Include Files: {0}", options.IncludeFiles);
                Console.WriteLine("Configuration: {0}", options.Configuration);
                Console.WriteLine("Ensure Revision: {0}", options.EnsureRevision);
                Console.WriteLine("Path to project file: {0}", options.ScProjFilePath);
                Console.WriteLine("DacPac Output: {0}", options.DacPac);

                string version = Guid.NewGuid().ToString();
                SanitizeOptions(options);

                if (ExclusionHandler.HasValidExclusions(options.Configuration, options.ScProjFilePath))
                {
                    var exclusions = ExclusionHandler.GetExcludedItems(options.ScProjFilePath, options.Configuration);

                    ExclusionHandler.RemoveExcludedItems(options.Source, exclusions);
                    ExclusionHandler.RemoveExcludedItems(options.Target, exclusions);
                }

                RainbowSerializationProvider.Enabled        = options.UseRainbow;
                RainbowSerializationProvider.IncludeFiles   = options.IncludeFiles;
                RainbowSerializationProvider.EnsureRevision = options.EnsureRevision;

                var commands = DiffGenerator.GetDiffCommands(options.Source, options.Target, options.IncludeSecurity, version, options.CollisionBehavior);

                var diff = new DiffInfo(
                    commands,
                    "Sitecore Courier Package",
                    string.Empty,
                    string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target));

                if (options.IncludeSecurity)
                {
                    var currentDirectory = Directory.GetCurrentDirectory();
                    commands.Add(new PostStepFileSystemDataItem(currentDirectory, string.Empty, PostDeployDll)
                                 .GenerateAddCommand().FirstOrDefault());
                    diff.PostStep = PostStep;
                    diff.Version  = version;
                }

                if (options.DacPac)
                {
                    SqlConverter c = new SqlConverter();
                    c.ConvertPackage(diff, options.Output);

                    var           builder = new DacPacBuilder();
                    DirectoryInfo d       = new DirectoryInfo(options.Output);
                    foreach (var file in d.GetFiles("*.sql"))
                    {
                        builder.ConvertToDacPac(file.FullName, Path.Combine(file.DirectoryName, $"{Path.GetFileNameWithoutExtension(file.Name)}.dacpac"));
                    }
                }
                else
                {
                    PackageGenerator.GeneratePackage(diff, string.Empty, options.Output);
                }
            }
            else
            {
                Console.WriteLine(options.GetUsage());
            }
        }
Ejemplo n.º 17
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();
        }
Ejemplo n.º 18
0
        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);
            }
        }
 public SQLConverterTest()
 {
     _sqlConverter = new SqlConverter(_generatedDomainName, SQLTypes.MSSQLTypes);
 }