Ejemplo n.º 1
0
        public void TestParseTableNested()
        {
            using (var docStream = AssemblyResourceHelper.GetResourceStream(this, "if_in_table_document.xml"))
            {
                doc = XDocument.Load(docStream);

                var expectedRootProcessor  = new RootProcessor();
                var expectedTableProcessor = new TableProcessor();
                expectedTableProcessor.AddProcessor(new IfProcessor());
                expectedRootProcessor.AddProcessor(expectedTableProcessor);
                var expectedTableProcessors = new List <ITagProcessor>(expectedTableProcessor.Processors);
                var expectedRootProcessors  = new List <ITagProcessor>(expectedRootProcessor.Processors);

                var actualRootProcessor = new RootProcessor();
                generalParser.Parse(actualRootProcessor, doc.Root);
                var actualRootProcessors = new List <ITagProcessor>(actualRootProcessor.Processors);

                Assert.AreEqual(expectedRootProcessors.Count, actualRootProcessors.Count);
                Assert.AreEqual(expectedRootProcessors[0].GetType(), actualRootProcessors[0].GetType());
                var actualTableProcessors = new List <ITagProcessor>(expectedRootProcessors[0].Processors);
                Assert.AreEqual(expectedTableProcessors.Count, actualTableProcessors.Count);
                Assert.AreEqual(expectedTableProcessors[0].GetType(), actualTableProcessors[0].GetType());
                Assert.AreEqual(expectedTableProcessors[0].Processors.Count, actualTableProcessors[0].Processors.Count);
            }
        }
        private void buttonMapFields_Click(object sender, EventArgs e)
        {
            if (comboBoxTableName.SelectedIndex == -1)
            {
                MessageBox.Show("Select source table first");
            }

            FormFieldsMap mapForm = new FormFieldsMap();

            mapForm.targetFields = tp.GetTransformFields();
            mapForm.inputFields  = tp.InputDatabase.GetFields(tp.tableName);
            //apply current settings
            //DeserializeFieldsMap(textBoxFieldsMapping.Text);
            if (mapForm.ShowDialog() == DialogResult.OK)
            {
                //Update fields mapping from UI
                mapForm.getMapping();

                tp.InputFieldNamesMap.Clear();
                foreach (var pair in mapForm.Target2InputFields)
                {
                    //Save as Inut field to target field map
                    tp.InputFieldNamesMap.Add(new KeyValuePair <string, string>(pair.Value, pair.Key));
                }
                textBoxFieldsMapping.Text = TableProcessor.SerializeFieldsMap(tp.InputFieldNamesMap);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Fills the variables ucDokuViewerGdPicture1.AllTableLines and allTableColumns and displays all the extracted text within the textBox
        /// </summary>
        private void butTest_Click(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;

            var extractionResult = ucDokuViewerGdPicture1.ExtractAllTableLinesAndColumns();

            foreach (var extractionObject in extractionResult)
            {
                var allTableLines   = extractionObject[0];
                var allTableColumns = extractionObject[1];

                textBox1.Text = textBox1.Text + "All Table Lines:" + Environment.NewLine + Environment.NewLine
                                + allTableLines + Environment.NewLine + Environment.NewLine + Environment.NewLine
                                + "All Table Columns:" + Environment.NewLine + Environment.NewLine
                                + allTableColumns + Environment.NewLine + Environment.NewLine
                                + "__________________________________________________" + Environment.NewLine + Environment.NewLine;

                var tableProcessor = new TableProcessor(Application.StartupPath);
                var table          = tableProcessor.BuildTableFromLinesAndColumns(tableProcessor.LoadTableLinesFromString(allTableLines), tableProcessor.LoadTableColumnsFromString(allTableColumns));

                var tableViewer = new frmTableViewer();
                tableViewer.ShowTable(table);
                tableViewer.Show();
            }
        }
Ejemplo n.º 4
0
        public void TestProcessNullTag()
        {
            var processor = new TableProcessor();

            processor.DataReader = this.dataReader;
            processor.Process();
        }
        public void TestUploadOfTableWithDateFieldsThatAreReservedWords()
        {
            TableProcessor tp        = new TableProcessor();
            const String   tableName = "SGIBKHDR";

            tp.Process(VfpConnectionString, tableName, SqlConnectionString, tableName);
            TestContext.WriteLine("TestUploadOfTableWithDateFieldsThatAreReservedWords complete");
        }
Ejemplo n.º 6
0
        public void TestProcessNullReader()
        {
            var processor = new TableProcessor {
                TableTag = this.GetTableTag()
            };

            processor.Process();
        }
        public void Generate(XElement startTableElement, XElement endTableElement, DataReader dataReader)
        {
            var coreParser = new CoreTableParser(true);
            var tag        = coreParser.Parse(startTableElement, endTableElement);
            var processor  = new TableProcessor()
            {
                DataReader = dataReader, TableTag = tag
            };

            processor.Process();
        }
Ejemplo n.º 8
0
        private static void BuildDocumentation(string content, List <string> matches)
        {
            ICollection <PgTable> tables = TableProcessor.GetTables(Program.SchemaPattern, Program.xSchemaPattern);

            content = content.Replace("[DBName]", Program.Database.ToUpperInvariant());

            content = Parsers.TableParser.Parse(content, matches, tables);

            FileHelper.WriteFile(content, OutputPath);
            SequencesRunner.Run();
        }
        /// <summary>
        /// Builds the table processor objects.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <param name="sqlConnectionStringBuilder">The SQL connection string builder.</param>
        /// <param name="builder">The builder.</param>
        /// <param name="fileWriter">The file writer.</param>
        private static void BuildTableProcessorObjects(ServiceCollection services, SqlConnectionStringBuilder sqlConnectionStringBuilder, IConfigurationRoot builder,
                                                       IFileWriter fileWriter)
        {
            string directoryToWriteTo = builder.GetValue <string>("baseDirectory");

            ITableProcessor tableProcessor = new TableProcessor(directoryToWriteTo, fileWriter, sqlConnectionStringBuilder.InitialCatalog);

            services.AddSingleton <ITableProcessor>(tableProcessor);

            services.AddSingleton <ITableMediator, TableMediator>();
        }
Ejemplo n.º 10
0
        private bool LoadOrOpen(TableProcessor.LoadMode lm, string path)
        {
            string msg    = "";
            var    status = _table.LoadOrOpen(lm, path);

            if (status == TableProcessor.LoadStatus.OK)
            {
                if (TableProcessor.LoadModeToContentMode(lm) == TableProcessor.ContentMode.Normal)
                {
                    this._tcThreatsList.SelectedIndex = 0;
                    this._tbUpdatedThreats.IsEnabled  = false;
                    _paginatorNormal = new Paginator(this._dgAllThreatsList, _table.GetShortContent(TableProcessor.ContentMode.Normal), _ElementsOnPageComboBox);
                    BtnNext_Clicked(this._dgAllThreatsList, null);

                    msg = (lm == TableProcessor.LoadMode.OpenExisting ? "Открыто успешно!" : "Загружено успешно!");
                }
                else
                {
                    _paginatorNormal = new Paginator(this._dgAllThreatsList, _table.GetShortContent(TableProcessor.ContentMode.Normal), _ElementsOnPageComboBox);
                    this._tcThreatsList.SelectedIndex = 0;
                    BtnNext_Clicked(this._dgAllThreatsList, null);

                    this._tbUpdatedThreats.IsEnabled = true;

                    _paginatorChanges = new Paginator(this._dgChangedList, _table.GetShortContent(TableProcessor.ContentMode.Changed), _ElementsOnPageComboBox);
                    this._tcThreatsList.SelectedIndex = 1;
                    BtnNext_Clicked(this._dgChangedList, null);

                    msg  = "Обновлено успешно!\n";
                    msg += (_paginatorChanges._DataLength > 0 ? $"Обновленных записей: {_paginatorChanges._DataLength}"
                        : "Вот только ничего не обновилось...\nКак часто ФСТЭК делает обновы???");
                }
            }
            else // smth went wrong - choose msg
            {
                switch (status)
                {
                case TableProcessor.LoadStatus.NetWorkProblems:
                    msg = "Что-то пошло не так!\nСеть накрылась!";
                    break;

                case TableProcessor.LoadStatus.FileProblems:
                    msg = "Что-то пошло не так!\nПроблемы с файлом!\nСтоит попробовать другой...";
                    break;

                case TableProcessor.LoadStatus.SameFile:
                    msg = "Незачем открывать тот же самый файл.";
                    break;
                }
            }
            UserMsgWndShow(msg);
            return(status == TableProcessor.LoadStatus.OK);
        }
Ejemplo n.º 11
0
        void SetMappings()
        {
            List <KeyValuePair <string, string> > map = new List <KeyValuePair <string, string> >();

            //Fields to map
            foreach (RepeaterItem row in Repeater1.Items)
            {
                Label        label = (Label)row.FindControl("Label1");
                DropDownList list  = (DropDownList)row.FindControl("DropDownList2");
                map.Add(new KeyValuePair <string, string>(list.SelectedValue, label.Text));
            }
            Session["Mappings"] = TableProcessor.SerializeFieldsMap(map);
        }
Ejemplo n.º 12
0
        public void TestParse()
        {
            var expectedTableProcessor = new TableProcessor();
            var expectedIfProcessor    = new IfProcessor();

            expectedIfProcessor.AddProcessor(new TextProcessor());
            expectedTableProcessor.AddProcessor(new TextProcessor());
            expectedTableProcessor.AddProcessor(expectedIfProcessor);
            var expectedRepeaterProcessor = new RepeaterProcessor();

            expectedRepeaterProcessor.AddProcessor(new TextProcessor());
            var expectedRootProcessor = new RootProcessor();

            expectedRootProcessor.AddProcessor(expectedTableProcessor);
            expectedRootProcessor.AddProcessor(expectedRepeaterProcessor);

            var actualRootProcessor = new RootProcessor();

            generalParser.Parse(actualRootProcessor, this.doc.Root);

            Assert.AreEqual(2, actualRootProcessor.Processors.Count);
            var actualInnerRootProcessors = new List <ITagProcessor>(actualRootProcessor.Processors);

            Assert.AreEqual(typeof(TableProcessor), actualInnerRootProcessors[0].GetType());
            Assert.AreEqual(typeof(RepeaterProcessor), actualInnerRootProcessors[1].GetType());

            var actualTableProcessor = actualInnerRootProcessors[0];

            Assert.AreEqual(2, actualTableProcessor.Processors.Count);
            var actualInnerTableProcessors = new List <ITagProcessor>(actualTableProcessor.Processors);

            Assert.AreEqual(typeof(TextProcessor), actualInnerTableProcessors[0].GetType());
            Assert.AreEqual(typeof(IfProcessor), actualInnerTableProcessors[1].GetType());

            Assert.AreEqual(0, actualInnerTableProcessors[0].Processors.Count);
            var actualIfProcessor = actualInnerTableProcessors[1];

            Assert.AreEqual(1, actualIfProcessor.Processors.Count);
            var actualInnerIfProcessors = new List <ITagProcessor>(actualIfProcessor.Processors);

            Assert.AreEqual(typeof(TextProcessor), actualInnerIfProcessors[0].GetType());

            var actualRepeaterProcessor = actualInnerRootProcessors[1];

            Assert.AreEqual(1, actualRepeaterProcessor.Processors.Count);
            var actualInnerRepeaterProcessors = new List <ITagProcessor>(actualRepeaterProcessor.Processors);

            Assert.AreEqual(typeof(TextProcessor), actualInnerRepeaterProcessors[0].GetType());
            Assert.AreEqual(0, actualInnerRepeaterProcessors[0].Processors.Count);
        }
Ejemplo n.º 13
0
        public UploadLauncher(IDictionary <String, String> connStrs, IBatchSizeProvider batchSizeProvider, RestartParameter restartDetails)
        {
            ConnectionStrings = new Dictionary <String, String>();
            IList <String> connectionNames = new List <String>()
            {
                Constants.ConnectionNames.Host.ToUpper(), Constants.ConnectionNames.POS.ToUpper(), Constants.ConnectionNames.Sql.ToUpper()
            };

            foreach (KeyValuePair <String, String> kvp in connStrs)
            {
                String key = kvp.Key.ToUpper();
                if (connectionNames.Contains(key))
                {
                    ConnectionStrings.Add(key, kvp.Value);
                }
            }

            IList <String> requiredConnectionNames = new List <String>()
            {
                Constants.ConnectionNames.Host.ToUpper(), Constants.ConnectionNames.Sql.ToUpper()
            };

            foreach (String connName in requiredConnectionNames)
            {
                if (!ConnectionStrings.ContainsKey(connName))
                {
                    throw new ApplicationException("No connection string found for connection name " + connName);
                }
            }

            foreach (KeyValuePair <String, String> kvp in ConnectionStrings)
            {
                if (kvp.Key.Equals(Constants.ConnectionNames.Sql, StringComparison.InvariantCultureIgnoreCase))
                {
                    SqlConnectionString = kvp.Value;
                }
                if (kvp.Key.Equals(Constants.ConnectionNames.Host, StringComparison.InvariantCultureIgnoreCase))
                {
                    HostConnectionString = kvp.Value;
                }
            }

            RestartParameter  = restartDetails;
            batchSizeProvider = batchSizeProvider ?? new DiTableOrDefaultBatchSizeProvider(HostConnectionString);
            TableProcessor    = new TableProcessor(batchSizeProvider);
        }
        public void TestUploadWithAsciiZero()
        {
            const String tableName = "IN_WATRM";

            Helper.ExecuteSqlNonQuery(SqlConnectionString, "DELETE FROM " + tableName);

            TableProcessor tp = new TableProcessor();

            tp.Process(VfpConnectionString, tableName, SqlConnectionString, tableName);

            DataTable dt = Helper.GetSqlDataTable(SqlConnectionString, "select charindex(char(0),cast(background as varchar(max))) from " + tableName);

            foreach (DataRow row in dt.Rows)
            {
                Assert.IsTrue(Convert.ToInt32(row[0]) > 0);
            }
        }
        public void The_Tables_Still_Order_Correctly()
        {
            TableProcessor processor = new TableProcessor();

            Table leftTable  = new Table("Table1");
            Table rightTable = new Table("Table1");

            var leftTables = new List <ITable> {
                leftTable
            };
            var rightTables = new List <ITable> {
                rightTable, new Table("aaaTable2")
            };

            var tableSet = processor.GetEqualTables(leftTables, rightTables);

            Assert.That(tableSet.Count(), Is.EqualTo(1));
            Assert.That(tableSet.First().Key, Is.SameAs(leftTable));
            Assert.That(tableSet.First().Value, Is.SameAs(rightTable));
        }
        public void TestBasicUpload()
        {
            const String tableName             = "IN_MSG";
            String       getCountCommandString = "SELECT COUNT(*) FROM " + tableName;
            int          vfpRowCount           = Convert.ToInt32(Helper.GetOleDbScaler(VfpConnectionString, getCountCommandString));
            int          vfpNonDeletedRowCount = Convert.ToInt32(Helper.GetOleDbScaler(VfpConnectionString, getCountCommandString + " WHERE NOT DELETED()"));
            int          vfpDeletedRowCount    = Convert.ToInt32(Helper.GetOleDbScaler(VfpConnectionString, getCountCommandString + " WHERE DELETED()"));

            Assert.IsTrue(vfpNonDeletedRowCount > 0, "Expected 1 or more non-deleted rows");
            Assert.IsTrue(vfpDeletedRowCount > 0, "Expected 1 or more deleted rows");

            // Clear out the SQL table
            Helper.ExecuteSqlNonQuery(SqlConnectionString, "DELETE FROM " + tableName);
            Assert.AreEqual(0, (int)Helper.GetSqlScaler(SqlConnectionString, getCountCommandString));

            // Import from VFP
            TableProcessor tp = new TableProcessor();

            tp.Process(bogusVfpConnectionString, tableName, SqlConnectionString, tableName);

            // Make sure rowcounts are correct
            int actualRowCount   = Convert.ToInt32(Helper.GetSqlScaler(SqlConnectionString, getCountCommandString));
            int expectedRowCount = Convert.ToInt32(Helper.GetOleDbScaler(VfpConnectionString, getCountCommandString));

            Assert.AreEqual(actualRowCount, expectedRowCount);

            // Check handling of Deleted()
            int sqlDeletedRowCount = Convert.ToInt32(Helper.GetSqlScaler(SqlConnectionString, getCountCommandString + String.Format(" WHERE {0} = 1", Constants.DILayer.DeletedColumnName)));

            Assert.AreEqual(sqlDeletedRowCount, vfpDeletedRowCount);

            // Check for nullDates
            String nullDateRowCountCmdStr = getCountCommandString + " WHERE mscldate is null or msBegin is null or msDate is null";
            int    nullDateRowCount       = Convert.ToInt32(Helper.GetSqlScaler(SqlConnectionString, nullDateRowCountCmdStr));

            Assert.IsTrue(nullDateRowCount > 0);
            // Check for non nullDates
            nullDateRowCountCmdStr = getCountCommandString + " WHERE mscldate is not null or msBegin is not null or msDate is not null";
            nullDateRowCount       = Convert.ToInt32(Helper.GetSqlScaler(SqlConnectionString, nullDateRowCountCmdStr));
            Assert.IsTrue(nullDateRowCount > 0);
        }
        private void buttonStart_Click(object sender, System.EventArgs e)
        {
            buttonStart.Enabled = false;
            try
            {
                string filename    = textBoxInputFileName.Text.Trim();
                string outfilename = textBoxOutputFileName.Text.Trim();
                //extract settings
                tp.InputDatabase = DatabaseAdapterFactory.CreateReader(Path.GetExtension(filename), CheckBoxEditMode.Checked);

                tp.InputDatabase.FileName = filename;
                //transform settings
                tp.tableName          = comboBoxTableName.Text;
                tp.InputFieldNamesMap = TableProcessor.DeserializeFieldsMap(textBoxFieldsMapping.Text);

                //load settings

                //If Edit mode - copy original and open for wrtiting
                if (CheckBoxEditMode.Checked)
                {
                    tp.OutputDatabase = DatabaseAdapterFactory.CreateWriter(Path.GetExtension(outfilename));
                    tp.ProcessMode    = ProcessMode.pmEdit;
                }

                tp.OutputDatabase.FileName = outfilename;

                tp.Progress = new ProgressBarMonitor(toolStripProgressBar1, toolStripStatusLabel1, 100);

                int.TryParse(textBoxOffset.Text, out tp.ProcessOffset);

                tp.Process();

                string Msg = Path.GetFileName(tp.InputDatabase.FileName) + " processing complete";
                MessageBox.Show(this, Msg, "Results");
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message + " " + ex.StackTrace, "Error");
            }
            buttonStart.Enabled = true;
        }
        public void TestUploadOfTableWithConversionActions()
        {
            const String tableName = "IN_SPBL";

            String triggerName          = tableName + "_PackageDetail_CurrentVersions_Rebuild";
            string currentVersionsTable = tableName + "_PackageDetail_CurrentVersions";
            String pkgDetailProc        = tableName + "_GetPackageDetail";

            List <String> dropCmds = new List <String>();
            StringBuilder sb       = new StringBuilder();

            sb.AppendLine("IF EXISTS(SELECT* FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[{0}]'))");
            sb.AppendLine("DROP TRIGGER {0}");
            dropCmds.Add(String.Format(sb.ToString(), triggerName));

            sb.Clear();
            sb.AppendLine("IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}')");
            sb.AppendLine("DROP TABLE {0}");
            dropCmds.Add(String.Format(sb.ToString(), currentVersionsTable));

            sb.Clear();
            sb.AppendLine("IF EXISTS(SELECT name FROM  sysobjects WHERE Name = '{0}' AND[Type] = 'P')");
            sb.AppendLine("DROP PROCEDURE {0}");
            dropCmds.Add(String.Format(sb.ToString(), pkgDetailProc));


            foreach (String dropCmd in dropCmds)
            {
                Helper.ExecuteSqlNonQuery(SqlConnectionString, dropCmd);
            }

            ITableProcessor tblProc = new TableProcessor(new DiTableOrDefaultBatchSizeProvider(VfpConnectionString));

            tblProc.Process(VfpConnectionString, tableName, SqlConnectionString, tableName);

            // Make sure table exists
            int rowCount = (int)Helper.GetSqlScaler(SqlConnectionString, "SELECT COUNT(*) FROM " + currentVersionsTable);

            Assert.IsTrue(rowCount > 0);
        }
Ejemplo n.º 19
0
        protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            Session["progress"] = new BaseProgress();
            SetMappings();
            //Start Processing
            TableProcessorNS.TableProcessor tp = new TableProcessorNS.TableProcessor();
            tp.Progress = (BaseProgress)Session["progress"];

            string inputFileName  = Session["InputFileName"].ToString().Trim();
            string outputFileName = Path.Combine(Path.GetDirectoryName(inputFileName), TextBoxOutputFileName.Text);

            tp.InputDatabase          = DatabaseAdapterFactory.CreateReader(Path.GetExtension(inputFileName), CheckBoxEditMode.Checked);
            tp.InputDatabase.FileName = inputFileName;
            tp.InputDatabase.Connect(inputFileName);
            List <string> tables = (List <string>)Session["tables"];

            tp.tableName = tables[0];
            List <string> modules = (List <string>)Session["Modules"];

            tp.SetRecordProcessor(Server.MapPath(Path.Combine("Modules", modules[0])));

            tp.InputFieldNamesMap = TableProcessor.DeserializeFieldsMap((string)Session["Mappings"]);



            //If Edit mode - copy original and open for wrtiting
            if (CheckBoxEditMode.Checked)
            {
                tp.OutputDatabase = DatabaseAdapterFactory.CreateWriter(Path.GetExtension(outputFileName));
                tp.ProcessMode    = ProcessMode.pmEdit;
            }

            tp.OutputDatabase.FileName = outputFileName;

            Thread run = new Thread(new ThreadStart(tp.Process));

            run.Start();
            Response.Write("Process started");
        }
Ejemplo n.º 20
0
        private void frmTableProcessor_Load(object sender, EventArgs e)
        {
            var processor = new TableProcessor(Path.Combine(Application.StartupPath, "TableFiles"));

            var tableResult = processor.RunDemo();



            //for (int i = 0; i < tableColumns.Count; i++)
            //{
            //    dataGridView1.Columns.Add(i.ToString(), i.ToString());
            //}

            //dataGridView1.Rows.Add(tableColumns.First());

            var twoD   = tableResult.Table;
            int height = twoD.GetLength(0);
            int width  = twoD.GetLength(1);

            this.dataGridView1.ColumnCount = width;

            for (int r = 0; r < height; r++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(this.dataGridView1);

                for (int c = 0; c < width; c++)
                {
                    row.Cells[c].Value = twoD[r, c];
                }

                this.dataGridView1.Rows.Add(row);
            }


            //    dataGridView1.DataSource = tableArray;
        }
        /// <summary>
        /// Do parsing
        /// </summary>
        public override XElement Parse(ITagProcessor parentProcessor, XElement startElement)
        {
            this.ValidateStartTag(startElement, "Table");

            if (parentProcessor == null)
            {
                throw new ArgumentNullException();
            }

            var endTableTag = this.TryGetRequiredTags(startElement, "EndTable").First();
            var coreParser  = new CoreTableParser(false);
            var tag         = coreParser.Parse(startElement, endTableTag);
            var processor   = new TableProcessor {
                TableTag = tag
            };

            if (TraverseUtils.ElementsBetween(startElement, endTableTag).Any())
            {
                this.GoDeeper(processor, TraverseUtils.ElementsBetween(startElement, endTableTag).First());
            }
            parentProcessor.AddProcessor(processor);

            return(endTableTag);
        }
Ejemplo n.º 22
0
 public PhotoCreator(TableProcessor t)
 {
     table = t;
     photos = new List<Photo>();
 }
Ejemplo n.º 23
0
        public DatabaseMergeResult MergeDatabases(IDatabase db1, IDatabase db2)
        {
            DatabaseMergeResult mergeResult = new DatabaseMergeResult();

            #region Tables
            IEnumerable<ITable> tables1 = db1.Tables;
            IEnumerable<ITable> tables2 = db2.Tables;

            List<ITable> newTables = tables1.Compliment(tables2).ToList();
            List<ITable> removedTables = tables2.Compliment(tables1).ToList();

            // Check for changed tables.
            Func<ITable, string> sorter = n => n.Name;
            Table.TableComparer comparer = new Table.TableComparer();
            IEnumerable<ITable> intersection1 = tables1.Intersect(tables2, comparer).OrderBy(sorter);
            var commonItems = intersection1.Zip(tables2.Intersect(tables1, comparer).OrderBy(sorter));

            foreach (var memberPair in commonItems)
                if (memberPair.Key.HasChanges(memberPair.Value))
                    mergeResult.AddTableOperation(new TableChangeOperation(memberPair.Key, memberPair.Value));

            foreach (var t in newTables)
                mergeResult.AddTableOperation(new TableAdditionOperation(db1, t));

            foreach (var t in removedTables)
                mergeResult.AddTableOperation(new TableRemovalOperation(t));

            TableProcessor processor = new TableProcessor();
            var tableResults = processor.ProcessTables(tables1, tables2);
            mergeResult.CopyFrom(tableResults);
            #endregion

            #region Views
            IEnumerable<ITable> views1 = db1.Views;
            IEnumerable<ITable> views2 = db2.Views;

            List<ITable> newViews = views1.Compliment(views2).ToList();
            List<ITable> removedViews = views2.Compliment(views1).ToList();

            // Check for changed tables.
            IEnumerable<ITable> viewsIntersection1 = views1.Intersect(views2, comparer).OrderBy(sorter);
            var commonViewItems = intersection1.Zip(views2.Intersect(views1, comparer).OrderBy(sorter));

            foreach (var memberPair in commonViewItems)
                if (memberPair.Key.HasChanges(memberPair.Value))
                    mergeResult.AddViewOperation(new TableChangeOperation(memberPair.Key, memberPair.Value));

            foreach (var t in newViews)
                mergeResult.AddViewOperation(new TableAdditionOperation(db1, t));

            foreach (var t in removedViews)
                mergeResult.AddViewOperation(new TableRemovalOperation(t));

            TableProcessor viewProcessor = new TableProcessor();
            var viewResults = processor.ProcessTables(views1, views2);
            mergeResult.CopyFrom(viewResults);
            #endregion

            return mergeResult;
        }
Ejemplo n.º 24
0
        public void TestProcess()
        {
            var tableTag = this.GetTableTag();

            Func <XElement, IEnumerable <TableElement> > MakeTableElementCallback = element =>
            {
                var tags = element.Descendants(WordMl.SdtName).ToList();

                var index =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemindex"));
                var subject =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemtext") && e.Element(WordMl.SdtContentName).Value == "./Subject");
                var issueDate =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemtext") && e.Element(WordMl.SdtContentName).Value == "./IssueDate");
                var expireDate =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemtext") && e.Element(WordMl.SdtContentName).Value == "./ExpireDate");
                var itemIf =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemif"));
                var endItemIf =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("enditemif"));


                IEnumerable <TableElement> tableElements = new TableElement[]
                {
                    new TableElement
                    {
                        IsIndex  = true,
                        IsItem   = false,
                        IsItemIf = false,
                        StartTag = index,
                    },
                    new TableElement
                    {
                        IsItemIf    = true,
                        IsIndex     = false,
                        IsItem      = false,
                        StartTag    = itemIf,
                        EndTag      = endItemIf,
                        Expression  = "./HasSubject",
                        TagElements =
                            new TableElement[]
                        {
                            new TableElement
                            {
                                IsItem     = true,
                                IsIndex    = false,
                                IsItemIf   = false,
                                StartTag   = subject,
                                Expression = "./Subject"
                            }
                        }
                    },
                    new TableElement
                    {
                        IsItem     = true,
                        IsIndex    = false,
                        IsItemIf   = false,
                        StartTag   = issueDate,
                        Expression = "./IssueDate"
                    },
                    new TableElement
                    {
                        IsItem     = true,
                        IsIndex    = false,
                        IsItemIf   = false,
                        StartTag   = expireDate,
                        Expression = "./ExpireDate"
                    }
                };
                return(tableElements);
            };

            tableTag.MakeTableElementCallback = MakeTableElementCallback;

            var tableProcessor = new TableProcessor
            {
                TableTag   = tableTag,
                DataReader = this.dataReader
            };

            tableProcessor.Process();

            Assert.IsFalse(this.documentRoot.Elements(WordMl.SdtName).Any(element => element.IsSdt()));
            var expectedTableStructure = new[]
            {
                new[] { "#", "Certificate", "Date" },
                new[] { string.Empty, string.Empty, "Issue", "Expiration" },
                new[] { "1", "2", "3", "4" },
                new[] { "1", "Subject1", "01.04.2014", "01.10.2015" },
                new[] { "2", "Subject2", "01.03.2014", "01.09.2015" },
                new[] { "3", "Subject3", "01.01.2011", "01.01.2012" },
                new[] { "This", "row", "stays", "untouched" },
            };

            var rows = tableTag.Table.Elements(WordMl.TableRowName).ToList();

            Assert.AreEqual(expectedTableStructure.Count(), rows.Count());
            int rowIndex = 0;

            foreach (var row in rows)
            {
                var expectedRow = expectedTableStructure[rowIndex];

                var cellsInRow = row.Elements(WordMl.TableCellName).ToList();

                Assert.AreEqual(expectedRow.Count(), cellsInRow.Count());

                int cellIndex = 0;
                foreach (var cell in cellsInRow)
                {
                    Assert.AreEqual(expectedRow[cellIndex], cell.Value);
                    cellIndex++;
                }

                rowIndex++;
            }

            /*
             * var tagsBetween =
             *  tableTag.TagTable.ElementsAfterSelf().Where(element => element.IsBefore(tableTag.TagContent));
             * Assert.IsFalse(tagsBetween.Any());
             *
             * tagsBetween =
             *  tableTag.TagEndContent.ElementsAfterSelf().Where(element => element.IsBefore(tableTag.TagEndTable));
             * Assert.IsFalse(tagsBetween.Any());*/
            this.ValidateTagsRemoved(this.documentRoot);
        }
Ejemplo n.º 25
0
        public void TestProcessWithStaticCells()
        {
            XElement root;

            using (var docStream = AssemblyResourceHelper.GetResourceStream(this, "TableProcessorWithStaticCellsTest.xml"))
            {
                var document = XDocument.Load(docStream);
                root = document.Root.Element(WordMl.BodyName);
            }
            var tableTag = this.GetTableTag(root);

            Func <XElement, IEnumerable <TableElement> > MakeTableElementCallback = element =>
            {
                var tags = element.Descendants(WordMl.SdtName).ToList();

                var index =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemindex"));
                var issueDate =
                    tags.Find(
                        e =>
                        e.Element(WordMl.SdtPrName)
                        .Element(WordMl.TagName)
                        .Attribute(WordMl.ValAttributeName)
                        .Value.ToLower()
                        .Equals("itemtext") && e.Element(WordMl.SdtContentName).Value == "./IssueDate");


                IEnumerable <TableElement> tableElements = new TableElement[]
                {
                    new TableElement
                    {
                        IsIndex  = true,
                        IsItem   = false,
                        IsItemIf = false,
                        StartTag = index,
                    },
                    new TableElement
                    {
                        IsItem     = true,
                        IsIndex    = false,
                        IsItemIf   = false,
                        StartTag   = issueDate,
                        Expression = "./IssueDate"
                    },
                };
                return(tableElements);
            };

            tableTag.MakeTableElementCallback = MakeTableElementCallback;

            var tableProcessor = new TableProcessor
            {
                TableTag   = tableTag,
                DataReader = this.dataReader
            };

            tableProcessor.Process();

            var expectedTableStructure = new[]
            {
                new[] { "#", "Certificate", "Date" },
                new[] { string.Empty, string.Empty, "Issue", "Expiration" },
                new[] { "1", "2", "3", "4" },
                new[] { "1", "First static text", "01.04.2014", "Second static text" },
                new[] { "2", "First static text", "01.03.2014", "Second static text" },
                new[] { "3", "First static text", "01.01.2011", "Second static text" },
                new[] { "This", "row", "stays", "untouched" },
            };

            var rows = tableTag.Table.Elements(WordMl.TableRowName).ToList();

            Assert.AreEqual(expectedTableStructure.Count(), rows.Count());
            int rowIndex = 0;

            foreach (var row in rows)
            {
                var expectedRow = expectedTableStructure[rowIndex];

                var cellsInRow = row.Elements(WordMl.TableCellName).ToList();

                Assert.AreEqual(expectedRow.Count(), cellsInRow.Count());

                int cellIndex = 0;
                foreach (var cell in cellsInRow)
                {
                    Assert.AreEqual(expectedRow[cellIndex], cell.Value);
                    cellIndex++;
                }

                rowIndex++;
            }
            this.ValidateTagsRemoved(root);
        }
Ejemplo n.º 26
0
        public void TestProcessItemIfCells()
        {
            XElement root;

            using (var docStream = AssemblyResourceHelper.GetResourceStream(this, "TableItemIfsTest.xml"))
            {
                var document = XDocument.Load(docStream);
                root = document.Root.Element(WordMl.BodyName);
            }
            var tableTag = this.GetTableTag(root);

            XDocument data;

            using (var docStream = AssemblyResourceHelper.GetResourceStream(this, "TableItemIfsData.xml"))
            {
                data = XDocument.Load(docStream);
            }

            Func <XElement, IEnumerable <TableElement> > MakeTableElementCallback = element =>
            {
                var cells = element.Descendants(WordMl.TableCellName).ToList();
                ICollection <TableElement> tableElements = new Collection <TableElement>();
                foreach (var cell in cells)
                {
                    var cellTags = cell.Descendants(WordMl.SdtName).ToList();
                    var firtsIf  = new TableElement
                    {
                        IsIndex     = false,
                        IsItem      = false,
                        IsItemIf    = true,
                        StartTag    = cellTags[0],
                        EndTag      = cellTags[2],
                        Expression  = cellTags[0].Value,
                        TagElements =
                            new TableElement[]
                        {
                            new TableElement
                            {
                                IsIndex    = false,
                                IsItemIf   = false,
                                IsItem     = true,
                                StartTag   = cellTags[1],
                                Expression = cellTags[1].Value,
                            }
                        }
                    };

                    var secondIf = new TableElement
                    {
                        IsIndex     = false,
                        IsItem      = false,
                        IsItemIf    = true,
                        StartTag    = cellTags[3],
                        EndTag      = cellTags[5],
                        Expression  = cellTags[3].Value,
                        TagElements =
                            new TableElement[]
                        {
                            new TableElement
                            {
                                IsIndex    = false,
                                IsItemIf   = false,
                                IsItem     = true,
                                StartTag   = cellTags[4],
                                Expression = cellTags[4].Value,
                            }
                        }
                    };

                    tableElements.Add(firtsIf);
                    tableElements.Add(secondIf);
                }

                return(tableElements);
            };

            tableTag.MakeTableElementCallback = MakeTableElementCallback;

            var tableProcessor = new TableProcessor
            {
                TableTag   = tableTag,
                DataReader = DataReaderFactory.CreateReader(data)
            };

            tableProcessor.Process();

            var expectedTableStructure = new[]
            {
                new[] { "#", "Certificate", "Date" },
                new[] { string.Empty, string.Empty, "Issue", "Expiration" },
                new[] { "1", "2", "3", "4" },
                new[] { "row1 - value1", "row1 - value2", "row1 - value3", "row1 - value4" },
                new[] { "row2 - value1", "row2 - value2", "row2 - value3", "row2 - value4" },
                new[] { "row3 - value1", "row3 - value2", "row3 - value3", "row3 - value4" },
                new[] { "row4 - value1", "row4 - value2", "row4 - value3", "row4 - value4" },
                new[] { "row5 - value1", "row5 - value2", "row5 - value3", "row5 - value4" },
                new[] { "This", "row", "stays", "untouched" },
            };

            var rows = tableTag.Table.Elements(WordMl.TableRowName).ToList();

            Assert.AreEqual(expectedTableStructure.Count(), rows.Count());
            int rowIndex = 0;

            foreach (var row in rows)
            {
                var expectedRow = expectedTableStructure[rowIndex];

                var cellsInRow = row.Elements(WordMl.TableCellName).ToList();

                Assert.AreEqual(expectedRow.Count(), cellsInRow.Count());

                int cellIndex = 0;
                foreach (var cell in cellsInRow)
                {
                    Assert.AreEqual(expectedRow[cellIndex], cell.Value);
                    cellIndex++;
                }

                rowIndex++;
            }

            /*
             * var tagsBetween =
             *  tableTag.TagTable.ElementsAfterSelf().Where(element => element.IsBefore(tableTag.TagContent));
             * Assert.IsFalse(tagsBetween.Any());
             *
             * tagsBetween =
             *  tableTag.TagEndContent.ElementsAfterSelf().Where(element => element.IsBefore(tableTag.TagEndTable));
             * Assert.IsFalse(tagsBetween.Any());*/
            this.ValidateTagsRemoved(root);
        }