Example #1
0
 public override void GenRuleTestBody(CSharpWriter csw, RuleCompiler cmp, string member)
 {
     csw.WriteLine("{0} node = {1}({2});", TypeName, FuncName, CallArgs.CreateDelimitedText(", "));
     csw.WriteLine("if (node == null) return false;");
     csw.WriteLine("args.{0} = node;", member);
     csw.WriteLine("return true;");
 }
Example #2
0
        private void ReloadLicenses()
        {
            lsvLicenses.Items.Clear();
            foreach (var lic in LicenseTool.ValidLicenses)
            {
                AddLincese(lic, 1);
            }
            foreach (var lic in LicenseTool.InvalidLicenses)
            {
                AddLincese(lic, 0);
            }

            lsvFeatures.Items.Clear();
            foreach (var holder in FeatureAddonType.Instance.CommonSpace.GetAllAddons())
            {
                var item = lsvFeatures.Items.Add(holder.Title);
                item.ImageIndex = LicenseTool.FeatureAllowed(holder.Name) ? 1 : 0;
                item.SubItems.Add(holder.GetDefiner());
                var lst = new List <string>();
                foreach (var lic in LicenseTool.ValidLicenses)
                {
                    if (lic.FeatureAllowed(holder.Name))
                    {
                        lst.Add(lic.LongText);
                    }
                }
                item.SubItems.Add(lst.CreateDelimitedText(","));
            }
        }
Example #3
0
        public override void WriteStructureBeforeData(IDatabaseStructure db)
        {
            using (StreamWriter sw = new StreamWriter(GetWorkingFileName()))
            {
                m_fmt.Writer   = sw;
                m_fmt.Language = Language;
                m_fmt.BeginFile("s_database");
                m_fmt.H2("s_tables");
                foreach (var tbl in db.Tables.SortedByKey <ITableStructure, NameWithSchema>(tbl => tbl.FullName))
                {
                    m_fmt.H3(String.Format("{0} {1}", Texts.LangGet("s_table", m_language), tbl));
                    m_fmt.BeginTable(new TableStyle {
                        Border = 1, WidthPercent = 100
                    });

                    m_fmt.BeginRow(true);
                    m_fmt.HeadingCell("s_name"); m_fmt.HeadingCell("s_type"); m_fmt.HeadingCell("s_nullable");
                    m_fmt.HeadingCell("s_default_value"); m_fmt.HeadingCell("s_keys");
                    m_fmt.EndRow(true);

                    foreach (var col in tbl.Columns)
                    {
                        m_fmt.BeginRow(false);
                        if (col.IsNullable)
                        {
                            m_fmt.Cell(col.ColumnName);
                        }
                        else
                        {
                            m_fmt.BeginCell(false).Bold(col.ColumnName).EndCell(false);
                        }
                        m_fmt.Cell(col.DataType);
                        m_fmt.Cell(col.IsNullable ? "s_yes" : "s_no");
                        m_fmt.Cell(col.DefaultValue.SafeGetSql(Dialect));

                        List <string> keys = new List <string>();
                        foreach (IPrimaryKey pk in tbl.GetConstraints <IPrimaryKey>())
                        {
                            if (pk.Columns.IndexOfIf(c => c.ColumnName == col.ColumnName) >= 0)
                            {
                                keys.Add("PK");
                            }
                        }
                        foreach (IForeignKey fk in tbl.GetConstraints <IForeignKey>())
                        {
                            if (fk.Columns.IndexOfIf(c => c.ColumnName == col.ColumnName) >= 0)
                            {
                                keys.Add("FK->" + fk.PrimaryKeyTable.ToString());
                            }
                        }
                        m_fmt.Cell(keys.CreateDelimitedText(", "));
                        m_fmt.EndRow(false);
                    }
                    m_fmt.EndTable();
                }
                m_fmt.EndFile();
                m_fmt.Writer = null;
            }
        }
Example #4
0
 public override void WriteSqlNodeMembers(CSharpWriter csw, RuleCompiler cmp)
 {
     base.WriteSqlNodeMembers(csw, cmp);
     foreach (var chain in Chains)
     {
         chain.WriteSqlNodeMembers(csw, cmp);
     }
     csw.WriteLine("public enum {0} {{ {1} }}", EnumTypeName, EnumElems.CreateDelimitedText(", "));
 }
Example #5
0
        protected override void RunBulkCopy(IDataQueue queue)
        {
            int           okRowCount = 0, failRowCount = 0;
            List <string> insertErrors = new List <string>();

            ITableStructure dst = queue.GetRowFormat;

            var           conn    = (NpgsqlConnection)Connection.SystemConnection;
            NpgsqlCommand command = new NpgsqlCommand(Connection.Dialect.GenerateScript(d => d.Put("^copy %f (%,i) ^from ^stdin", DestinationTable.FullName, from c in dst.Columns select c.ColumnName)), conn);
            NpgsqlCopyIn  cin     = new NpgsqlCopyIn(command, conn);

            try
            {
                cin.Start();
                var fw = new BinaryWriter(cin.CopyStream);
                while (!queue.IsEof)
                {
                    IBedRecord rec = queue.GetRecord();
                    for (int i = 0; i < rec.FieldCount; i++)
                    {
                        if (i > 0)
                        {
                            fw.Write((byte)'\t');
                        }
                        rec.ReadValue(i);
                        WriteField(rec, fw);
                    }
                    fw.Write((byte)'\r');
                    fw.Write((byte)'\n');
                    okRowCount++;
                }
                fw.Flush();
                cin.End();
            }
            catch (Exception err)
            {
                cin.Cancel("canceled");
                ProgressInfo.LogMessageDetail(
                    "INSERT", DatAdmin.LogLevel.Error,
                    String.Format("{0}", Texts.Get("s_error_inserting_into_table$table", "table", DestinationTable.FullName)), err.ToString());
                throw;
            }

            if (failRowCount > 0)
            {
                ProgressInfo.LogMessageDetail(
                    "INSERT", DatAdmin.LogLevel.Error,
                    String.Format("{0}, OK:{1}, FAIL:{2}", Texts.Get("s_error_inserting_into_table$table", "table", DestinationTable.FullName), okRowCount, failRowCount),
                    insertErrors.CreateDelimitedText("\r\n")
                    );
            }
            else
            {
                ProgressInfo.LogMessage("INSERT", DatAdmin.LogLevel.Info, Texts.Get("s_inserted_into_table$table$rows", "table", DestinationTable.FullName, "rows", okRowCount));
            }
        }
Example #6
0
        public virtual void SendScript(IPhysicalConnection conn, List <string> script, List <string> batchBegin, List <string> batchEnd, DataSynOperation operation, IDataSynReportEnv repenv)
        {
            var fullcmd = new List <string>();

            if (batchBegin != null)
            {
                fullcmd.AddRange(batchBegin);
            }
            fullcmd.AddRange(script);
            if (batchEnd != null)
            {
                fullcmd.AddRange(batchEnd);
            }
            repenv.SendScriptWrapper(new DataSynScriptWrapper_ExecuteNonQuery(fullcmd.CreateDelimitedText(";\n"), operation, conn.SystemConnection));
        }
Example #7
0
        public static string GetTitle(string features)
        {
            var res = new List <string>();

            foreach (string item in features.Split('|'))
            {
                AddonHolder addon = Instance.FindHolder(item);
                if (addon == null)
                {
                    continue;
                }
                res.Add(addon.Attrib.Title);
                var attr = (FeatureAttribute)addon.Attrib;
            }
            return(res.CreateDelimitedText(","));
        }
Example #8
0
 public DataSqlGenChooseColumnsForm(ITableStructure table, List <string> columns)
 {
     m_columns = columns;
     InitializeComponent();
     if (table != null)
     {
         textBox1.Visible = false;
         foreach (var col in table.Columns)
         {
             checkedListBox1.Items.Add(col.ColumnName, columns.Contains(col.ColumnName));
         }
     }
     else
     {
         checkedListBox1.Visible = false;
         textBox1.Text           = columns.CreateDelimitedText("\r\n");
     }
 }
Example #9
0
 private void ShowCurrentEntityStyle()
 {
     if (m_selectedTables.Count >= 1)
     {
         var names = new List <string>();
         foreach (var tbl in m_selectedTables)
         {
             names.Add(tbl.Table.Name);
         }
         tbxStyleTableName.Text = names.CreateDelimitedText(", ");
         entityStyleFrame1.ShowEntityStyle(m_diagram.GetCurrentEntityStyle(), EnumNamedStyles, GetSelectedTablesEntityOveride, SetSelectedTablesEntityOveride);
     }
     if (m_selectedTables.Count == 0)
     {
         tbxStyleTableName.Text = "(" + Texts.Get("s_diagram") + ")";
         entityStyleFrame1.ShowEntityStyle(m_diagram.Style.Entity, null, m_diagram.GetEntityOverride, m_diagram.SetEntityOverride);
     }
 }
Example #10
0
        public string ToString(string format, IFormatProvider formatProvider)
        {
            switch (format)
            {
            case "L":
            case "M":
                if (SubNames.Count > 0)
                {
                    return(ObjectName.ToString(format, formatProvider) + "." + SubNames.CreateDelimitedText("."));
                }
                return(ObjectName.ToString(format, formatProvider));

            case "S":
            default:
                if (SubNames.Count > 0)
                {
                    return(SubNames[SubNames.Count - 1]);
                }
                return(ObjectName.ToString(format, formatProvider));
            }
        }
Example #11
0
        private void btnDeleteJob_Click(object sender, EventArgs e)
        {
            var files = new List <string>();

            if (lsvJobs.SelectedItems.Count == 0)
            {
                return;
            }
            foreach (ListViewItem item in lsvJobs.SelectedItems)
            {
                var rec = (JobWithFile)item.Tag;
                files.Add(rec.FullFile);
            }
            if (MessageBox.Show(Texts.Get("s_really_delete_jobs") + "\n" + files.CreateDelimitedText("\n"), VersionInfo.ProgramTitle, MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }
            foreach (string fn in files)
            {
                File.Delete(fn);
            }
            RefreshJobs();
        }
Example #12
0
        private void btnRunJob_Click(object sender, EventArgs e)
        {
            if (lsvJobs.SelectedItems.Count == 0)
            {
                return;
            }
            if (MessageBox.Show(Texts.Get("s_really_run$jobs", "jobs", lsvJobs.SelectedItems.Count), VersionInfo.ProgramTitle, MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }
            var cmdlist = new List <JobCommand>();
            var joblist = new List <string>();
            var job     = new Job();

            foreach (ListViewItem item in lsvJobs.SelectedItems)
            {
                var rec = (JobWithFile)item.Tag;
                joblist.Add(rec.Job.ToString());
                // we must load current version of job
                var job2 = Job.LoadFromFile(rec.FullFile);
                foreach (var cmd in rec.Job.Root.Commands)
                {
                    var find = job2.FindCommand(cmd.GroupId);
                    if (find != null)
                    {
                        job.AddCommand(find.Clone(false));
                    }
                    else
                    {
                        job.AddCommand(cmd.Clone(false));
                    }
                }
                job.Root.ReportConfigs.AddRange(job2.Root.ReportConfigs);
            }
            job.Title = joblist.CreateDelimitedText(";");
            job.CreateProcess(new Dictionary <string, string>()).Start();
        }
Example #13
0
 public override string ToString()
 {
     return(Components.CreateDelimitedText("."));
 }
Example #14
0
        public override void Run(TextReader reader)
        {
            int maxpacket  = Int32.Parse(Connection.ExecuteScalar("select @@max_allowed_packet").ToString());
            int maxdatalen = maxpacket / 3 * 2;

            if (Cfg != null && Cfg.MaxPacketSize > 0 && Cfg.MaxPacketSize < maxdatalen)
            {
                maxdatalen = Cfg.MaxPacketSize;
            }
            var splitter = m_dialect.CreateQuerySplitter();

            splitter.AllowGoSeparator = false;
            splitter.StripComments    = true;

            // mysql splitter strips line comments, /* */ comments remains (they cannot be stripped, unless they contains ! )
            var setre = new Regex(@"((\/\*.*\*\/)?\s?)*(\/\*\!\d+)?\s*set\s+", RegexOptions.IgnoreCase);

            var    scripter  = Connection as IScriptAcceptConnection;
            var    stateless = Connection as IStatelessConnection;
            string originit  = "";

            if (stateless != null)
            {
                originit = stateless.SessionInitScript;
            }

            try
            {
                if (scripter != null && scripter.SendScriptSupported)
                {
                    // HTTP tunnel - SendScript + handle StateLessConnection only here (collect init script)
                    bool collectInit = stateless != null;
                    var  pacdata     = new List <string>();
                    var  init        = new List <string>();
                    int  paclen      = 0;
                    foreach (var item in splitter.Run(reader))
                    {
                        if (collectInit)
                        {
                            if (setre.Match(item.Data).Success)
                            {
                                init.Add(item.Data);
                                continue;
                            }
                            else
                            {
                                collectInit = false;
                                if (!stateless.SessionInitScript.IsEmpty())
                                {
                                    init.Insert(0, stateless.SessionInitScript);
                                }
                                stateless.SessionInitScript = init.CreateDelimitedText("||");
                            }
                        }
                        if (item.Data.TrimStart().StartsWith("DELIMITER ", StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }
                        if (pacdata.Count >= 64 || paclen >= maxdatalen)
                        {
                            SendPacket(scripter, pacdata);
                            pacdata.Clear();
                            paclen = 0;
                        }
                        pacdata.Add(item.Data);
                        paclen += item.Data.Length;
                        ShowProgress();
                    }
                    if (pacdata.Count > 0)
                    {
                        SendPacket(scripter, pacdata);
                        pacdata.Clear();
                    }
                }
                else
                {
                    var pacdata = new StringBuilder();
                    foreach (var item in splitter.Run(reader))
                    {
                        ShowProgress();
                        if (item.Data.TrimStart().StartsWith("DELIMITER ", StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }

                        if (item.Delimiter != ";" || (pacdata.Length + item.Length > maxdatalen && pacdata.Length > 0))
                        {
                            SendPacket(pacdata.ToString());
                            pacdata = new StringBuilder();
                        }
                        if (item.Delimiter != ";")
                        {
                            SendPacket(item.Data);
                        }
                        else
                        {
                            pacdata.Append(item.Data);
                            pacdata.Append(";\n");
                        }
                    }
                    if (pacdata.Length > 0)
                    {
                        SendPacket(pacdata.ToString());
                    }
                }
            }
            finally
            {
                if (stateless != null)
                {
                    stateless.SessionInitScript = originit;
                }
            }
            ReportFinish();
        }
Example #15
0
        protected virtual void RunInserts(IDataQueue queue)
        {
            Connection.SystemConnection.SafeChangeDatabase(DatabaseName);
            var dda = Connection.GetAnyDDA();

            using (DbCommand inscmd = Connection.DbFactory.CreateCommand())
            {
                List <string>   colnames = new List <string>();
                List <string>   vals     = new List <string>();
                ITableStructure ts       = queue.GetRowFormat;
                ITableStructure dst_ts   = DestinationTable;
                foreach (IColumnStructure col in ts.Columns)
                {
                    vals.Add("{" + colnames.Count.ToString() + "}");
                    colnames.Add(col.ColumnName);
                }
                string[]       values         = new string[colnames.Count];
                NameWithSchema table          = DestinationTable.FullName;
                string         insertTemplate = SqlDumper.Format(Connection.Dialect, "^insert ^into %f (%,i) ^values (%,s)", table, colnames, vals);

                bool hasident = HasIdentity(queue);

                DbTransaction trans = Connection.SystemConnection.BeginTransaction();
                inscmd.Connection  = Connection.SystemConnection;
                inscmd.Transaction = trans;

                int           okRowCount = 0, failRowCount = 0;
                List <string> insertErrors = new List <string>();
                try
                {
                    if (hasident)
                    {
                        Connection.RunScript(dmp => { dmp.AllowIdentityInsert(table, true); }, trans, ProgressInfo);
                    }
                    try
                    {
                        int rowcounter = 0;
                        while (!queue.IsEof)
                        {
                            rowcounter++;
                            IBedRecord row = queue.GetRecord();
                            for (int i = 0; i < row.FieldCount; i++)
                            {
                                row.ReadValue(i);
                                values[i] = dda.GetSqlLiteral(row);
                            }
                            inscmd.CommandText = String.Format(insertTemplate, values);

                            if (rowcounter > 10000)
                            {
                                // next transaction
                                trans.Commit();
                                trans.Dispose();
                                trans = Connection.SystemConnection.BeginTransaction();
                                inscmd.Transaction = trans;
                                rowcounter         = 0;
                            }
                            try
                            {
                                inscmd.ExecuteNonQuery();
                                okRowCount++;
                            }
                            catch (Exception err)
                            {
                                if (insertErrors.Count < 10)
                                {
                                    StringBuilder msg = new StringBuilder();
                                    msg.Append(err.Message);
                                    insertErrors.Add(msg.ToString());
                                }
                                failRowCount++;
                            }
                        }
                    }
                    finally
                    {
                        if (hasident)
                        {
                            Connection.RunScript(dmp => { dmp.AllowIdentityInsert(table, false); }, trans, ProgressInfo);
                        }
                    }
                    trans.Commit();
                    if (failRowCount > 0)
                    {
                        ProgressInfo.LogMessageDetail(
                            "INSERT", LogLevel.Error,
                            String.Format("{0}, OK:{1}, FAIL:{2}", Texts.Get("s_error_inserting_into_table$table", "table", DestinationTable.FullName), okRowCount, failRowCount),
                            insertErrors.CreateDelimitedText("\r\n")
                            );
                    }
                    else
                    {
                        ProgressInfo.LogMessage("INSERT", LogLevel.Info, Texts.Get("s_inserted_into_table$table$rows", "table", DestinationTable.FullName, "rows", okRowCount));
                    }
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
Example #16
0
        protected override void RunBulkCopy(IDataQueue queue)
        {
            int           recsInBatch = 0;
            int           okRowCount = 0, failRowCount = 0;
            List <string> insertErrors = new List <string>();
            StringWriter  buf          = null;
            ISqlDumper    dmp          = null;
            int           maxpacket    = Int32.Parse(Connection.SystemConnection.ExecuteScalar("select @@max_allowed_packet").ToString());

            using (DbTransaction tran = Connection.SystemConnection.BeginTransaction())
            {
                try
                {
                    ITableStructure dst = queue.GetRowFormat;
                    while (!queue.IsEof)
                    {
                        IBedRecord rec = queue.GetRecord();
                        if (recsInBatch == 0)
                        {
                            buf = new StringWriter();
                            dmp = Connection.Dialect.CreateDumper(buf);
                            dmp.Put("^insert ^into %f (%,i) ^values ", DestinationTable.FullName,
                                    from c in dst.Columns select c.ColumnName);
                        }
                        else
                        {
                            dmp.Put(", ");
                        }
                        dmp.Put("(%,v)", rec);
                        recsInBatch++;
                        if (recsInBatch >= BatchSize || buf.GetStringBuilder().Length > maxpacket / 4)
                        {
                            string sql   = buf.ToString();
                            int    bytes = (int)(Encoding.UTF32.GetByteCount(sql) + 0x200);
                            try
                            {
                                Connection.SystemConnection.ExecuteNonQuery(sql, Connection.Dialect);
                                okRowCount += recsInBatch;
                            }
                            catch (Exception err)
                            {
                                failRowCount += recsInBatch;
                                if (insertErrors.Count < 10)
                                {
                                    insertErrors.Add(err.Message);
                                }
                            }
                            recsInBatch = 0;
                        }
                    }
                    if (recsInBatch > 0)
                    {
                        Connection.SystemConnection.ExecuteNonQuery(buf.ToString(), Connection.Dialect);
                        okRowCount += recsInBatch;
                    }
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    ProgressInfo.LogMessageDetail(
                        "INSERT", LogLevel.Error,
                        String.Format("{0}", Texts.Get("s_error_inserting_into_table$table", "table", DestinationTable.FullName)), err.ToString());
                    throw;
                }
                tran.Commit();

                if (failRowCount > 0)
                {
                    ProgressInfo.LogMessageDetail(
                        "INSERT", LogLevel.Error,
                        String.Format("{0}, OK:{1}, FAIL:{2}", Texts.Get("s_error_inserting_into_table$table", "table", DestinationTable.FullName), okRowCount, failRowCount),
                        insertErrors.CreateDelimitedText("\r\n")
                        );
                }
                else
                {
                    ProgressInfo.LogMessage("INSERT", LogLevel.Info, Texts.Get("s_inserted_into_table$table$rows", "table", DestinationTable.FullName, "rows", okRowCount));
                }
            }
        }
Example #17
0
        public static bool Run(Action closesplash)
        {
            // debug version, don't check auto-update
            if (!VersionInfo.IsRelease && !VersionInfo.IsBeta)
            {
                return(false);
            }

            if (Framework.Instance.GetCheckNewVersion() == CheckNewVersions.CheckAndDownload)
            {
                if (File.Exists(VersionFile) && File.Exists(InstallExeFile))
                {
                    string   newver = IOTool.LoadTextFile(VersionFile).Trim();
                    DateTime newverdt;
                    try { newverdt = DateTime.ParseExact(IOTool.LoadTextFile(InstallTimestampFile).Trim(), "s", CultureInfo.InvariantCulture); }
                    catch { newverdt = new DateTime(1900, 1, 1); }
                    if (CompareVersions(newver, VersionInfo.VERSION) > 0)
                    {
                        closesplash();
                        var lst = new List <string>();
                        foreach (var lic in LicenseTool.ValidLicenses)
                        {
                            if (lic.UpdatesTo < newverdt)
                            {
                                lst.Add(lic.LongText);
                            }
                        }
                        string msg = Texts.Get("s_install_version$version", "version", newver);
                        if (lst.Count > 0)
                        {
                            msg += "\n" + Texts.Get("s_license_update_expire_warning") + "\n" + lst.CreateDelimitedText("\n");
                        }
                        if (MessageBox.Show(msg, VersionInfo.ProgramTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            System.Diagnostics.Process.Start(InstallExeFile);
                            return(true);
                        }
                    }
                }
            }
            Thread t = new Thread(RunCheckThread);

            t.IsBackground = true;
            t.Start();
            return(false);
        }
Example #18
0
        private string SearchExistingFile(string file, ResolveFileMode mode, params string[] folders)
        {
            foreach (string folder in folders)
            {
                if (folder == null)
                {
                    continue;
                }
                string fn = Path.Combine(folder, file);
                if (System.IO.File.Exists(fn))
                {
                    return(fn);
                }
            }
            var additionalFoldersCtx = this;

            while (additionalFoldersCtx != null)
            {
                if (additionalFoldersCtx._additionalSearchFolders.ContainsKey(mode))
                {
                    foreach (string folder in additionalFoldersCtx._additionalSearchFolders[mode])
                    {
                        string fn = Path.Combine(folder, file);
                        if (System.IO.File.Exists(fn))
                        {
                            return(fn);
                        }
                    }
                }
                additionalFoldersCtx = additionalFoldersCtx._parent;
            }
            if (System.IO.File.Exists(file))
            {
                return(file);
            }

            var allFolders = new List <string>(folders);

            if (_additionalSearchFolders.ContainsKey(mode))
            {
                allFolders.AddRange(_additionalSearchFolders[mode]);
            }
            throw new Exception(String.Format("DBSH-00063 Could not find file {0}, searched in folders {1}", file, allFolders.CreateDelimitedText(";")));
        }
Example #19
0
        private string SearchExistingFile(string file, ResolveFileMode mode, params string[] folders)
        {
            foreach (string folder in folders)
            {
                if (folder == null) continue;
                string fn = Path.Combine(folder, file);
                if (System.IO.File.Exists(fn)) return fn;
            }
            var additionalFoldersCtx = this;
            while (additionalFoldersCtx != null)
            {
                if (additionalFoldersCtx._additionalSearchFolders.ContainsKey(mode))
                {
                    foreach (string folder in additionalFoldersCtx._additionalSearchFolders[mode])
                    {
                        string fn = Path.Combine(folder, file);
                        if (System.IO.File.Exists(fn)) return fn;
                    }
                }
                additionalFoldersCtx = additionalFoldersCtx._parent;
            }
            if (System.IO.File.Exists(file)) return file;

            var allFolders = new List<string>(folders);
            if (_additionalSearchFolders.ContainsKey(mode))
            {
                allFolders.AddRange(_additionalSearchFolders[mode]);
            }
            throw new Exception(String.Format("DBSH-00063 Could not find file {0}, searched in folders {1}", file, allFolders.CreateDelimitedText(";")));
        }
Example #20
0
        protected virtual void RunInserts(ICdlReader reader)
        {
            //Connection.SystemConnection.SafeChangeDatabase(DatabaseName);
            var dda = Connection.GetFactory(ServiceProvider).CreateDataAdapter();

            using (DbCommand inscmd = Connection.CreateCommand())
            {
                List <string> colnames = new List <string>();
                List <string> vals     = new List <string>();
                foreach (var colIndexes in _columnMap.Items)
                {
                    vals.Add("{" + colnames.Count.ToString() + "}");
                    colnames.Add(DestinationTable.Columns[colIndexes.Target].Name);
                }
                string[]       values         = new string[colnames.Count];
                NameWithSchema table          = DestinationTable.FullName;
                string         insertTemplate = SqlDumper.Format(Connection.GetFactory(ServiceProvider), "^insert ^into %f (%,i) ^values (%,s)", table, colnames, vals);

                bool hasident = HasIdentity(reader);

                DbTransaction trans = Connection.BeginTransaction();
                inscmd.Transaction = trans;

                int           okRowCount = 0, failRowCount = 0;
                List <string> insertErrors = new List <string>();
                try
                {
                    if (hasident)
                    {
                        Connection.RunScript(ServiceProvider, dmp => { dmp.AllowIdentityInsert(table, true); }, trans);
                    }
                    try
                    {
                        int rowcounter = 0;
                        while (reader.Read())
                        {
                            rowcounter++;
                            var row = reader;
                            for (int i = 0; i < _columnMap.Items.Count; i++)
                            {
                                row.ReadValue(_columnMap.Items[i].Source);
                                values[i] = dda.GetSqlLiteral(row, new DbTypeString());
                            }
                            inscmd.CommandText = String.Format(insertTemplate, values);

                            if (rowcounter > 10000)
                            {
                                // next transaction
                                trans.Commit();
                                trans.Dispose();
                                trans = Connection.BeginTransaction();
                                inscmd.Transaction = trans;
                                rowcounter         = 0;
                            }
                            try
                            {
                                inscmd.ExecuteNonQuery();
                                okRowCount++;
                            }
                            catch (Exception err)
                            {
                                if (insertErrors.Count < 10)
                                {
                                    StringBuilder msg = new StringBuilder();
                                    msg.Append(err.Message);
                                    insertErrors.Add(msg.ToString());
                                }
                                failRowCount++;
                            }
                        }
                    }
                    finally
                    {
                        if (hasident)
                        {
                            Connection.RunScript(ServiceProvider, dmp => { dmp.AllowIdentityInsert(table, false); }, trans);
                        }
                    }
                    trans.Commit();

                    if (failRowCount > 0)
                    {
                        LogError($"DBSH-00199 Error inserting into table {DestinationTable}, correct inserts {okRowCount}, failed inserts {failRowCount}");
                        LogError(insertErrors.CreateDelimitedText("\n"));
                    }
                    else
                    {
                        LogInfo($"{okRowCount} rows successfully inserted into table {DestinationTable}");
                    }
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
Example #21
0
        protected virtual void RunInserts(ICdlReader reader)
        {
            //Connection.SystemConnection.SafeChangeDatabase(DatabaseName);
            var dda = Connection.GetFactory().CreateDataAdapter();
            using (DbCommand inscmd = Connection.CreateCommand())
            {
                List<string> colnames = new List<string>();
                List<string> vals = new List<string>();
                foreach (var colIndexes in _columnMap.Items)
                {
                    vals.Add("{" + colnames.Count.ToString() + "}");
                    colnames.Add(DestinationTable.Columns[colIndexes.Target].Name);
                }
                string[] values = new string[colnames.Count];
                NameWithSchema table = DestinationTable.FullName;
                string insertTemplate = SqlDumper.Format(Connection.GetFactory(), "^insert ^into %f (%,i) ^values (%,s)", table, colnames, vals);

                bool hasident = HasIdentity(reader);

                DbTransaction trans = Connection.BeginTransaction();
                inscmd.Transaction = trans;

                int okRowCount = 0, failRowCount = 0;
                List<string> insertErrors = new List<string>();
                try
                {
                    if (hasident) Connection.RunScript(dmp => { dmp.AllowIdentityInsert(table, true); }, trans);
                    try
                    {
                        int rowcounter = 0;
                        while (reader.Read())
                        {
                            rowcounter++;
                            var row = reader;
                            for (int i = 0; i < _columnMap.Items.Count; i++)
                            {
                                row.ReadValue(_columnMap.Items[i].Source);
                                values[i] = dda.GetSqlLiteral(row, new DbTypeString());
                            }
                            inscmd.CommandText = String.Format(insertTemplate, values);

                            if (rowcounter > 10000)
                            {
                                // next transaction
                                trans.Commit();
                                trans.Dispose();
                                trans = Connection.BeginTransaction();
                                inscmd.Transaction = trans;
                                rowcounter = 0;
                            }
                            try
                            {
                                inscmd.ExecuteNonQuery();
                                okRowCount++;
                            }
                            catch (Exception err)
                            {
                                if (insertErrors.Count < 10)
                                {
                                    StringBuilder msg = new StringBuilder();
                                    msg.Append(err.Message);
                                    insertErrors.Add(msg.ToString());
                                }
                                failRowCount++;
                            }
                        }
                    }
                    finally
                    {
                        if (hasident) Connection.RunScript(dmp => { dmp.AllowIdentityInsert(table, false); }, trans);
                    }
                    trans.Commit();

                    if (failRowCount > 0)
                    {
                        LogError($"DBSH-00199 Error inserting into table {DestinationTable}, correct inserts {okRowCount}, failed inserts {failRowCount}");
                        LogError(insertErrors.CreateDelimitedText("\n"));

                    }
                    else
                    {
                        LogInfo($"{okRowCount} rows successfully inserted into table {DestinationTable}");
                    }
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }