Exemplo n.º 1
0
        /// <summary>
        /// Assigns values to all linked fields based on a code table.
        /// </summary>
        /// <param name="sender">The control that contains the link references</param>
        public void FilterList(object sender, System.EventArgs e)
        {
            string TestValue = null;

            if (sender is ListFieldComboBox)
            {
                ListFieldComboBox lvcb = (ListFieldComboBox)sender;

                TestValue = lvcb.SelectedValue.ToString();
            }
            else
            {
                TestValue = ((Control)sender).Text;
            }

            this.DataSource = null;
            Epi.Fields.DDListField field = (Epi.Fields.DDListField)Epi.Windows.Enter.PresentationLogic.ControlFactory.Instance.GetAssociatedField(this);
            string SourceTable           = field.SourceTable;
            string relateField           = null;
            string displayfield          = field.TextColumnName;

            foreach (System.Collections.Generic.KeyValuePair <string, int> kvp in field.pairAssociated)
            {
                relateField = kvp.Key;
                break;
            }

            System.Data.DataTable drv = DBReadExecute.GetDataTable(field.GetProject().FilePath, string.Format("Select * from {0} Where {1} Like '{2}%'", SourceTable, relateField, TestValue));
            this.Items.Clear();
            this.DataSource    = drv;
            this.DisplayMember = displayfield;
            this.ValueMember   = relateField;
            this.RefreshItems();
        }
        private void PopulateTable(Dictionary <string, List <TableColumn> > pTableColumns)
        {
            //DataTable sourceTable = OutputDriver.GetTableData(this.TableName);
            //DataTable sourceTable = OutputDriver.GetTableData(this.TableName);
            foreach (KeyValuePair <string, List <TableColumn> > kvp in pTableColumns)
            {
                StringBuilder      ColumnSQL     = new StringBuilder();
                DataTable          WritableTable = CurrentDataTable.Clone();
                List <TableColumn> TableColumns  = kvp.Value;

                for (int i = WritableTable.Columns.Count - 1; i > -1; i--)
                {
                    DataColumn col     = WritableTable.Columns[i];
                    bool       isFound = false;
                    foreach (TableColumn TC in TableColumns)
                    {
                        if (TC.Name.Equals(col.ColumnName, StringComparison.OrdinalIgnoreCase))
                        {
                            isFound = true;
                            break;
                        }
                    }

                    if (!isFound)
                    {
                        WritableTable.Columns.Remove(col);
                    }
                }

                foreach (DataRow row in CurrentDataTable.Select("", this.Context.SortExpression.ToString()))
                {
                    DataRow newRow = WritableTable.NewRow();
                    foreach (TableColumn column in TableColumns)
                    {
                        newRow[column.Name] = row[column.Name];
                    }
                    WritableTable.Rows.Add(newRow);
                }


                System.Data.Common.DbDataReader DataReader = WritableTable.CreateDataReader();
                DBReadExecute.InsertBulkRows(FilePath, "Select * From [" + kvp.Key + "]", DataReader, SetGadgetStatusHandler);

                this.OutTarget += "<br/>" + FilePath + "\\" + kvp.Key;
            }


            if (CurrentDataTable.Rows.Count > 0)
            {
                this.statusMessage = "Export completed successfully, ";
            }
            else
            {
                this.statusMessage = "Export was not completed successfully, ";
            }
            this.statusMessage += CurrentDataTable.Rows.Count.ToString() + " records written.";
        }
Exemplo n.º 3
0
        private int GetRecordCount(string filePath, string identifier)
        {
            int recordCount = 0;

            if (filePath.ToUpperInvariant().StartsWith("CONFIG:"))
            {
                string[]      datakey          = filePath.Split(':');
                string        ConnectionString = null;
                Configuration config           = Configuration.GetNewInstance();

                for (int i = 0; i < config.RecentDataSources.Count; i++)
                {
                    Epi.DataSets.Config.RecentDataSourceRow row = config.RecentDataSources[i];
                    if (row.Name.ToUpperInvariant() == datakey[1].ToUpperInvariant())
                    {
                        ConnectionString = Configuration.Decrypt(row.ConnectionString);
                        break;
                    }
                }

                filePath = ConnectionString;
            }

            string[]      Identifiers       = identifier.Split('.');
            StringBuilder IdentifierBuilder = new StringBuilder();

            for (int i = 0; i < Identifiers.Length; i++)
            {
                IdentifierBuilder.Append("[");
                IdentifierBuilder.Append(Identifiers[i]);
                IdentifierBuilder.Append("].");
            }

            IdentifierBuilder.Length = IdentifierBuilder.Length - 1;

            if (DBReadExecute.ProjectFileName != "")
            {
                if (Context.CurrentProject.Views.Exists(identifier))
                {
                    recordCount = (int)DBReadExecute.GetScalar(filePath, "SELECT COUNT(*) FROM " + Context.CurrentProject.Views[identifier].TableName);
                }
                else
                {
                    recordCount = (int)DBReadExecute.GetScalar(filePath, "SELECT COUNT(*) FROM " + IdentifierBuilder.ToString());
                }
            }
            else
            {
                recordCount = (int)DBReadExecute.GetScalar(filePath, "SELECT COUNT(*) FROM " + IdentifierBuilder.ToString());
            }

            return(recordCount);
        }
 /// <summary>
 /// WriteToOutTable deletes the table named in the outTableName param
 /// then creates and inserts and new table with the name given.
 /// </summary>
 /// <param name="table">The DataTable that will be copied to the database.</param>
 /// <param name="outTableName">The name of the new table to be persised</param>
 private void WriteToOutTable(DataTable table, string outTableName)
 {
     if (!string.IsNullOrEmpty(outTableName))
     {
         if (this.Context.CurrentRead != null)
         {
             if (DBReadExecute.CheckDatabaseTableExistance(this.Context.CurrentRead.File, outTableName))
             {
                 DBReadExecute.ExecuteSQL(this.Context.CurrentRead.File, "Delete From " + outTableName);
                 DBReadExecute.ExecuteSQL(this.Context.CurrentRead.File, "Drop Table " + outTableName);
             }
             DBReadExecute.ExecuteSQL(this.Context.CurrentRead.File, DBReadExecute.GetCreateFromDataTableSQL(outTableName, table));
             DBReadExecute.InsertData(this.Context.CurrentRead.File, "Select * from " + outTableName, table.CreateDataReader());
         }
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Returns a 2x2 table for the tables command
        /// </summary>
        /// <remarks>The cells are numbered as they are in Epi3</remarks>
        /// <param name="outcome"></param>
        /// <param name="exposure"></param>
        /// <returns>DataTable</returns>
        public DataSet GetDataSet2x2(Rule_Context pContext, string exposure, string outcome)
        {
            DataSet ds = null;

            try
            {
                StringBuilder sb = new StringBuilder("select ");
                sb.Append(exposure).Append(" AS [").Append(ColumnNames.EXPOSURE).Append("], [");
                sb.Append(outcome).Append("] AS [").Append(ColumnNames.OUTCOME);
                sb.Append("], count([").Append(outcome).Append("]) AS [").Append(ColumnNames.COUNT);
                sb.Append("] ");
                sb.Append(GetSqlStatementPartFrom(pContext));

                //if there is no project, there will not be a column Rec Status
                if (PrimaryTable.Columns.Contains(ColumnNames.REC_STATUS))
                {
                    sb.Append(ExcludeMissing(GetSqlStatementPartWhere(),
                                             new string[] { exposure, outcome }));
                }
                //a natively read MDB, and SELECT chosen
                else if (!string.IsNullOrEmpty(selectCriteria))
                {
                    string whereClause = " where " + this.selectCriteria;
                    sb.Append(ExcludeMissing(whereClause, new string[] { exposure, outcome }));
                }
                sb.Append(" group by [").Append(exposure).Append("], [").Append(outcome);
                sb.Append("] order by [").Append(exposure);
                sb.Append("], [").Append(outcome).Append("];");

                DataTable Table2x2 = DBReadExecute.GetDataTable(pContext.CurrentRead.File, sb.ToString());

                //Query query = Db.CreateQuery(sb.ToString());
                //DataTable Table2x2 = Db.Select(query);
                Table2x2.TableName = "Table2x2";
                ds = new DataSet("dsTable2x2");
                ds.Tables.Add(Table2x2);
                //DataTable distinctOutcomes = DistinctColumn(outcome);
                //distinctOutcomes.TableName = "DistinctOutcomes";
                //ds.Tables.Add(distinctOutcomes);
            }
            catch (Exception ex)
            {
                throw new GeneralException(SharedStrings.UNABLE_CREATE_2X2, ex);
            }
            return(ds);
        }
 private void mainForm_OpenViewEvent(object sender, Epi.Windows.Enter.PresentationLogic.OpenViewEventArgs e)
 {
     if (e.View != null)
     {
         if (!e.View.IsRelatedView)
         {
             this.currentView = e.View;
             this.fields      = null;
             db = DBReadExecute.GetDataDriver(e.View.Project.FilePath);
             CreateFromGrid();
             CreateToGrid();
             ToggleEnable(true);
         }
         else
         {
             lvLinkedFrom.Clear();
             lvLinkedTo.Clear();
             ToggleEnable(false);
         }
     }
 }
Exemplo n.º 7
0
        public void UpdateCurrentRecordNumber()
        {
            if (this.mView.CurrentRecordId > 0)
            {
                if (!this.RecordNumberMap.ContainsKey(this.mView.CurrentRecordId))
                {
                    string relatedViewFilter = string.Empty;
                    if (this.mView.IsRelatedView)
                    {
                        relatedViewFilter  = " and ";
                        relatedViewFilter += ColumnNames.FOREIGN_KEY;
                        relatedViewFilter += StringLiterals.EQUAL + "'" + mView.ForeignKeyField.CurrentRecordValueString + "'";
                    }

                    DataTable DT = DBReadExecute.GetDataTable(this.mView.Project.FilePath, "Select Count(*) From [" + this.mView.TableName + "] Where UniqueKey <= " + this.mView.CurrentRecordId.ToString() + relatedViewFilter);
                    if (DT.Rows.Count > 0)
                    {
                        this.RecordNumberMap.Add(this.mView.CurrentRecordId, int.Parse(DT.Rows[0][0].ToString()));
                    }
                }
            }
        }
Exemplo n.º 8
0
        public bool OutTable(System.Data.DataTable pDataTable)
        {
            bool result = false;

            try
            {
                if (DBReadExecute.CheckDatabaseTableExistance(DBReadExecute.ParseConnectionString(this.mContext.CurrentRead.File), pDataTable.TableName))
                {
                    DBReadExecute.ExecuteSQL(this.mContext.CurrentRead.File, "Delete From [" + pDataTable.TableName + "]");
                    DBReadExecute.ExecuteSQL(this.mContext.CurrentRead.File, "Drop Table [" + pDataTable.TableName + "]");
                }
                DBReadExecute.ExecuteSQL(this.mContext.CurrentRead.File, DBReadExecute.GetCreateFromDataTableSQL(pDataTable.TableName, pDataTable));

                DBReadExecute.InsertData(this.mContext.CurrentRead.File, "Select * from [" + pDataTable.TableName + "]", pDataTable.CreateDataReader());

                result = true;
            }
            catch (Exception e)
            {
                // do nothing for now
            }
            return(result);
        }
Exemplo n.º 9
0
        private DataTable GetDataTable(string filePath, string identifier)
        {
            System.Data.DataTable table;

            if (filePath.ToUpperInvariant().StartsWith("CONFIG:"))
            {
                string[]      datakey          = filePath.Split(':');
                string        connectionString = null;
                Configuration config           = Configuration.GetNewInstance();

                for (int i = 0; i < config.RecentDataSources.Count; i++)
                {
                    Epi.DataSets.Config.RecentDataSourceRow row = config.RecentDataSources[i];
                    if (row.Name.ToUpperInvariant() == datakey[1].ToUpperInvariant())
                    {
                        connectionString = Configuration.Decrypt(row.ConnectionString);
                        break;
                    }
                }

                filePath = connectionString;
            }

            string[]      Identifiers       = identifier.Split('.');
            StringBuilder IdentifierBuilder = new StringBuilder();

            for (int i = 0; i < Identifiers.Length; i++)
            {
                IdentifierBuilder.Append("[");
                IdentifierBuilder.Append(Identifiers[i]);
                IdentifierBuilder.Append("].");
            }

            IdentifierBuilder.Length = IdentifierBuilder.Length - 1;

            if (DBReadExecute.ProjectFileName != "")
            {
                if (Context.CurrentProject.Views.Exists(identifier))
                {
                    string selectStatement = "Select * From [" + identifier + "]";
                    table = DBReadExecute.GetDataTable(Context.CurrentRead.File, selectStatement);

                    foreach (Page page in Context.CurrentProject.Views[identifier].Pages)
                    {
                        DataTable pageTable = DBReadExecute.GetDataTable(Context.CurrentRead.File, "Select  * From [" + page.TableName + "]");
                        table = JoinPagesTables(table, pageTable);
                    }
                }
                else
                {
                    if (filePath.EndsWith(".prj"))
                    {
                        Epi.Data.IDbDriver driver = DBReadExecute.GetDataDriver(filePath);
                        table = driver.GetTableData(identifier);
                        DataTable pageTables = DBReadExecute.GetDataTable(driver, "Select DISTINCT PageId FROM metaFields Where DataTableName = '" + identifier + "' AND PageId <> null");

                        foreach (DataRow row in pageTables.Rows)
                        {
                            DataTable pageTable = driver.GetTableData(identifier + row["PageId"]);
                            table = JoinPagesTables(table, pageTable);
                        }
                    }
                    else
                    {
                        table = DBReadExecute.GetDataTable(filePath, "Select * FROM " + IdentifierBuilder.ToString());
                    }
                }
            }
            else
            {
                if (filePath.EndsWith(".prj"))
                {
                    Epi.Data.IDbDriver driver = DBReadExecute.GetDataDriver(filePath);
                    table = driver.GetTableData(identifier);
                    DataTable pageTables = DBReadExecute.GetDataTable(driver, "Select DISTINCT PageId FROM metaFields Where DataTableName = '" + identifier + "' AND PageId <> null");

                    foreach (DataRow row in pageTables.Rows)
                    {
                        DataTable pageTable = driver.GetTableData(identifier + row["PageId"]);
                        table = JoinPagesTables(table, pageTable);
                    }
                }
                else
                {
                    table = DBReadExecute.GetDataTable(filePath, "Select * from " + IdentifierBuilder.ToString());
                }
            }

            return(table);
        }
Exemplo n.º 10
0
        private void BuildKeyDialog_Load(object sender, EventArgs e)
        {
            if (SelectedDataSource != null)
            {
                if (SelectedDataSource is IDbDriver)
                {
                    IDbDriver db = SelectedDataSource as IDbDriver;
                    //--EI-114
                    // relatedFields = db.GetTableColumnNames(RelatedTable);
                    if (RelatedTable.Contains(StringLiterals.SPACE))
                    {
                        string    pstr      = "Select TOP 2 * from [" + RelatedTable + "]";
                        DataTable relfields = DBReadExecute.GetDataTable(db, pstr);
                        foreach (DataColumn dc in relfields.Columns)
                        {
                            relatedFields.Add(dc.ColumnName);
                        }
                    }
                    else
                    {
                        relatedFields = db.GetTableColumnNames(RelatedTable);
                    }
                    //---
                }
                else if (SelectedDataSource is Project)
                {
                    Project project = SelectedDataSource as Project;

                    if (project.Views.Exists(relatedTable))
                    {
                        foreach (Epi.Fields.IField field in project.Views[RelatedTable].Fields)
                        {
                            if (!(field is Epi.Fields.LabelField) & !(field is Epi.Fields.CommandButtonField) & !(field is Epi.Fields.PhoneNumberField)//EI-705
                                & !(field is Epi.Fields.MultilineTextField) & !(field is Epi.Fields.GroupField) & !(field is Epi.Fields.CheckBoxField)
                                & !(field is Epi.Fields.ImageField) & !(field is Epi.Fields.OptionField) & !(field is Epi.Fields.GridField)
                                & !(field is Epi.Fields.MirrorField))
                            {
                                relatedFields.Add(field.Name);
                            }
                        }
                    }
                    else
                    {
                        relatedFields = project.GetTableColumnNames(RelatedTable);
                    }
                }
                if (this.EpiInterpreter.Context.DataSet != null)
                {
                    View CurrentView = null;
                    bool currentReadIdentifierIsView = false;

                    if (this.EpiInterpreter.Context.CurrentProject != null)
                    {
                        currentReadIdentifierIsView = this.EpiInterpreter.Context.CurrentProject.IsView(this.EpiInterpreter.Context.CurrentRead.Identifier);
                    }

                    if (currentReadIdentifierIsView)
                    {
                        CurrentView = this.EpiInterpreter.Context.CurrentProject.GetViewByName(this.EpiInterpreter.Context.CurrentRead.Identifier); //EI-705
                        foreach (DataColumn column in this.EpiInterpreter.Context.DataSet.Tables["Output"].Columns)
                        {
                            if ((CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.LabelField)) & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.CommandButtonField)) & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.PhoneNumberField))
                                & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.MultilineTextField)) & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.GroupField)) & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.CheckBoxField))
                                & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.ImageField)) & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.OptionField)) & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.GridField))
                                & (CurrentView.Fields.Exists(column.ColumnName) && !(CurrentView.Fields[column.ColumnName] is Epi.Fields.MirrorField)))
                            {
                                currentFields.Add(column.ColumnName);
                            }
                        }
                    }
                    else
                    {
                        foreach (DataColumn column in this.EpiInterpreter.Context.DataSet.Tables["Output"].Columns)
                        {
                            currentFields.Add(column.ColumnName);
                        }
                    }
                }
                currentFields.Sort();
            }
            //rdbCurrentTable.Checked = true;

            relatedFields.Sort();
            currentFields.Sort();

            //cmbAvailableVariables2.DataSource = relatedFields;
            lbxRelatedTableFields.DataSource = relatedFields;
            //cmbAvailableVariables.DataSource = currentFields;
            lbxCurrentTableFields.DataSource = currentFields;

            lbxCurrentTableFields.SelectedIndex = -1;
            lbxRelatedTableFields.SelectedIndex = -1;

            if (CallingDialog == "RELATE")
            {
                lblBuildKeyInstructions.Text = SharedStrings.BUILDKEY_RELATE_INSTRUCTIONS;
            }
            else
            {
                lblBuildKeyInstructions.Text = SharedStrings.BUILDKEY_MERGE_INSTRUCTIONS;
            }

            this.LoadIsFinished = true;
        }
        /// <summary>
        /// performs execution of the WRITE command
        /// </summary>
        /// <returns>object</returns>
        public override object Execute()
        {
            object result = null;

            Context.AnalysisCheckCodeInterface.ShowWaitDialog("Exporting data...");

            //string[] tmp = this.OutTarget.ToString().Split(':');
            //string FilePath = null;
            //if (tmp.Length <= 2)
            //{
            //    FilePath = tmp[0];
            //}
            //else
            //{
            //    FilePath = tmp[0] + ":" + tmp[1];
            //}
            //FilePath = FilePath.Trim().Trim(new char[] { '\'' });
            //string TableName;
            //if (tmp.Length > 1)
            //{
            //    TableName = tmp[tmp.Length - 1].Replace("]", "").Replace("[", "").Trim().Trim('\'');
            //}
            //else
            //{
            //    TableName = this.OutTarget;
            //    FilePath = this.Context.CurrentProject.CollectedDataConnectionString;
            //}

            CurrentDataTable = this.Context.DataSet.Tables["output"].Clone();

            foreach (DataRow row in this.Context.GetOutput(new List <string>()))
            {
                CurrentDataTable.ImportRow(row);
            }

            if (this.IdentifierList[0] == "*")
            {
                for (int i = 0; i < CurrentDataTable.Columns.Count; i++)
                {
                    IVariable var = (IVariable)this.Context.GetVariable(CurrentDataTable.Columns[i].ColumnName);

                    if (var != null)
                    {
                        if (var.VarType != VariableType.Global && var.VarType != VariableType.Permanent)
                        {
                            TempVariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant());
                        }
                    }
                    else
                    {
                        TempVariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant());
                    }
                }
            }
            else
            {
                for (int i = 0; i < this.IdentifierList.Length; i++)
                {
                    TempVariableList.Add(this.IdentifierList[i].ToUpperInvariant());
                }
            }

            if (isExceptionList)
            {
                for (int i = CurrentDataTable.Columns.Count - 1; i > -1; i--)
                {
                    if (TempVariableList.Contains(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant()))
                    {
                        //CurrentDataTable.Columns.Remove(CurrentDataTable.Columns[i]);
                    }
                    else
                    {
                        if (this.IdentifierList[0] == "*")
                        {
                            IVariable var = (IVariable)this.Context.GetVariable(CurrentDataTable.Columns[i].ColumnName);

                            if (var != null)
                            {
                                if (var != null && var.VarType != VariableType.Global && var.VarType != VariableType.Permanent)
                                {
                                    VariableList.Add(var.Name.ToUpperInvariant());
                                }
                            }
                        }
                        else
                        {
                            VariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant());
                        }
                    }
                }
            }
            else // is NOT an isExceptionList
            {
                for (int i = 0; i < CurrentDataTable.Columns.Count; i++)
                {
                    if (TempVariableList.Contains(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant()))
                    {
                        VariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpperInvariant());
                    }
                    else
                    {
                        //CurrentDataTable.Columns.Remove(CurrentDataTable.Columns[i]);
                    }
                }
            }

            try
            {
                Dictionary <string, List <TableColumn> > WideTableColumns = null;
                DataSets.Config.DataDriverDataTable      dataDrivers      = Configuration.GetNewInstance().DataDrivers;
                IDbDriverFactory dbFactory = null;
                foreach (DataSets.Config.DataDriverRow dataDriver in dataDrivers)
                {
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(dataDriver.Type);

                    if (dbFactory.CanClaimConnectionString(FilePath))
                    {
                        break;
                    }
                }

                OutputDriver = DBReadExecute.GetDataDriver(FilePath, this.isConnectionString);

                if (OutputDriver.GetType().Name.Equals("CsvFile", StringComparison.OrdinalIgnoreCase) || this.FileDataFormat.Equals("TEXT", StringComparison.OrdinalIgnoreCase))
                {
                    if (!this.TableName.EndsWith(".txt") && !this.TableName.EndsWith(".csv") && !this.TableName.EndsWith("#csv") && !this.TableName.EndsWith("#txt"))
                    {
                        this.TableName = this.TableName + ".csv";
                    }
                }
                this.OutTarget = this.FilePath + ":" + this.TableName;
                this.curFile   = OutputDriver.DataSource;

                if (!OutputDriver.CheckDatabaseExistance(FilePath, TableName, this.isConnectionString))
                {
                    DbDriverInfo collectDbInfo = new DbDriverInfo();
                    Type         SqlDriverType = Type.GetType("Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer");
                    if (DBReadExecute.DataSource.GetType().AssemblyQualifiedName == SqlDriverType.AssemblyQualifiedName)
                    {
                        collectDbInfo.DBCnnStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
                    }
                    else
                    {
                        collectDbInfo.DBCnnStringBuilder = new System.Data.OleDb.OleDbConnectionStringBuilder();
                    }
                    collectDbInfo.DBCnnStringBuilder.ConnectionString = dbFactory.ConvertFileStringToConnectionString(FilePath);
                    //collectDbInfo.DBCnnStringBuilder = dbFactory.RequestDefaultConnection(dbFactory.FilePath.Trim());
                    OutputDriver         = dbFactory.CreateDatabaseObject(collectDbInfo.DBCnnStringBuilder);
                    collectDbInfo.DBName = OutputDriver.DbName;
                    dbFactory.CreatePhysicalDatabase(collectDbInfo);
                }


                bool?deleteSuccessful = null;
                if (this.WriteMode.Equals("REPLACE", StringComparison.OrdinalIgnoreCase) && DBReadExecute.CheckDatabaseTableExistance(FilePath, TableName, this.isConnectionString))
                {
                    deleteSuccessful = OutputDriver.DeleteTable(TableName);
                }

                List <TableColumn> TableColumns = new List <TableColumn>();

                if (!DBReadExecute.CheckDatabaseTableExistance(FilePath, TableName, this.isConnectionString))
                {
                    foreach (DataColumn column in CurrentDataTable.Columns)
                    {
                        if (VariableList.Contains(column.ColumnName.ToUpperInvariant()))
                        {
                            bool isPermanentVariable = false;

                            IVariable candidate = Context.MemoryRegion.GetVariable(column.ColumnName);

                            if (candidate != null && candidate.IsVarType(VariableType.Permanent))
                            {
                                isPermanentVariable = true;
                            }

                            if (isPermanentVariable == false)
                            {
                                TableColumn newTableColumn;

                                if (column.DataType.ToString() == "System.String")
                                {
                                    if (column.MaxLength <= 0)
                                    {
                                        newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull);
                                    }
                                    else
                                    {
                                        newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                                    }
                                }
                                else if (column.DataType.ToString() == "System.Guid")
                                {
                                    if (column.MaxLength <= 0)
                                    {
                                        newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull);
                                    }
                                    else
                                    {
                                        newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                                    }
                                }
                                else
                                {
                                    newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull);
                                }

                                newTableColumn.AllowNull  = column.AllowDBNull;
                                newTableColumn.IsIdentity = column.Unique;
                                TableColumns.Add(newTableColumn);
                            }
                        }
                    }

                    if
                    (
                        (
                            (!(OutputDriver.GetType().Name.Equals("AccessDatabase", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Access2007Database", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) &&
                             VariableList.Count <= Max_Number_Columns) ||
                            OutputDriver.GetType().Name.Equals("SqlDatabase", StringComparison.OrdinalIgnoreCase)
                        )
                    )
                    {
                        OutputDriver.CreateTable(TableName, TableColumns);
                    }
                    else
                    {
                        if (OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase))
                        {
                            WideTableColumns = this.CreateExcelWideTable(TableColumns);
                        }
                        else if (!OutputDriver.GetType().Name.Equals("CsvFile", StringComparison.OrdinalIgnoreCase))
                        {
                            WideTableColumns = this.CreateAccessWideTable(TableColumns);
                        }
                    }
                }
                else // check that column name exists in destinationl
                {
                    foreach (string columnName in VariableList)
                    {
                        bool isFound = false;
                        foreach (DataColumn column in CurrentDataTable.Columns)
                        {
                            if (column.ColumnName.ToUpperInvariant() == columnName.ToUpperInvariant())
                            {
                                isFound = true;
                                break;
                            }
                        }

                        if (!isFound)
                        {
                            TableColumn newTableColumn;
                            DataColumn  column = CurrentDataTable.Columns[columnName];
                            if (column.DataType.ToString() == "System.String")
                            {
                                newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                            }
                            else if (column.DataType.ToString() == "System.Guid")
                            {
                                newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                            }
                            else
                            {
                                newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull);
                            }
                            newTableColumn.AllowNull  = column.AllowDBNull;
                            newTableColumn.IsIdentity = column.Unique;

                            OutputDriver.AddColumn(TableName, newTableColumn);
                        }
                    }

                    if ((OutputDriver.GetType().Name.Equals("AccessDatabase", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Access2007Database", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) && VariableList.Count > Max_Number_Columns)
                    {
                        foreach (DataColumn column in CurrentDataTable.Columns)
                        {
                            if (VariableList.Contains(column.ColumnName.ToUpperInvariant()))
                            {
                                bool isPermanentVariable = false;

                                IVariable candidate = Context.MemoryRegion.GetVariable(column.ColumnName);

                                if (candidate != null && candidate.IsVarType(VariableType.Permanent))
                                {
                                    isPermanentVariable = true;
                                }

                                if (isPermanentVariable == false)
                                {
                                    TableColumn newTableColumn;

                                    if (column.DataType.ToString() == "System.String")
                                    {
                                        if (column.MaxLength <= 0)
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull);
                                        }
                                        else
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                                        }
                                    }
                                    else if (column.DataType.ToString() == "System.Guid")
                                    {
                                        if (column.MaxLength <= 0)
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull);
                                        }
                                        else
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                                        }
                                    }
                                    else
                                    {
                                        newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull);
                                    }

                                    newTableColumn.AllowNull  = column.AllowDBNull;
                                    newTableColumn.IsIdentity = column.Unique;
                                    TableColumns.Add(newTableColumn);
                                }
                            }
                        }

                        if (OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase))
                        {
                            WideTableColumns = this.CreateExcelWideTable(TableColumns);
                        }
                        else
                        {
                            WideTableColumns = this.CreateAccessWideTable(TableColumns, false);
                        }
                    }
                }


                ////APPEND| REPLACE	| !Null
                //if (this.WriteMode.Equals("REPLACE", StringComparison.OrdinalIgnoreCase))
                //{
                //    WriteMethod = this.ReplaceWrite;
                //}
                //else
                //{
                //    WriteMethod = this.AppendWrite;
                //}


                if (OutputDriver.GetType().Name.Equals("CsvFile", StringComparison.OrdinalIgnoreCase) || this.FileDataFormat.Equals("TEXT", StringComparison.OrdinalIgnoreCase))
                {
                    if (TableColumns.Count == 0)
                    {
                        foreach (DataColumn column in CurrentDataTable.Columns)
                        {
                            if (VariableList.Contains(column.ColumnName.ToUpperInvariant()))
                            {
                                bool isPermanentVariable = false;

                                IVariable candidate = Context.MemoryRegion.GetVariable(column.ColumnName);

                                if (candidate != null && candidate.IsVarType(VariableType.Permanent))
                                {
                                    isPermanentVariable = true;
                                }

                                if (isPermanentVariable == false)
                                {
                                    TableColumn newTableColumn;

                                    if (column.DataType.ToString() == "System.String")
                                    {
                                        if (column.MaxLength <= 0)
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull);
                                        }
                                        else
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                                        }
                                    }
                                    else if (column.DataType.ToString() == "System.Guid")
                                    {
                                        if (column.MaxLength <= 0)
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), int.MaxValue, column.AllowDBNull);
                                        }
                                        else
                                        {
                                            newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.MaxLength, column.AllowDBNull);
                                        }
                                    }
                                    else
                                    {
                                        newTableColumn = new TableColumn(column.ColumnName.ToString(), ConvertToGenericType(column.DataType), column.AllowDBNull);
                                    }

                                    newTableColumn.AllowNull  = column.AllowDBNull;
                                    newTableColumn.IsIdentity = column.Unique;
                                    TableColumns.Add(newTableColumn);
                                }
                            }
                        }
                    }
                    this.WriteCSVFile(TableColumns);
                }
                else if ((OutputDriver.GetType().Name.Equals("AccessDatabase", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Access2007Database", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("ExcelWorkbook", StringComparison.OrdinalIgnoreCase) || OutputDriver.GetType().Name.Equals("Excel2007Workbook", StringComparison.OrdinalIgnoreCase)) && VariableList.Count > Max_Number_Columns)
                {
                    this.PopulateTable(WideTableColumns);
                }
                else
                {
                    DataTable sourceTable = OutputDriver.GetTableData(TableName);

                    OutputDriver.IsBulkOperation = true; StringBuilder sqlquery = new StringBuilder();

                    int count = 0;

                    sqlquery.Append("create table [" + TableName + "] ( ");

                    foreach (string column in VariableList)
                    {
                        string columnName = String.Empty;
                        if (!column.Contains(".") && !OutputDriver.ColumnExists(TableName, column))
                        {
                            columnName = column;
                            if (count > 0)
                            {
                                sqlquery.Append(", ");
                            }
                            sqlquery.Append(" [" + columnName + "] " + DBReadExecute.SQLGetType(CurrentDataTable.Columns[column]));
                            count++;
                        }
                    }

                    sqlquery.Append(" )");

                    if (count > 0)
                    {
                        Query qr = OutputDriver.CreateQuery(sqlquery.ToString());
                        OutputDriver.ExecuteNonQuery(qr);
                    }

                    OutputDriver.IsBulkOperation = false;

                    //Insert data into table

                    ////Open connection
                    ////Setup Schema
                    ////Loop through records
                    ////Close connection
                    DataTable WritableTable = CurrentDataTable.Clone();
                    for (int i = WritableTable.Columns.Count - 1; i > -1; i--)
                    {
                        if (WritableTable.Columns[i].DataType == typeof(Guid))
                        {
                            WritableTable.Columns[i].DataType = typeof(String);
                        }
                    }
                    for (int i = WritableTable.Columns.Count - 1; i > -1; i--)
                    {
                        DataColumn col = WritableTable.Columns[i];

                        if (!VariableList.Contains(col.ColumnName.ToUpperInvariant()))
                        {
                            WritableTable.Columns.Remove(col);
                        }
                    }

                    foreach (DataRow row in CurrentDataTable.Select("", this.Context.SortExpression.ToString()))
                    {
                        DataRow newRow = WritableTable.NewRow();
                        foreach (string column in VariableList)
                        {
                            newRow[column] = row[column];
                        }

                        WritableTable.Rows.Add(newRow);
                    }

                    System.Data.Common.DbDataReader DataReader = WritableTable.CreateDataReader();
                    DBReadExecute.InsertBulkRows(FilePath, "Select * From [" + TableName + "]", DataReader, SetGadgetStatusHandler);

                    if (CurrentDataTable.Rows.Count > 0)
                    {
                        this.statusMessage = "Export completed successfully, ";
                    }
                    else
                    {
                        this.statusMessage = "Export was not completed successfully, ";
                    }
                    this.statusMessage += CurrentDataTable.Rows.Count.ToString() + " records written.";

                    DataReader.Close();
                }
            }
            catch (Exception ex)
            {
                this.statusMessage = "Problems exporting records: " + ex.ToString();
                System.Console.Write(ex);
            }
            finally
            {
                Context.AnalysisCheckCodeInterface.HideWaitDialog();
            }

            /*
             *
             *
             *
             *
             * Comments
             *  Records deleted in Enter or selected in Analysis are handled as in other Analysis commands.
             *  Defined variables may be written, allowing the creation of a new Epi Info file that makes the changes permanent.
             *  Global and permanent variables will not be written unless explicitly specified.
             *  To write only selected variables, the word EXCEPT may be inserted to indicate all variables except those following EXCEPT.
             *  If the output file specified does not exist, the WRITE command will attempt to create it.
             *  Either APPEND or REPLACE must be specified to indicate that an existing file/table by the
             *  same name will be erased or records will be appended to the existing file/table.
             *  If some, but not all, of the fields being written match those in an existing file during an APPEND,
             *  the unmatched fields are added to the output table.
             *  For Epi 6 REC or Access/EpiInfo table outputs, if there are no records,
             *  the WRITE command creates a table/file with variable information but no data.
             *
             *  WRITE <METHOD> {<output type>} {<project>:}table {[<variable(s)>]}
             *  WRITE <METHOD> {<output type>} {<project>:}table * EXCEPT {[<variable(s)>]}
             *
             *  The <METHOD> represents either REPLACE or APPEND
             *  The <project> represents the path and filename of the output.
             *  The <variable(s)> represents one or more variable names.
             *  The <output type> represents the following allowable outputs:
             *
             *  Database Type Specifier Element
             *
             *  Jet "Access 97" "Access 2000"
             *  "Epi 2000"  <path:<table>
             *  dBase III  "dBase III"  <path>
             *  dBase IV "dBase IV"  <path>
             *  dBase 5.0  "dBase 5.0"  <path>
             *  Paradox 3.x  "Paradox 3.x"  <path>
             *  Paradox 4.x "Paradox 4.x" <path>
             *  FoxPro 2.0 "FoxPro 2.0" <path>
             *  FoxPro 2.5 "FoxPro 2.5" <path>
             *  FoxPro 2.6 "FoxPro 2.6" <path>
             *  Excel 3.0 "Excel 3.0" <path>
             *  Excel 4.0 "Excel 4.0" <path>
             *  Epi Info 6 "Epi6" <path>
             *  Text (Delimited) "Text" <path>
             *
             */



            args.Add("COMMANDNAME", CommandNames.WRITE);
            args.Add("WRITEMODE", this.WriteMode);
            args.Add("OUTTARGET", this.OutTarget);
            args.Add("STATUS", this.statusMessage);
            //args.Add("PROGRESST", this.progress.ToString());
            //args.Add("ROWCOUNT", CurrentDataTable.Select("", this.Context.SortExpression.ToString()).Length.ToString());
            this.Context.AnalysisCheckCodeInterface.Display(args);


            return(result);
        }
Exemplo n.º 12
0
        public void Render(Epi.View view)
        {
            try
            {
                if (!view.IsRelatedView)
                {
                    EpiDashboard.DashboardHelper helper = new EpiDashboard.DashboardHelper(view, DBReadExecute.GetDataDriver(view.Project.FilePath));
                    dashboard = new EpiDashboard.DashboardControl(helper);

                    this.WindowState = FormWindowState.Maximized;

                    helper.SetDashboardControl(dashboard);
                    dashboard.RecordCountChanged += new EpiDashboard.RecordCountChangedHandler(dashboard_RecordCountChanged);
                    host.Child = dashboard;
                    dashboard.UpdateRecordCount();
                    dashboard.ReCacheDataSource();
                }
            }
            catch (Exception ex)
            {
                //temporarily catch all
            }
        }
Exemplo n.º 13
0
 private IDbDriver SetupSourceProject()
 {
     sourceProjectDataDriver = DBReadExecute.GetDataDriver(sourceProject.FilePath);
     return(sourceProjectDataDriver);
 }
Exemplo n.º 14
0
        EpiDashboard.DashboardHelper dashboard_DashboardHelperRequested()
        {
            Epi.Windows.Dialogs.BaseReadDialog dlg = new Dialogs.BaseReadDialog(this);

            if (dashboardHelper != null && dashboardHelper.Database != null && !dashboardHelper.IsUsingEpiProject)
            {
                dlg = new Dialogs.BaseReadDialog(this, dashboardHelper.Database);
                if (dashboardHelper.CustomQuery != null && !string.IsNullOrEmpty(dashboardHelper.CustomQuery.Trim()))
                {
                    dlg.SQLQuery = dashboardHelper.CustomQuery;
                }
            }
            else if (dashboardHelper != null && dashboardHelper.Database != null && dashboardHelper.IsUsingEpiProject)
            {
                dlg = new Dialogs.BaseReadDialog(this, dashboardHelper.View.Project);
            }

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (dlg.SelectedDataSource is Project)
                {
                    Project project = (Project)dlg.SelectedDataSource;

                    if (dlg.IsFormSelected)
                    {
                        View view = project.GetViewByName(dlg.SelectedDataMember);
                        if (!File.Exists(project.FilePath))
                        {
                            MsgBox.ShowInformation(string.Format(SharedStrings.DASHBOARD_ERROR_PROJECT_NOT_FOUND, project.FilePath));
                            return(null);
                        }
                        IDbDriver dbDriver = DBReadExecute.GetDataDriver(project.FilePath);
                        if (!dbDriver.TableExists(view.TableName))
                        {
                            MsgBox.ShowInformation(string.Format(SharedStrings.DATA_TABLE_NOT_FOUND, view.Name));
                            return(null);
                        }
                        else
                        {
                            dashboardHelper = new EpiDashboard.DashboardHelper(view, dbDriver);
                        }
                    }
                    else
                    {
                        // Note: This pathway breaks when you try and re-set the data source, however, the UI that allows this code to be
                        //    hit has been temporarily disabled.
                        IDbDriver dbDriver = project.CollectedData.GetDatabase();
                        dashboardHelper = new EpiDashboard.DashboardHelper(dlg.SelectedDataMember, dbDriver);
                    }
                }
                else
                {
                    IDbDriver dbDriver = (IDbDriver)dlg.SelectedDataSource;
                    if (string.IsNullOrEmpty(dlg.SQLQuery))
                    {
                        dashboardHelper = new EpiDashboard.DashboardHelper(dlg.SelectedDataMember, dbDriver);
                    }
                    else
                    {
                        dashboardHelper = new EpiDashboard.DashboardHelper(dlg.SelectedDataMember, dlg.SQLQuery, dbDriver);
                    }
                }

                return(dashboardHelper);
            }
            return(null);
        }
Exemplo n.º 15
0
        EpiDashboard.RelatedConnection dashboard_RelatedDataRequested()
        {
            if (this.dashboard.DashboardHelper == null)
            {
                Epi.Windows.MsgBox.ShowInformation(SharedStrings.DASHBOARD_CANNOT_RELATE_NO_DATA_SOURCE);
                return(null);
            }

            // May arrive here by opening a canvas file without going through normal request routine.
            this.dashboardHelper = this.dashboard.DashboardHelper;

            Epi.Windows.Dialogs.ReadRelatedDialog dlg = new Dialogs.ReadRelatedDialog(this.dashboard.DashboardHelper.TableColumnNames);

            if (dashboard.DashboardHelper.IsUsingEpiProject)
            {
                Dictionary <string, string> tableColumnNamesFiltered = new Dictionary <string, string>();

                foreach (KeyValuePair <string, string> kvp in this.dashboardHelper.TableColumnNames)
                {
                    if (kvp.Value.ToLowerInvariant() != "epi.fields.groupfield")
                    {
                        tableColumnNamesFiltered.Add(kvp.Key, kvp.Value);
                    }
                }

                dlg = new Dialogs.ReadRelatedDialog(this.dashboard.DashboardHelper.View.Project, tableColumnNamesFiltered);
            }
            EpiDashboard.RelatedConnection relatedConnection = null;

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (dlg.SelectedDataSource is Project && dlg.SelectedItemType == Dialogs.SelectedItemType.Form)
                {
                    Project   project  = (Project)dlg.SelectedDataSource;
                    View      view     = project.GetViewByName(dlg.SelectedDataMember);
                    IDbDriver dbDriver = DBReadExecute.GetDataDriver(project.FilePath);
                    relatedConnection = new EpiDashboard.RelatedConnection(view, dbDriver, dlg.ParentKeyField, dlg.ChildKeyField, dlg.UseUnmatched, false);

                    if (dashboardHelper.IsUsingEpiProject && dashboardHelper.View.Project.FilePath == project.FilePath)
                    {
                        relatedConnection.SameDataSource = true;
                    }
                }
                else if (dlg.SelectedDataSource is Project && dlg.SelectedItemType == Dialogs.SelectedItemType.Table)
                {
                    Project   project  = (Project)dlg.SelectedDataSource;
                    IDbDriver dbDriver = project.CollectedData.GetDbDriver();
                    relatedConnection = new EpiDashboard.RelatedConnection(dlg.SelectedDataMember, dbDriver, dlg.ParentKeyField, dlg.ChildKeyField, dlg.UseUnmatched, false);

                    if (dashboardHelper.IsUsingEpiProject && dashboardHelper.View.Project.FilePath == project.FilePath)
                    {
                        relatedConnection.SameDataSource = true;
                    }
                }
                else
                {
                    IDbDriver dbDriver = (IDbDriver)dlg.SelectedDataSource;
                    relatedConnection = new EpiDashboard.RelatedConnection(dlg.SelectedDataMember, dbDriver, dlg.ParentKeyField, dlg.ChildKeyField, dlg.UseUnmatched, false);
                }

                dashboard.ReCacheDataSource(false);

                return(relatedConnection);
            }
            return(null);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Returns true if the given database is a valid Epi Info 7 project.
        /// </summary>
        /// <param name="connectionInfo">The connection information to the database.</param>
        /// <param name="isConnectionString">Whether the connection info is a connection string</param>
        /// <returns>bool</returns>
        public static bool IsDatabaseEpiProject(string connectionInfo, bool isConnectionString)
        {
            //if (fileName.ToLowerInvariant().EndsWith(".mdb"))
            //{
            IDbDriver db        = DBReadExecute.GetDataDriver(connectionInfo, isConnectionString);
            bool      isProject = true;

            List <string> metaTableNames = new List <string>();

            metaTableNames.Add("metaBackgrounds");
            metaTableNames.Add("metaDataTypes");
            metaTableNames.Add("metaDbInfo");
            metaTableNames.Add("metaFields");
            metaTableNames.Add("metaFieldTypes");
            metaTableNames.Add("metaImages");
            metaTableNames.Add("metaLinks");
            metaTableNames.Add("metaPages");
            metaTableNames.Add("metaViews");

            foreach (string tableName in metaTableNames)
            {
                if (!db.TableExists(tableName))
                {
                    isProject = false;
                }
            }

            List <string> metaViewsColumnNames = db.GetTableColumnNames("metaViews");

            if (
                !metaViewsColumnNames.Contains("ViewId") ||
                !metaViewsColumnNames.Contains("Name") ||
                !metaViewsColumnNames.Contains("IsRelatedView") ||
                !metaViewsColumnNames.Contains("CheckCode") ||
                !metaViewsColumnNames.Contains("Width") ||
                !metaViewsColumnNames.Contains("Height") ||
                !metaViewsColumnNames.Contains("Orientation")
                )
            {
                isProject = false;
            }

            List <string> metaPagesColumnNames = db.GetTableColumnNames("metaPages");

            if (
                !metaPagesColumnNames.Contains("PageId") ||
                !metaPagesColumnNames.Contains("Name") ||
                !metaPagesColumnNames.Contains("Position") ||
                !metaPagesColumnNames.Contains("BackgroundId") ||
                !metaPagesColumnNames.Contains("ViewId")
                )
            {
                isProject = false;
            }

            List <string> metaFieldsColumnNames = db.GetTableColumnNames("metaFields");

            if (
                !metaFieldsColumnNames.Contains("FieldId") ||
                !metaFieldsColumnNames.Contains("UniqueId") ||
                !metaFieldsColumnNames.Contains("Name") ||
                !metaFieldsColumnNames.Contains("PromptText") ||
                !metaFieldsColumnNames.Contains("ControlFontFamily") ||
                !metaFieldsColumnNames.Contains("ControlFontSize") ||
                !metaFieldsColumnNames.Contains("ControlFontStyle") ||
                !metaFieldsColumnNames.Contains("ControlTopPositionPercentage") ||
                !metaFieldsColumnNames.Contains("ControlLeftPositionPercentage") ||
                !metaFieldsColumnNames.Contains("ControlHeightPercentage") ||
                !metaFieldsColumnNames.Contains("ControlWidthPercentage") ||
                !metaFieldsColumnNames.Contains("TabIndex") ||
                !metaFieldsColumnNames.Contains("HasTabStop") ||
                !metaFieldsColumnNames.Contains("Lower") ||
                !metaFieldsColumnNames.Contains("Upper") ||
                !metaFieldsColumnNames.Contains("Pattern") ||
                !metaFieldsColumnNames.Contains("PageId") ||
                !metaFieldsColumnNames.Contains("ViewId")
                )
            {
                isProject = false;
            }
            //}

            db.Dispose();
            db = null;

            return(isProject);
        }
Exemplo n.º 17
0
        /// <summary>
        /// performs execution of the READ command
        /// </summary>
        /// <returns>object</returns>
        public override object Execute()
        {
            object    result = null;
            DataTable outputTable;
            int       recordCount = 0;

            Context.isReadMode        = true;
            Context.GroupVariableList = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);

            if (File.ToUpperInvariant().StartsWith("CONFIG:"))
            {
                string[]      datakey          = File.Split(':');
                string        connectionString = null;
                Configuration config           = Configuration.GetNewInstance();

                for (int i = 0; i < config.RecentDataSources.Count; i++)
                {
                    Epi.DataSets.Config.RecentDataSourceRow row = config.RecentDataSources[i];

                    if (row.Name.ToUpperInvariant() == datakey[1].ToUpperInvariant())
                    {
                        connectionString = Configuration.Decrypt(row.ConnectionString);
                        break;
                    }
                }

                File = connectionString;
            }

            if (_isSimpleRead)
            {
                if (Context.CurrentProject == null)
                {
                    if (Context.CurrentRead == null)
                    {
                        throw new GeneralException(SharedStrings.NO_CURRENT_PROJECT);
                    }
                    else
                    {
                        Context.AddConnection("_DB", Context.CurrentRead.File);
                        outputTable         = DBReadExecute.GetDataTable(Context.CurrentRead.File, "Select TOP 2 * from " + Identifier);
                        recordCount         = (int)DBReadExecute.GetScalar(Context.CurrentRead.File, "SELECT COUNT(*) FROM " + Identifier);
                        File                = Context.CurrentRead.File;
                        IsEpi7ProjectRead   = Context.CurrentRead.IsEpi7ProjectRead;
                        Context.CurrentRead = this;
                    }
                }
                else
                {
                    Context.AddConnection("_DB", Context.CurrentProject.CollectedDataConnectionString);
                    outputTable         = DBReadExecute.GetDataTable(Context.CurrentProject.CollectedDataConnectionString, "Select TOP 2 * from " + Context.CurrentProject.views[Identifier].FromViewSQL);
                    recordCount         = (int)DBReadExecute.GetScalar(Context.CurrentProject.CollectedDataConnectionString, "SELECT COUNT(*) FROM " + Identifier);
                    File                = Context.CurrentProject.FilePath;
                    Context.CurrentRead = this;
                    IsEpi7ProjectRead   = true;
                }
            }
            else
            {
                Context.AddConnection("_DB", File);
                Context.CurrentRead = this;

                string[]      identifiers       = Identifier.Split('.');
                StringBuilder identifierBuilder = new StringBuilder();

                for (int i = 0; i < identifiers.Length; i++)
                {
                    identifierBuilder.Append("[");
                    identifierBuilder.Append(identifiers[i]);
                    identifierBuilder.Append("].");
                }

                identifierBuilder.Length = identifierBuilder.Length - 1;

                if (DBReadExecute.ProjectFileName != "")
                {
                    IsEpi7ProjectRead      = true;
                    Context.CurrentProject = new Project(DBReadExecute.ProjectFileName);

                    if (Context.CurrentProject.Views.Exists(Identifier))
                    {
                        string tableName = Context.CurrentProject.Views[Identifier].TableName;
                        DataSets.Config.DataDriverDataTable dataDrivers = Configuration.GetNewInstance().DataDrivers;

                        if (!DBReadExecute.CheckDatabaseTableExistance(DBReadExecute.ParseConnectionString(File), tableName, true))
                        {
                            throw new GeneralException(string.Format("The Datatable for [{0}] does NOT exist.\nPlease be sure the Datatable exists before trying to READ.", Identifier));
                        }
                        else
                        {
                            string query = GetEpi7ProjectRecordCountQuery(tableName);
                            recordCount = (int)DBReadExecute.GetScalar(File, query);
                            outputTable = DBReadExecute.GetDataTable(File, "Select TOP 2 * From [" + Context.CurrentProject.Views[Identifier].TableName + "]");

                            foreach (Page page in Context.CurrentProject.Views[Identifier].Pages)
                            {
                                outputTable = JoinTables(outputTable, DBReadExecute.GetDataTable(File, "Select TOP 2 * From [" + page.TableName + "]"));
                            }
                        }
                    }
                    else
                    {
                        outputTable = DBReadExecute.GetDataTable(File, "Select TOP 2 * FROM " + identifierBuilder.ToString());
                        recordCount = (int)DBReadExecute.GetScalar(File, "SELECT COUNT(*) FROM " + identifierBuilder.ToString());
                    }
                }
                else
                {
                    String identifier = identifierBuilder.ToString();
                    outputTable = DBReadExecute.GetDataTable(File, "Select TOP 2 * from " + identifier);
                    recordCount = int.Parse(DBReadExecute.GetScalar(File, "SELECT COUNT(*) FROM " + identifier).ToString());
                }
            }

            outputTable.TableName = "Output";

            Context.DataTableRefreshNeeded = true;

            if (Context.DataSet.Tables.Contains("Output"))
            {
                Context.DataSet.Tables.Remove("Output");
            }

            Context.DataSet.Tables.Add(outputTable);

            if (Context.DataSet.Tables.Contains("datasource"))
            {
                Context.DataSet.Tables.Remove("datasource");
            }

            DataTable datasouceTable = new DataTable("datasource");

            foreach (DataColumn column in outputTable.Columns)
            {
                DataColumn newColumn = new DataColumn(column.ColumnName);
                newColumn.DataType = column.DataType;
                datasouceTable.Columns.Add(newColumn);
            }

            Context.DataSet.Tables.Add(datasouceTable);
            Context.MemoryRegion.RemoveVariablesInScope(VariableType.DataSource);
            Context.ReadDataSource(datasouceTable);
            Context.GroupVariableList = new Dictionary <string, List <string> >();

            if (Rule_Read.RemoveVariables)
            {
                if (Context.DataSet.Tables.Contains("variables"))
                {
                    Context.DataSet.Tables.Remove("variables");
                    Context.MemoryRegion.RemoveVariablesInScope(VariableType.Standard);
                }

                if (Context.SelectExpression != null)
                {
                    Context.SelectExpression.Clear();
                }
                if (Context.SubroutineList != null)
                {
                    Context.SubroutineList.Clear();
                }
                if (Context.Subroutine != null)
                {
                    Context.Subroutine.Clear();
                }

                Context.SelectString.Length   = 0;
                Context.SortExpression.Length = 0;
            }
            else
            {
                Rule_Read.RemoveVariables = true;
            }

            Context.SyncVariableAndOutputTable();
            Context.ClearParticipatingVariableList();

            Context.GetOutput();

            result = string.Format("number of records read {0}", recordCount);
            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("COMMANDNAME", CommandNames.READ);
            args.Add("FILENAME", File);
            args.Add("TABLENAME", Identifier);
            args.Add("ROWCOUNT", recordCount.ToString());

            Project currentProject = Context.CurrentProject;

            if (string.IsNullOrEmpty(File) && currentProject == null)
            {
                throw new GeneralException(SharedStrings.NO_CURRENT_PROJECT);
            }

            Context.AnalysisCheckCodeInterface.Display(args);
            return(result);
        }
Exemplo n.º 18
0
        private void BuildKeyDialog_Load(object sender, EventArgs e)
        {
            if (SelectedDataSource != null)
            {
                if (SelectedDataSource is IDbDriver)
                {
                    IDbDriver db = SelectedDataSource as IDbDriver;
                    //--EI-114
                    // relatedFields = db.GetTableColumnNames(RelatedTable);
                    if (RelatedTable.Contains(StringLiterals.SPACE))
                    {
                        string    pstr      = "Select TOP 2 * from [" + RelatedTable + "]";
                        DataTable relfields = DBReadExecute.GetDataTable(db, pstr);
                        foreach (DataColumn dc in relfields.Columns)
                        {
                            relatedFields.Add(dc.ColumnName);
                        }
                    }
                    else
                    {
                        relatedFields = db.GetTableColumnNames(RelatedTable);
                    }
                    //---
                }
                else if (SelectedDataSource is Project)
                {
                    Project project = SelectedDataSource as Project;

                    if (project.Views.Exists(relatedTable))
                    {
                        foreach (Epi.Fields.IField field in project.Views[RelatedTable].Fields)
                        {
                            if (!(field is Epi.Fields.LabelField) &
                                !(field is Epi.Fields.CommandButtonField) &
                                !(field is Epi.Fields.PhoneNumberField) &
                                !(field is Epi.Fields.MultilineTextField) &
                                !(field is Epi.Fields.GroupField) &
                                !(field is Epi.Fields.CheckBoxField) &
                                !(field is Epi.Fields.ImageField) &
                                !(field is Epi.Fields.OptionField) &
                                !(field is Epi.Fields.GridField) &
                                !(field is Epi.Fields.MirrorField))
                            {
                                relatedFields.Add(field.Name);
                            }
                        }
                    }
                    else
                    {
                        relatedFields = project.GetTableColumnNames(RelatedTable);
                    }
                }

                currentFields = GetCurrentFields();
            }

            relatedFields.Sort();
            currentFields.Sort();

            lbxRelatedTableFields.DataSource = relatedFields;
            lbxCurrentTableFields.DataSource = currentFields;

            lbxCurrentTableFields.SelectedIndex = -1;
            lbxRelatedTableFields.SelectedIndex = -1;

            if (CallingDialog == "RELATE")
            {
                lblBuildKeyInstructions.Text = SharedStrings.BUILDKEY_RELATE_INSTRUCTIONS;
            }
            else
            {
                lblBuildKeyInstructions.Text = SharedStrings.BUILDKEY_MERGE_INSTRUCTIONS;
            }

            this.LoadIsFinished = true;
        }