Пример #1
0
        /// <summary>
        /// returns true if table exists
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns>bool</returns>
        public bool TableExists(string tableName)
        {
            if (string.IsNullOrEmpty(tableName))
            {
                throw new ArgumentException("tableName");
            }

            return(db.TableExists(tableName));
        }
Пример #2
0
        public CountryNameEditor(EpiDataHelper dataHelper)
        {
            InitializeComponent();

            Database   = dataHelper.Database;
            DataHelper = dataHelper;

            IDbDriver db = DataHelper.Database; // lazy

            if (!db.TableExists("codeCountryList"))
            {
                List <Epi.Data.TableColumn> tableColumns = new List <Epi.Data.TableColumn>();
                tableColumns.Add(new Epi.Data.TableColumn("COUNTRY", GenericDbColumnType.String, 255, true, false));
                db.CreateTable("codeCountryList", tableColumns);
            }

            Query selectQuery = Database.CreateQuery("SELECT * FROM [codeCountryList] ORDER BY COUNTRY");
            bool  exists      = Database.TableExists("codeCountryList");

            dg.ItemsSource = (Database.Select(selectQuery)).DefaultView;
        }
Пример #3
0
        /// <summary>
        /// Handles the DoWorker event for the worker
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            lock (syncLock)
            {
                System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();

                try
                {
                    string tableName = (string)e.Argument;

                    SetGadgetStatusHandler      requestUpdateStatus  = new SetGadgetStatusHandler(RequestUpdateStatusMessage);
                    CheckForCancellationHandler checkForCancellation = new CheckForCancellationHandler(IsCancelled);

                    if (db.TableExists(tableName))
                    {
                        db.DeleteTable(tableName);
                    }

                    List <Epi.Data.TableColumn> tcList = dashboardHelper.GetFieldsAsListOfEpiTableColumns();

                    db.CreateTable(tableName, tcList);

                    DataView dv = dashboardHelper.DataSet.Tables[0].DefaultView;

                    System.Data.Common.DbDataReader dataReader = dv.ToTable().CreateDataReader();
                    db.InsertBulkRows("Select * From [" + tableName + "]", dataReader, requestUpdateStatus, checkForCancellation);
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetWarningMessage), ex.Message);
                }
                finally
                {
                    stopWatch.Stop();
                    System.Diagnostics.Debug.Print("Export thread finished in " + stopWatch.Elapsed.ToString());
                }
            }
        }
Пример #4
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);
        }
        private Dictionary <string, List <TableColumn> > CreateAccessWideTable(List <TableColumn> pTableColumns, bool pCreateTable = true)
        {
            Dictionary <string, List <TableColumn> > result = new Dictionary <string, List <TableColumn> >();

            int columnCount = 0;
            int sequence    = 0;

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

            foreach (TableColumn column in pTableColumns)
            {
                if (column.IsIdentity || column.IsPrimaryKey || column.Name.Equals("UniqueKey", StringComparison.OrdinalIgnoreCase) || column.Name.Equals("GlobalRecordId", StringComparison.OrdinalIgnoreCase))
                {
                    primaryKeyList.Add(column);
                }
            }
            List <TableColumn> ParcialTableColumns = new List <TableColumn>();

            ParcialTableColumns.AddRange(primaryKeyList);
            columnCount = ParcialTableColumns.Count;

            string[] tableName = new string[pTableColumns.Count / Max_Number_Columns + 1];
            tableName[0] = this.TableName;
            foreach (TableColumn column in pTableColumns)
            {
                if (columnCount < Max_Number_Columns)
                {
                    if (ParcialTableColumns.Contains(column))
                    {
                    }
                    else
                    {
                        ParcialTableColumns.Add(column);
                    }
                }
                else
                {
                    if (!OutputDriver.TableExists(tableName[sequence]))
                    {
                        if (pCreateTable)
                        {
                            OutputDriver.CreateTable(tableName[sequence], ParcialTableColumns);
                        }
                    }
                    result.Add(tableName[sequence], ParcialTableColumns);
                    sequence += 1;

                    if (sequence > 0)
                    {
                        tableName[sequence] = tableName[0] + "_Seq" + sequence.ToString();
                    }

                    ParcialTableColumns = new List <TableColumn>();
                    ParcialTableColumns.AddRange(primaryKeyList);
                    columnCount = ParcialTableColumns.Count;
                }
                columnCount += 1;
            }


            if (!OutputDriver.TableExists(tableName[sequence]))
            {
                if (pCreateTable)
                {
                    OutputDriver.CreateTable(tableName[sequence], ParcialTableColumns);
                }
            }
            result.Add(tableName[sequence], ParcialTableColumns);

            return(result);
        }
        /// <summary>
        /// Sets the appropriate properties for a given field, based on the specified column conversion information
        /// </summary>
        /// <param name="field">The Epi Info 7 field</param>
        /// <param name="cci">The column conversion information</param>
        private void SetFieldProperties(Field field, ColumnConversionInfo cci)
        {
            if (cci.Prompt == null)
            {
                cci.Prompt = cci.DestinationColumnName;
            }
            switch (field.FieldType)
            {
            case MetaFieldType.Checkbox:
                CheckBoxField checkboxField = (CheckBoxField)field;
                checkboxField.TabIndex         = cci.TabIndex;
                checkboxField.IsReadOnly       = cci.IsReadOnly;
                checkboxField.IsRequired       = cci.IsRequired;
                checkboxField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.YesNo:
                YesNoField yesNoField = (YesNoField)field;
                yesNoField.TabIndex         = cci.TabIndex;
                yesNoField.IsReadOnly       = cci.IsReadOnly;
                yesNoField.IsRequired       = cci.IsRequired;
                yesNoField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.Text:
                SingleLineTextField textField = (SingleLineTextField)field;
                textField.TabIndex         = cci.TabIndex;
                textField.IsReadOnly       = cci.IsReadOnly;
                textField.IsRequired       = cci.IsRequired;
                textField.ShouldRepeatLast = cci.IsRepeatLast;
                if (cci.UpperBound is int)
                {
                    textField.MaxLength = (int)cci.UpperBound;
                }
                break;

            case MetaFieldType.Multiline:
                MultilineTextField multilineTextField = (MultilineTextField)field;
                multilineTextField.TabIndex         = cci.TabIndex;
                multilineTextField.IsReadOnly       = cci.IsReadOnly;
                multilineTextField.IsRequired       = cci.IsRequired;
                multilineTextField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.Date:
                DateField dateField = (DateField)field;
                dateField.TabIndex         = cci.TabIndex;
                dateField.IsReadOnly       = cci.IsReadOnly;
                dateField.IsRequired       = cci.IsRequired;
                dateField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.DateTime:
                DateTimeField dateTimeField = (DateTimeField)field;
                dateTimeField.TabIndex         = cci.TabIndex;
                dateTimeField.IsReadOnly       = cci.IsReadOnly;
                dateTimeField.IsRequired       = cci.IsRequired;
                dateTimeField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.Time:
                TimeField timeField = (TimeField)field;
                timeField.TabIndex         = cci.TabIndex;
                timeField.IsReadOnly       = cci.IsReadOnly;
                timeField.IsRequired       = cci.IsRequired;
                timeField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.Number:
                NumberField numberField = (NumberField)field;
                numberField.TabIndex         = cci.TabIndex;
                numberField.IsReadOnly       = cci.IsReadOnly;
                numberField.IsRequired       = cci.IsRequired;
                numberField.ShouldRepeatLast = cci.IsRepeatLast;
                break;

            case MetaFieldType.LegalValues:
                DDLFieldOfLegalValues legalValuesField = (DDLFieldOfLegalValues)field;
                legalValuesField.TabIndex         = cci.TabIndex;
                legalValuesField.IsReadOnly       = cci.IsReadOnly;
                legalValuesField.IsRequired       = cci.IsRequired;
                legalValuesField.ShouldRepeatLast = cci.IsRepeatLast;

                if (string.IsNullOrEmpty(cci.ListSourceTableName))
                {
                    DataTable dt = new DataTable(cci.SourceColumnName);
                    dt.Columns.Add(new DataColumn(cci.SourceColumnName, typeof(string)));
                    // table is blank, so assume user wants to use a SELECT DISTINCT as the value source
                    Query       selectDistinctQuery = sourceDriver.CreateQuery("SELECT DISTINCT [" + cci.SourceColumnName + "] FROM [" + tableName + "]");
                    IDataReader distinctReader      = sourceDriver.ExecuteReader(selectDistinctQuery);
                    while (distinctReader.Read())
                    {
                        dt.Rows.Add(distinctReader[0].ToString());
                    }

                    cci.ListSourceTable          = dt;
                    cci.ListSourceTableName      = cci.SourceColumnName;
                    cci.ListSourceTextColumnName = cci.SourceColumnName;

                    IDbDriver db = project.CollectedData.GetDatabase();
                    if (!db.TableExists(cci.ListSourceTableName))
                    {
                        project.CreateCodeTable(cci.ListSourceTableName, cci.ListSourceTextColumnName);
                        project.SaveCodeTableData(cci.ListSourceTable, cci.ListSourceTableName, cci.ListSourceTextColumnName);
                    }

                    legalValuesField.SourceTableName = cci.ListSourceTableName;
                    legalValuesField.TextColumnName  = cci.ListSourceTextColumnName;
                    legalValuesField.CodeColumnName  = cci.ListSourceTextColumnName;
                }
                else
                {
                    IDbDriver db = project.CollectedData.GetDatabase();
                    if (!db.TableExists(cci.ListSourceTableName))
                    {
                        project.CreateCodeTable(cci.ListSourceTableName, cci.ListSourceTextColumnName);
                        string[] columns = new string[1];
                        columns[0] = cci.ListSourceTextColumnName;
                        project.InsertCodeTableData(cci.ListSourceTable, cci.ListSourceTableName, columns);
                    }
                    legalValuesField.SourceTableName = cci.ListSourceTableName;
                    legalValuesField.TextColumnName  = cci.ListSourceTextColumnName;
                    legalValuesField.CodeColumnName  = cci.ListSourceTextColumnName;
                }
                break;

            default:
                throw new ApplicationException("Invalid field type");
                //break;
            }

            double ControlHeightPercentage = 0.0;
            double ControlWidthPercentage  = 0.0;

            if (field is FieldWithSeparatePrompt)
            {
                FieldWithSeparatePrompt fieldWithPrompt;
                fieldWithPrompt             = (FieldWithSeparatePrompt)field;
                fieldWithPrompt.PromptText  = cci.Prompt;
                fieldWithPrompt.PromptFont  = cci.PromptFont;
                fieldWithPrompt.ControlFont = cci.ControlFont;
                fieldWithPrompt.PromptLeftPositionPercentage = cci.ControlLeftPosition / 100;
                fieldWithPrompt.PromptTopPositionPercentage  = cci.ControlTopPosition / 100;
                fieldWithPrompt.Name = cci.DestinationColumnName;
                fieldWithPrompt.ControlHeightPercentage       = ControlHeightPercentage / 100;
                fieldWithPrompt.ControlWidthPercentage        = ControlWidthPercentage / 100;
                fieldWithPrompt.ControlTopPositionPercentage  = cci.ControlTopPosition / 100;
                fieldWithPrompt.ControlLeftPositionPercentage = (cci.ControlLeftPosition / 100) + 0.090702947845805;

                fieldWithPrompt.UpdatePromptPosition();
                fieldWithPrompt.UpdateControlPosition();
            }
            else
            {
                FieldWithoutSeparatePrompt fieldWithoutPrompt;
                fieldWithoutPrompt            = (FieldWithoutSeparatePrompt)field;
                fieldWithoutPrompt.PromptText = cci.Prompt;
                fieldWithoutPrompt.PromptFont = cci.PromptFont;
                fieldWithoutPrompt.Name       = cci.DestinationColumnName;

                fieldWithoutPrompt.ControlHeightPercentage       = ControlHeightPercentage / 100;
                fieldWithoutPrompt.ControlWidthPercentage        = ControlWidthPercentage / 100;
                fieldWithoutPrompt.ControlTopPositionPercentage  = cci.ControlTopPosition / 100;
                fieldWithoutPrompt.ControlLeftPositionPercentage = (cci.ControlLeftPosition / 100) + 0.090702947845805;

                fieldWithoutPrompt.UpdateControlPosition();
            }
        }
Пример #7
0
        protected virtual void WriteFollowUpsData(XmlWriter writer)
        {
            MinorProgress = 0;
            OnMinorProgressChanged();

            string    selectQueryText = "SELECT * FROM metaHistory";
            IDbDriver db = Project.CollectedData.GetDatabase();

            CultureInfo format = CultureInfo.InvariantCulture;

            if (!db.TableExists("metaHistory"))
            {
                return;
            }

            writer.WriteStartElement("ContactFollowUps");

            Query selectQuery = db.CreateQuery(selectQueryText);

            double totalRecords = Convert.ToDouble(db.ExecuteScalar(db.CreateQuery("SELECT COUNT(*) FROM metaHistory")));
            double inc          = 100 / totalRecords;

            bool   filter        = _contactGuids != null;
            string contactFormId = Project.Views[Core.Constants.CONTACT_FORM_NAME].Id.ToString();

            using (IDataReader reader = db.ExecuteReader(selectQuery))
            {
                while (reader.Read())
                {
                    string contactGuid = reader["ContactGUID"].ToString();

                    if (filter && !_contactGuids.Contains(contactGuid))
                    {
                        continue;
                    }

                    writer.WriteStartElement("ContactFollowUp");

                    #region Followup Fields

                    writer.WriteStartElement("ContactGUID");
                    writer.WriteString(contactGuid);
                    writer.WriteEndElement();

                    writer.WriteStartElement("FollowUpDate");
                    writer.WriteString(Convert.ToDateTime(reader["FollowUpDate"]).ToString(format.DateTimeFormat.ShortDatePattern));
                    writer.WriteEndElement();

                    if (!String.IsNullOrEmpty(reader["StatusOnDate"].ToString()))
                    {
                        writer.WriteStartElement("StatusOnDate");
                        writer.WriteString(reader["StatusOnDate"].ToString());
                        writer.WriteEndElement();
                    }

                    if (!String.IsNullOrEmpty(reader["Note"].ToString()))
                    {
                        writer.WriteStartElement("Note");
                        writer.WriteString(reader["Note"].ToString());
                        writer.WriteEndElement();
                    }

                    if (!String.IsNullOrEmpty(reader["Temp1"].ToString()))
                    {
                        writer.WriteStartElement("Temp1");
                        writer.WriteString(reader["Temp1"] == DBNull.Value ? String.Empty : Convert.ToDouble(reader["Temp1"]).ToString(System.Globalization.CultureInfo.InvariantCulture));
                        writer.WriteEndElement();
                    }

                    if (!String.IsNullOrEmpty(reader["Temp2"].ToString()))
                    {
                        writer.WriteStartElement("Temp2");
                        writer.WriteString(reader["Temp2"] == DBNull.Value ? String.Empty : Convert.ToDouble(reader["Temp2"]).ToString(System.Globalization.CultureInfo.InvariantCulture));
                        writer.WriteEndElement();
                    }

                    #endregion // Followup Fields

                    writer.WriteEndElement();

                    MinorProgress += inc;
                    OnMinorProgressChanged();

                    OnMinorStatusChanged(String.Format("{0} of contact tracing records exported...", (MinorProgress / 100).ToString("P0")));
                }
            }

            writer.WriteEndElement();
        }
Пример #8
0
        /// <summary>
        /// Handles the DoWorker event for the worker
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void datadriverWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            lock (syncLock)
            {
                System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();

                try
                {
                    string tableName = (string)e.Argument;

                    SetGadgetStatusHandler      requestUpdateStatus  = new SetGadgetStatusHandler(RequestUpdateStatusMessage);
                    CheckForCancellationHandler checkForCancellation = new CheckForCancellationHandler(IsCancelled);

                    if (db.TableExists(tableName) && !db.ConnectionDescription.ToLower().Contains("excel"))
                    {
                        db.DeleteTable(tableName);
                    }
                    else if (db.TableExists(tableName))
                    {
                        this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetErrorMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_EXCEL_TABLE_OVERWRITE_FAIL, tableName));
                        stopWatch.Stop();
                        return;
                    }

                    dashboardHelper.PopulateDataSet(); // the only reason to call this is to see if any new user-defined vars have been added and apply them.
                    List <Epi.Data.TableColumn> tcList = dashboardHelper.GetFieldsAsListOfEpiTableColumns(useTabOrder);
                    allFieldsSelected = false;         // TODO: Fix?

                    if (allFieldsSelected)
                    {
                        if (tcList.Count <= 250)
                        {
                            db.CreateTable(tableName, tcList);
                            DataView  dv    = dashboardHelper.DataSet.Tables[0].DefaultView;
                            DataTable table = dv.ToTable(false);
                            if (useTabOrder)
                            {
                                dashboardHelper.OrderColumns(table, true);
                            }
                            System.Data.Common.DbDataReader dataReader = table.CreateDataReader();
                            db.InsertBulkRows("Select * From [" + tableName + "]", dataReader, requestUpdateStatus, checkForCancellation);
                        }
                        else
                        {
                            Dictionary <string, List <Epi.Data.TableColumn> > fieldTableDictionary = new Dictionary <string, List <Epi.Data.TableColumn> >();
                            int totalTablesNeeded = (tcList.Count / 250) + 1;
                            int tableNumber       = 0;
                            List <Epi.Data.TableColumn> tableTcList = new List <Epi.Data.TableColumn>();
                            for (int i = 0; i < tcList.Count; i++)
                            {
                                if (i % 250 == 0)
                                {
                                    if (tableNumber != 0)
                                    {
                                        fieldTableDictionary.Add(tableName + tableNumber.ToString(), tableTcList);
                                    }
                                    tableTcList = new List <Epi.Data.TableColumn>();
                                    tableNumber++;
                                }

                                tableTcList.Add(tcList[i]);

                                if (i == tcList.Count - 1)
                                {
                                    fieldTableDictionary.Add(tableName + tableNumber.ToString(), tableTcList);
                                }
                            }

                            foreach (KeyValuePair <string, List <Epi.Data.TableColumn> > kvp in fieldTableDictionary)
                            {
                                if (db.TableExists(kvp.Key))
                                {
                                    this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetErrorMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_WIDE_TABLE_FAIL, totalTablesNeeded.ToString()));
                                    return;
                                }
                            }

                            foreach (KeyValuePair <string, List <Epi.Data.TableColumn> > kvp in fieldTableDictionary)
                            {
                                db.CreateTable(kvp.Key, kvp.Value);
                            }

                            foreach (KeyValuePair <string, List <Epi.Data.TableColumn> > kvp in fieldTableDictionary)
                            {
                                List <string> exportTableFields = new List <string>();
                                foreach (Epi.Data.TableColumn tc in kvp.Value)
                                {
                                    exportTableFields.Add(tc.Name);
                                }

                                DataView  dv    = dashboardHelper.DataSet.Tables[0].DefaultView;
                                DataTable table = dv.ToTable(false, exportTableFields.ToArray());
                                if (useTabOrder)
                                {
                                    dashboardHelper.OrderColumns(table, true);
                                }
                                System.Data.Common.DbDataReader dataReader = table.CreateDataReader(); //dv.ToTable().CreateDataReader();
                                db.InsertBulkRows("Select * From [" + kvp.Key + "]", dataReader, requestUpdateStatus, checkForCancellation);
                            }
                        }
                    }
                    else
                    {
                        List <Epi.Data.TableColumn> tcFilteredList = new List <Epi.Data.TableColumn>();

                        foreach (string columnName in exportFields)
                        {
                            foreach (Epi.Data.TableColumn tc in tcList)
                            {
                                if (tc.Name.Equals(columnName) && !tcFilteredList.Contains(tc))
                                {
                                    tcFilteredList.Add(tc);
                                }
                            }
                        }

                        if (tcFilteredList.Count <= 250)
                        {
                            db.CreateTable(tableName, tcFilteredList);
                            DataView  dv    = dashboardHelper.DataSet.Tables[0].DefaultView;
                            DataTable table = dv.ToTable(false, exportFields.ToArray());
                            if (useTabOrder)
                            {
                                dashboardHelper.OrderColumns(table, true);
                            }
                            System.Data.Common.DbDataReader dataReader = table.CreateDataReader(); //dv.ToTable().CreateDataReader();
                            db.InsertBulkRows("Select * From [" + tableName + "]", dataReader, requestUpdateStatus, checkForCancellation);
                        }
                        else
                        {
                            Dictionary <string, List <Epi.Data.TableColumn> > fieldTableDictionary = new Dictionary <string, List <Epi.Data.TableColumn> >();
                            int totalTablesNeeded = (tcFilteredList.Count / 250) + 1;
                            int tableNumber       = 0;
                            List <Epi.Data.TableColumn> tableTcList = new List <Epi.Data.TableColumn>();
                            for (int i = 0; i < tcFilteredList.Count; i++)
                            {
                                if (i % 250 == 0)
                                {
                                    if (tableNumber != 0)
                                    {
                                        foreach (Epi.Data.TableColumn tc in tcFilteredList)
                                        {
                                            if (tc.Name == "GlobalRecordId")
                                            {
                                                if (!tableTcList.Contains(tc))
                                                {
                                                    tableTcList.Add(tc);
                                                }
                                            }
                                        }

                                        fieldTableDictionary.Add(tableName + tableNumber.ToString(), tableTcList);
                                    }
                                    tableTcList = new List <Epi.Data.TableColumn>();
                                    tableNumber++;
                                }

                                tableTcList.Add(tcFilteredList[i]);

                                if (i == tcFilteredList.Count - 1)
                                {
                                    foreach (Epi.Data.TableColumn tc in tcFilteredList)
                                    {
                                        if (tc.Name == "GlobalRecordId")
                                        {
                                            if (!tableTcList.Contains(tc))
                                            {
                                                tableTcList.Add(tc);
                                            }
                                        }
                                    }

                                    fieldTableDictionary.Add(tableName + tableNumber.ToString(), tableTcList);
                                }
                            }

                            foreach (KeyValuePair <string, List <Epi.Data.TableColumn> > kvp in fieldTableDictionary)
                            {
                                if (db.TableExists(kvp.Key))
                                {
                                    this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetErrorMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_WIDE_TABLE_FAIL, totalTablesNeeded.ToString()));
                                    return;
                                }
                            }

                            foreach (KeyValuePair <string, List <Epi.Data.TableColumn> > kvp in fieldTableDictionary)
                            {
                                db.CreateTable(kvp.Key, kvp.Value);
                            }

                            foreach (KeyValuePair <string, List <Epi.Data.TableColumn> > kvp in fieldTableDictionary)
                            {
                                List <string> exportTableFields = new List <string>();
                                foreach (Epi.Data.TableColumn tc in kvp.Value)
                                {
                                    exportTableFields.Add(tc.Name);
                                }

                                DataView  dv    = dashboardHelper.DataSet.Tables[0].DefaultView;
                                DataTable table = dv.ToTable(false, exportTableFields.ToArray());
                                if (useTabOrder)
                                {
                                    dashboardHelper.OrderColumns(table, true);
                                }
                                System.Data.Common.DbDataReader dataReader = table.CreateDataReader(); //dv.ToTable().CreateDataReader();
                                db.InsertBulkRows("Select * From [" + kvp.Key + "]", dataReader, requestUpdateStatus, checkForCancellation);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetErrorMessage), ex.Message);
                }
                finally
                {
                    stopWatch.Stop();
                    System.Diagnostics.Debug.Print("Export thread finished in " + stopWatch.Elapsed.ToString());
                }
            }
        }
        void ToNodeFiller_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (lvLinkedTo.InvokeRequired)
                {
                    lvLinkedTo.Invoke(new MethodInvoker(delegate
                    {
                        lvLinkedTo.Items.Clear();
                        lvLinkedTo.Groups.Clear();
                    }));
                }
                else
                {
                    lvLinkedTo.Items.Clear();
                    lvLinkedTo.Groups.Clear();
                }
                if (btnUnlinkTo.InvokeRequired)
                {
                    btnUnlinkTo.Invoke(new MethodInvoker(delegate
                    {
                        btnUnlinkTo.Enabled = false;
                    }));
                }
                else
                {
                    btnUnlinkTo.Enabled = false;
                }

                Dictionary <string, string> fieldNames = new Dictionary <string, string>();
                Query query;

                query = db.CreateQuery
                        (
                    "SELECT [metaPages.PageId] as PageId, [metaPages.ViewId] as ViewId, [metaViews.Name] as Name " +
                    "FROM [metaPages] " +
                    "LEFT OUTER JOIN [metaViews] ON metaPages.ViewId = metaViews.ViewId " +
                    "WHERE [metaPages.Position] = 0"
                        );

                DataTable pageIds = db.Select(query);

                query = db.CreateQuery
                        (
                    "SELECT [metaFields.Name] as Name, [metaFields.PageId] as PageId, [metaFields.ViewId] as ViewId, [metaFields.TabIndex] as TabIndex " +
                    "FROM [metaFields] " +
                    "LEFT OUTER JOIN [metaPages] ON metaPages.ViewId = metaFields.ViewId " +
                    "WHERE [metaFields.HasTabStop] = true AND [metaPages.Position] = 0 " +
                    "ORDER BY [metaFields.ViewId], [metaFields.TabIndex]"
                        );

                DataTable fields = db.Select(query);

                List <string> list = fields.AsEnumerable().Select(r => r.Field <string>(0)).ToList();

                string uniqueKeys = "";
                string parens     = "";
                string joins      = "";

                foreach (View view in enterMainForm.View.Project.Views)
                {
                    if (!string.IsNullOrEmpty(view.TableName) && db.TableExists(view.TableName))
                    {
                        if (!view.IsRelatedView)
                        {
                            uniqueKeys += "t" + view.Id + ".UniqueKey as Key" + view.Id + ", ";
                            parens     += "(";
                            joins      += "left outer join " + view.TableName + " t" + view.Id + " on m.ToRecordGuid = t" + view.Id + ".GlobalRecordId) ";
                        }
                    }
                }

                uniqueKeys = uniqueKeys.Substring(0, uniqueKeys.Length - 2) + " ";

                query = db.CreateQuery(@"Select FromRecordGuid, ToRecordGuid, FromViewId, ToViewId, " + uniqueKeys + " from " + parens + "metaLinks m " + joins + " where m.FromRecordGuid = @GlobalRecordId");
                QueryParameter parameter = new QueryParameter("@GlobalRecordId", DbType.StringFixedLength, enterMainForm.View.CurrentGlobalRecordId);
                parameter.Size = enterMainForm.View.CurrentGlobalRecordId.Length;
                query.Parameters.Add(parameter);
                DataTable data = db.Select(query);

                if (data.Rows.Count > 0)
                {
                    foreach (View view in enterMainForm.View.Project.Views)
                    {
                        if (lvLinkedTo.InvokeRequired)
                        {
                            lvLinkedTo.Invoke(new MethodInvoker(delegate
                            {
                                lvLinkedTo.Groups.Add(view.Id.ToString(), view.Name);
                            }));
                        }
                        else
                        {
                            lvLinkedTo.Groups.Add(view.Id.ToString(), view.Name);
                        }
                    }
                }

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

                string        toViewId     = string.Empty;
                string        toRecordGuid = string.Empty;
                string        fieldPrint   = string.Empty;
                DataRow[]     fieldRows    = null;
                List <string> fieldPrintList;
                string        collectedDataTableName = string.Empty;

                foreach (DataRow row in data.Rows)
                {
                    ListViewItem item = new ListViewItem();

                    toViewId     = row["ToViewId"].ToString();
                    toRecordGuid = row["ToRecordGuid"].ToString();

                    DataRow[] oneRow = pageIds.Select("ViewId = '" + toViewId + "'");
                    collectedDataTableName = ((string)oneRow[0]["Name"]) + ((string)oneRow[0]["PageId"].ToString());

                    fieldRows = fields.Select("ViewId = " + toViewId);

                    List <string> columnNames = db.GetTableColumnNames(collectedDataTableName);
                    fieldPrintList = fieldRows.Select(r => r.Field <string>(0)).ToList();
                    fieldPrintList = fieldPrintList.Intersect(columnNames).ToList();
                    fieldPrintList.Add("GlobalRecordId");

                    var datatable = db.GetTableData(collectedDataTableName, fieldPrintList);
                    var theRow    = datatable.Select("GlobalRecordId = '" + toRecordGuid + "'");

                    fieldPrint = row["Key" + row["ToViewId"].ToString()].ToString();;

                    if (theRow != null)
                    {
                        fieldPrint += " :: ";
                        fieldPrint += theRow[0][0].ToString() + "; " + theRow[0][1].ToString() + "; " + theRow[0][2].ToString();
                    }

                    item      = new ListViewItem(fieldPrint);
                    item.Tag  = row["Key" + row["ToViewId"].ToString()].ToString();
                    item.Name = toRecordGuid;

                    for (int x = 0; x < data.Columns.Count; x++)
                    {
                        item.SubItems.Add(row[x].ToString());
                    }

                    item.ImageIndex = 0;
                    item.Group      = lvLinkedTo.Groups[row["ToViewId"].ToString()];

                    if (names.Contains(toRecordGuid) == false)
                    {
                        names.Add(toRecordGuid);

                        if (lvLinkedTo.InvokeRequired)
                        {
                            lvLinkedTo.Invoke(new MethodInvoker(delegate
                            {
                                if (lvLinkedTo.Items.ContainsKey(toRecordGuid) == false)
                                {
                                    lvLinkedTo.Items.Add(item);
                                }
                            }));
                        }
                        else
                        {
                            if (lvLinkedTo.Items.ContainsKey(toRecordGuid) == false)
                            {
                                lvLinkedTo.Items.Add(item);
                            }
                        }
                    }
                }
            }
            catch { }
        }
Пример #10
0
        protected override void OnOK()
        {
            try
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                System.Collections.Generic.List <string> ProblemVariableList = new System.Collections.Generic.List <string>();
                if (cbxAllExcept.Checked)
                {
                    foreach (string s in lbxVariables.Items)
                    {
                        if (!this.lbxVariables.SelectedItems.Contains(s))
                        {
                            if (s.IndexOf(' ') == 0)
                            {
                                if (ProblemVariableList.Count == 0)
                                {
                                    sb.Append("[");
                                }
                                else
                                {
                                    sb.Append(" ,[");
                                }
                                sb.Append(s);
                                sb.Append("] ");
                                ProblemVariableList.Add(s);
                            }
                        }
                    }
                }
                else
                {
                    foreach (string s in lbxVariables.SelectedItems)
                    {
                        if (s.IndexOf(' ') == 0)
                        {
                            if (ProblemVariableList.Count == 0)
                            {
                                sb.Append("[");
                            }
                            else
                            {
                                sb.Append(" ,[");
                            }
                            sb.Append(s);
                            sb.Append("] ");
                            ProblemVariableList.Add(s);
                        }
                    }
                }

                if (ProblemVariableList.Count > 0)
                {
                    Epi.Windows.MsgBox.ShowError(string.Format(SharedStrings.EXPORT_CANNOT_PROCEED_LEADING_TRAILING_SPACES, sb.ToString()));
                    return;
                }
                else if (selectedDataSource is IDbDriver)
                {
                    Type csv = Type.GetType("Epi.Data.Office.CsvFile, Epi.Data.Office");
                    if (selectedDataSource.GetType().AssemblyQualifiedName == csv.AssemblyQualifiedName)
                    {
                        cmbDataTable.Text = cmbDataTable.Text.Replace('.', '#');
                        if (!cmbDataTable.Text.Contains("#"))
                        {
                            //cmbDataTable.Text = cmbDataTable.Text + "#txt";
                            cmbDataTable.Text = cmbDataTable.Text + "#csv";
                        }
                    }

                    IDbDriver db = selectedDataSource as IDbDriver;
                    if (db.TableExists(((Epi.Windows.Analysis.Dialogs.WriteDialog.ComboBoxItem)(cmbDataTable.SelectedItem)).Value.ToString()))
                    {
                        DataTable temp = db.Select(db.CreateQuery("SELECT COUNT (*) FROM " + ((Epi.Windows.Analysis.Dialogs.WriteDialog.ComboBoxItem)(cmbDataTable.SelectedItem)).Value.ToString()));
                        if (temp.Rows.Count > 0)
                        {
                            int count = (int)temp.Rows[0][0];
                            if (count > 0)
                            {
                                if (rdbAppend.Checked)
                                {
                                    if (MessageBox.Show(string.Format(SharedStrings.EXISTING_TABLE_APPEND, cmbDataTable.Text, count.ToString()), "Existing Table", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                                    {
                                        return;
                                    }
                                }
                                else
                                {
                                    if (MessageBox.Show(string.Format(SharedStrings.EXISTING_TABLE_REPLACE, cmbDataTable.Text, count.ToString()), "Existing Table", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //
            }
            base.OnOK();
        }
Пример #11
0
        public void CreateCaseSyncFileStart(ContactTracing.ImportExport.SyncFileFilters filters /*string fileName, bool includeCases, bool includeCaseExposures, bool includeContacts, Epi.ImportExport.Filters.RowFilters filters, bool deIdentifyData, Epi.RecordProcessingScope recordProcessingScope*/)
        {
            if (IsWaitingOnOtherClients)
            {
                return;
            }

            if (String.IsNullOrEmpty(SyncFilePath.Trim()))
            {
                throw new ArgumentNullException("fileName");
            }

            bool success = true;

            IsDataSyncing   = true;
            RecordsExported = String.Empty;

            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            #region Remove extraneous data

            //int rows = 0;

            MinorSyncStatus = "Deleting extraneous page table rows...";
            IDbDriver db = _project.CollectedData.GetDatabase();

            if (db.ToString().ToLower().Contains("sql"))
            {
                using (IDbTransaction transaction = db.OpenTransaction())
                {
                    foreach (View form in _project.Views)
                    {
                        Query formDeleteDuplicateQuery = Database.CreateQuery("WITH cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY GlobalRecordId ORDER BY GlobalRecordId) 'RowRank' FROM " + form.TableName + ") " +
                                                                              "DELETE FROM cte " +
                                                                              "WHERE RowRank > 1");
                        Database.ExecuteNonQuery(formDeleteDuplicateQuery, transaction);

                        foreach (Page page in form.Pages)
                        {
                            Query deleteQuery = db.CreateQuery("DELETE FROM " + form.Name + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + page.TableName + ")");
                            db.ExecuteNonQuery(deleteQuery, transaction);
                            //if (rows > 0)
                            //{
                            //    // report ??
                            //}

                            Query pageDeleteQuery = db.CreateQuery("DELETE FROM " + page.TableName + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + form.Name + ")");
                            db.ExecuteNonQuery(deleteQuery, transaction);
                            //if (rows > 0)
                            //{
                            //    // report ??
                            //}

                            Query pageDeleteDuplicateQuery = Database.CreateQuery("WITH cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY GlobalRecordId ORDER BY GlobalRecordId) 'RowRank' FROM " + page.TableName + ") " +
                                                                                  "DELETE FROM cte " +
                                                                                  "WHERE RowRank > 1");
                            Database.ExecuteNonQuery(pageDeleteDuplicateQuery, transaction);
                        }
                    }

                    Query linksDeleteQuery = db.CreateQuery("DELETE FROM metaLinks WHERE ToViewId = @ToViewId AND ToRecordGuid NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")");
                    linksDeleteQuery.Parameters.Add(new QueryParameter("@ToViewId", DbType.Int32, ContactFormId));
                    db.ExecuteNonQuery(linksDeleteQuery, transaction);

                    if (db.TableExists("metaHistory"))
                    {
                        Query historyDeleteQuery = db.CreateQuery("DELETE FROM metaHistory WHERE ContactGUID NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")");
                        db.ExecuteNonQuery(historyDeleteQuery, transaction);
                    }

                    try
                    {
                        transaction.Commit();
                    }
                    catch (Exception ex0)
                    {
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup exception Type: {0}", ex0.GetType()));
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup exception Message: {0}", ex0.Message));
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup rollback started..."));
                        DbLogger.Log("Database cleanup failed on commit. Exception: " + ex0.Message);

                        try
                        {
                            transaction.Rollback();
                            Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup rollback was successful."));
                        }
                        catch (Exception ex1)
                        {
                            DbLogger.Log("Database cleanup rollback failed. Exception: " + ex1.Message);
                        }
                    }

                    db.CloseTransaction(transaction);
                }
            }
            #endregion // Remove extraneous data

            RecordsExported         = String.Empty;
            IsDataSyncing           = true;
            IsShowingExportProgress = true;

            SendMessageForAwaitAll();

            DbLogger.Log(String.Format("Initiated process 'export sync file' - IncludeCasesAndContacts = {0}", IncludeCasesAndContacts));

            Task.Factory.StartNew(
                () =>
            {
                success = CreateCaseSyncFile(filters /*fileName, includeCases, includeCaseExposures, includeContacts, filters, deIdentifyData, recordProcessingScope*/);
            },
                System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(
                delegate
            {
                SendMessageForUnAwaitAll();

                TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
                MajorProgressValue   = 0;

                IsDataSyncing = false;

                MinorProgressValue = 0;

                stopwatch.Stop();
                MinorSyncStatus = String.Empty;

                if (success)
                {
                    HasExportErrors = false;
                    MajorSyncStatus = "Finished exporting data to sync file.";
                    TimeElapsed     = "Elapsed time: " + stopwatch.Elapsed.TotalMinutes.ToString("F1") + " minutes.";
                    DbLogger.Log(String.Format("Completed process 'export sync file' successfully - elapsed time = {0} ms", stopwatch.Elapsed.TotalMilliseconds.ToString()));
                }
                else
                {
                    HasExportErrors = true;
                    MajorSyncStatus = "There was a problem exporting the data.";
                    DbLogger.Log(String.Format("Completed process 'export sync file' with errors"));
                }

                CommandManager.InvalidateRequerySuggested();
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Пример #12
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);
        }
Пример #13
0
        public void CreateCaseSyncFileStart(Epi.ImportExport.Filters.RowFilters filters, Epi.RecordProcessingScope recordProcessingScope)
        {
            if (IsWaitingOnOtherClients)
            {
                return;
            }

            if (String.IsNullOrEmpty(SyncFilePath.Trim()))
            {
                throw new InvalidOperationException();
            }

            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            bool includeCases         = IncludeCasesAndContacts || IncludeCasesOnly;
            bool includeCaseExposures = true;
            bool includeContacts      = IncludeCasesAndContacts;
            bool deIdentifyData       = DeIdentifyData;

            #region Remove extraneous data

            int rows = 0;

            OverallSyncStatus = "Deleting extraneous page table rows...";
            IDbDriver db = _project.CollectedData.GetDatabase();

            foreach (View form in _project.Views)
            {
                foreach (Page page in form.Pages)
                {
                    Query deleteQuery = db.CreateQuery("DELETE FROM " + form.Name + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + page.TableName + ")");
                    rows = db.ExecuteNonQuery(deleteQuery);
                    if (rows > 0)
                    {
                        // report ??
                    }

                    Query pageDeleteQuery = db.CreateQuery("DELETE FROM " + page.TableName + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + form.Name + ")");
                    rows = db.ExecuteNonQuery(deleteQuery);
                    if (rows > 0)
                    {
                        // report ??
                    }
                }
            }

            Query linksDeleteQuery = db.CreateQuery("DELETE FROM metaLinks WHERE ToViewId = @ToViewId AND ToRecordGuid NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")");
            linksDeleteQuery.Parameters.Add(new QueryParameter("@ToViewId", DbType.Int32, ContactFormId));
            rows = db.ExecuteNonQuery(linksDeleteQuery);

            if (db.TableExists("metaHistory"))
            {
                Query historyDeleteQuery = db.CreateQuery("DELETE FROM metaHistory WHERE ContactGUID NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")");
                rows = db.ExecuteNonQuery(historyDeleteQuery);
            }

            #endregion // Remove extraneous data

            RecordsExported         = String.Empty;
            IsDataSyncing           = true;
            IsShowingExportProgress = true;

            var doc = new XmlDocument {
                XmlResolver = null
            };

            SendMessageForAwaitAll();

            Task.Factory.StartNew(
                () =>
            {
                doc = CreateCaseSyncFile(includeCases, includeCaseExposures, includeContacts, filters, deIdentifyData, recordProcessingScope);
            },
                System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(
                delegate
            {
                try
                {
                    if (!String.IsNullOrEmpty(doc.InnerText))
                    {
                        string compressedText = Epi.ImportExport.ImportExportHelper.Zip(doc.OuterXml);
                        compressedText        = "[[EPIINFO7_VHF_CASE_SYNC_FILE__0937]]" + compressedText;
                        Epi.Configuration.EncryptStringToFile(compressedText, SyncFilePath, "vQ@6L'<J3?)~5=vQnwh(2ic;>.<=dknF&/TZ4Uu!$78", "", "", 1000);
                    }
                }
                catch (Exception)
                {
                    // do nothing... if the XML is invalid, we should have already alerted the user in a different method
                }
                finally
                {
                    SendMessageForUnAwaitAll();
                }

                TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
                TaskbarProgressValue = 0;
                ProgressValue        = 0;

                IsDataSyncing = false;

                stopwatch.Stop();
                SyncStatus        = String.Empty;
                OverallSyncStatus = "Finished exporting data to sync file. Elapsed time: " + stopwatch.Elapsed.TotalMinutes.ToString("F1") + " minutes.";
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Пример #14
0
        private XmlDocument CreateCaseSyncFile(bool includeCases, bool includeCaseExposures, bool includeContacts, Epi.ImportExport.Filters.RowFilters filters, bool deIdentifyData, Epi.RecordProcessingScope recordProcessingScope)
        {
            TaskbarProgressValue = 0;
            TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal;
            ProgressValue        = 0;

            _increment = 0.25;

            if (includeCaseExposures && includeContacts)
            {
                _increment = 0.25;
            }
            else if (includeCaseExposures && !includeContacts)
            {
                _increment = 0.34;
            }
            else if (!includeCaseExposures && !includeContacts)
            {
                _increment = 0.5;
            }

            IDbDriver database = _project.CollectedData.GetDatabase();

            //#region Repair page tables
            //RemoveExtraneousPageTableRecordsCommand.Execute(null);
            //#endregion // Repair page tables

            #region Case and Lab Data
            //var packager = new ContactTracing.ExportView.XmlSqlDataPackager(CaseForm, "sync") //new Epi.ImportExport.ProjectPackagers.XmlDataPackager(CaseForm, "sync")
            var packager = new Epi.ImportExport.ProjectPackagers.XmlDataPackager(CaseForm, "sync")
            {
                RecordProcessingScope = recordProcessingScope
            };

            packager.StatusChanged  += unpackager_StatusChanged;
            packager.UpdateProgress += unpackager_UpdateProgress;

            if (filters == null)
            {
                filters = new Epi.ImportExport.Filters.RowFilters(database, Epi.ImportExport.Filters.ConditionJoinTypes.And);
            }

            if (includeCases == false)
            {
                // filter out all cases
                var tfc = new Epi.ImportExport.TextRowFilterCondition("[EpiCaseDef] = @EpiCaseDef", "EpiCaseDef", "@EpiCaseDef", "1000")
                {
                    Description = "EpiCaseDef is equal to 1000"
                };
                filters.Add(tfc);
            }

            DateTime dateValue = DateTime.MinValue;

            DateTime today    = DateTime.Now;
            TimeSpan ts       = new TimeSpan(int.Parse(Days), 0, 0, 0);
            DateTime nDaysAgo = today - ts;
            dateValue = nDaysAgo;

            var daysAgoFilter = new Epi.ImportExport.DateRowFilterCondition("LastSaveTime >= @LastSaveTime", "LastSaveTime", "@LastSaveTime", dateValue);
            filters.Add(daysAgoFilter);

            packager.Filters = new Dictionary <string, Epi.ImportExport.Filters.RowFilters>
            {
                { "CaseInformationForm", filters }
            };

            if (deIdentifyData)
            {
                if (!IsCountryUS)
                {
                    packager.FieldsToNull.Add(CaseForm.Name, new List <string> {
                        "Surname", "OtherNames", "PhoneNumber", "PhoneOwner", "HeadHouse", "ContactName1", "ContactName2", "ContactName3", "FuneralName1", "FuneralName2", "HospitalBeforeIllPatient", "TradHealerName", "InterviewerName", "InterviewerPhone", "InterviwerEmail", "ProxyName"
                    });
                    packager.FieldsToNull.Add(LabForm.Name, new List <string> {
                        "SurnameLab", "OtherNameLab"
                    });
                }
                else
                {
                    packager.FieldsToNull.Add(CaseForm.Name, new List <string> {
                        "Surname", "OtherNames", "PhoneNumber", "PhoneOwner", "HeadHouse", "ContactName1", "ContactName2", "ContactName3", "FuneralName1", "FuneralName2", "HospitalBeforeIllPatient", "TradHealerName", "InterviewerName", "InterviewerPhone", "InterviwerEmail", "ProxyName", "DOB", "Email", "AddressRes", "AddressOnset", "ProxyPhone", "ProxyEmail"
                    });
                    packager.FieldsToNull.Add(LabForm.Name, new List <string> {
                        "SurnameLab", "OtherNameLab", "PersonLabSubmit", "PhoneLabSubmit", "EmailLabSubmit"
                    });
                }
            }
            packager.IncludeNullFieldData = false;

            var doc = new XmlDocument {
                XmlResolver = null
            };

            bool failed = false;

            try
            {
                OverallSyncStatus = "Packaging case records...";
                doc = packager.PackageForm();
                TaskbarProgressValue = TaskbarProgressValue + _increment;
                OverallSyncStatus    = "Finished packaging case records";

                if (packager.ExportInfo.RecordsPackaged.ContainsKey(LabForm))
                {
                    RecordsExported = "Exported: " + RecordsExported + packager.ExportInfo.RecordsPackaged[CaseForm].ToString() + " cases, " + packager.ExportInfo.RecordsPackaged[LabForm].ToString() + " lab results";
                }
                else
                {
                    RecordsExported = "Exported: " + RecordsExported + packager.ExportInfo.TotalRecordsPackaged.ToString() + " cases";
                }
            }
            catch (Exception ex)
            {
                if (SyncProblemsDetected != null)
                {
                    SyncProblemsDetected(ex, new EventArgs());
                }
                failed = true;
            }
            finally
            {
                packager.StatusChanged  -= unpackager_StatusChanged;
                packager.UpdateProgress -= unpackager_UpdateProgress;
            }

            if (failed)
            {
                return(doc);
            }
            #endregion // Case and Lab Data

            #region Contact Data
            if (includeContacts)
            {
                OverallSyncStatus = "Packaging contact records...";
                //packager = new ContactTracing.ExportView.XmlSqlDataPackager(ContactForm, "sync") //new Epi.ImportExport.ProjectPackagers.XmlSqlDataPackager(ContactForm, "sync");
                packager = new Epi.ImportExport.ProjectPackagers.XmlDataPackager(ContactForm, "sync")
                {
                    RecordProcessingScope = recordProcessingScope
                };

                packager.StatusChanged  += unpackager_StatusChanged;
                packager.UpdateProgress += unpackager_UpdateProgress;

                packager.RecordProcessingScope = recordProcessingScope;

                filters       = new Epi.ImportExport.Filters.RowFilters(database, Epi.ImportExport.Filters.ConditionJoinTypes.And);
                daysAgoFilter = new Epi.ImportExport.DateRowFilterCondition("LastSaveTime >= @LastSaveTime", "LastSaveTime", "@LastSaveTime", dateValue);
                filters.Add(daysAgoFilter);

                packager.Filters = new Dictionary <string, Epi.ImportExport.Filters.RowFilters>
                {
                    { ContactForm.Name, filters }
                };

                if (deIdentifyData)
                {
                    if (!IsCountryUS)
                    {
                        packager.FieldsToNull.Add(ContactForm.Name, new List <string> {
                            "ContactSurname", "ContactOtherNames", "ContactHeadHouse", "ContactPhone", "LC1"
                        });
                    }
                    else
                    {
                        packager.FieldsToNull.Add(ContactForm.Name, new List <string> {
                            "ContactSurname", "ContactOtherNames", "ContactHeadHouse", "ContactPhone", "LC1", "ContactDOB", "ContactAddress", "ContactEmail"
                        });
                    }
                }

                try
                {
                    XmlDocument contactDoc = packager.PackageForm();
                    RecordsExported = RecordsExported + ", " + packager.ExportInfo.TotalRecordsPackaged.ToString() + " contacts";
                    XmlNodeList xnList = contactDoc.SelectNodes("/DataPackage/Form");
                    if (IsCountryUS)
                    {
                        foreach (XmlNode node in contactDoc.GetElementsByTagName("FieldInfo"))
                        {
                            if (node.Attributes[0].Value == "AdminOverride")
                            {
                                node.ParentNode.RemoveChild(node);
                                break;
                            }
                        }
                    }

                    if (xnList.Count == 1)
                    {
                        XmlNode nodeToCopy = doc.ImportNode(contactDoc.SelectSingleNode("/DataPackage/Form"), true); // note: target
                        XmlNode parentNode = doc.SelectSingleNode("/DataPackage");
                        parentNode.AppendChild(nodeToCopy);

                        //doc.Save(@"C:\Temp\ContactTest.xml");
                    }
                }
                catch (Exception ex)
                {
                    //if (SyncProblemsDetected != null)
                    //{
                    //    SyncProblemsDetected(ex, new EventArgs());
                    //}
                    // TODO: Re-work this
                }
                finally
                {
                    packager.StatusChanged  -= unpackager_StatusChanged;
                    packager.UpdateProgress -= unpackager_UpdateProgress;
                }
            }
            TaskbarProgressValue = TaskbarProgressValue + _increment;
            OverallSyncStatus    = "Finished packaging contact records";
            #endregion // Contact Data

            #region Link Data

            if (includeCaseExposures || includeContacts)
            {
                OverallSyncStatus = "Packaging relationship records...";
                #region metaLinks table
                XmlElement links = doc.CreateElement("Links");

                Query     selectQuery = database.CreateQuery("SELECT * FROM [metaLinks] ORDER BY [LastContactDate] DESC");
                DataTable linksTable  = database.Select(selectQuery);

                foreach (DataRow row in linksTable.Rows)
                {
                    XmlElement link = doc.CreateElement("Link");

                    var toViewId   = (int)row["ToViewId"];
                    var fromViewId = (int)row["FromViewId"];

                    if (includeCaseExposures && toViewId == CaseFormId && fromViewId == CaseFormId)
                    {
                        // we have a case-to-case link, add it

                        foreach (DataColumn dc in linksTable.Columns)
                        {
                            XmlElement element = doc.CreateElement(dc.ColumnName);
                            if (row[dc] != DBNull.Value)
                            {
                                if (row[dc] is DateTime || dc.ColumnName.Equals("LastContactDate", StringComparison.OrdinalIgnoreCase))
                                {
                                    var dt = (DateTime)row[dc];
                                    element.InnerText = dt.Ticks.ToString();
                                }
                                else
                                {
                                    element.InnerText = row[dc].ToString();
                                }
                            }
                            else
                            {
                                element.InnerText = String.Empty;
                            }

                            //if (!String.IsNullOrEmpty(element.InnerText) || !element.Name.StartsWith("Day", StringComparison.OrdinalIgnoreCase))
                            //{
                            link.AppendChild(element);
                            //}
                        }
                    }

                    if (includeContacts && toViewId == ContactFormId && fromViewId == CaseFormId)
                    {
                        // we have a case-to-contact link, add it
                        foreach (DataColumn dc in linksTable.Columns)
                        {
                            XmlElement element = doc.CreateElement(dc.ColumnName);
                            if (row[dc] != DBNull.Value)
                            {
                                if (row[dc] is DateTime || dc.ColumnName.Equals("LastContactDate", StringComparison.OrdinalIgnoreCase))
                                {
                                    var dt = (DateTime)row[dc];
                                    element.InnerText = dt.Ticks.ToString();
                                }
                                else
                                {
                                    element.InnerText = row[dc].ToString();
                                }
                            }
                            else
                            {
                                element.InnerText = String.Empty;
                            }
                            //if (!String.IsNullOrEmpty(element.InnerText) || !element.Name.StartsWith("Day", StringComparison.OrdinalIgnoreCase))
                            //{
                            link.AppendChild(element);
                            //}
                        }
                    }

                    links.AppendChild(link);
                }

                doc.ChildNodes[0].AppendChild(links);
                #endregion // metaLinks table
                TaskbarProgressValue = TaskbarProgressValue + _increment;
                RecordsExported      = RecordsExported + ", " + linksTable.Rows.Count.ToString() + " relationships";

                if (includeContacts)
                {
                    if (database.TableExists("metaHistory"))
                    {
                        OverallSyncStatus = "Packaging daily follow-up records...";
                        #region metaHistory table
                        XmlElement followUps = doc.CreateElement("ContactFollowUps");

                        selectQuery = database.CreateQuery("SELECT * FROM [metaHistory] ORDER BY [ContactGUID] DESC, [FollowUpDate] DESC");
                        DataTable followUpsTable = database.Select(selectQuery);

                        foreach (DataRow row in followUpsTable.Rows)
                        {
                            XmlElement followUp = doc.CreateElement("ContactFollowUp");

                            XmlElement guid = doc.CreateElement("ContactGUID");
                            guid.InnerText = row["ContactGUID"].ToString();
                            followUp.AppendChild(guid);

                            CultureInfo format = CultureInfo.InvariantCulture;

                            XmlElement fuDate = doc.CreateElement("FollowUpDate");
                            fuDate.InnerText = Convert.ToDateTime(row["FollowUpDate"]).ToString(format.DateTimeFormat.ShortDatePattern);
                            followUp.AppendChild(fuDate);

                            XmlElement statusOnDate = doc.CreateElement("StatusOnDate");
                            statusOnDate.InnerText = row["StatusOnDate"].ToString();
                            followUp.AppendChild(statusOnDate);

                            XmlElement note = doc.CreateElement("Note");
                            note.InnerText = row["Note"].ToString();
                            followUp.AppendChild(note);

                            if (row.Table.Columns.Contains("Temp1"))
                            {
                                XmlElement temp1 = doc.CreateElement("Temp1");
                                if (row["Temp1"] != DBNull.Value)
                                {
                                    temp1.InnerText = Convert.ToDouble(row["Temp1"]).ToString(System.Globalization.CultureInfo.InvariantCulture);
                                }
                                followUp.AppendChild(temp1);

                                XmlElement temp2 = doc.CreateElement("Temp2");
                                if (row["Temp2"] != DBNull.Value)
                                {
                                    temp2.InnerText = Convert.ToDouble(row["Temp2"]).ToString(System.Globalization.CultureInfo.InvariantCulture);
                                }
                                followUp.AppendChild(temp2);
                            }

                            followUps.AppendChild(followUp);
                        }
                        #endregion // metaHistory table

                        doc.ChildNodes[0].AppendChild(followUps);
                        TaskbarProgressValue = TaskbarProgressValue + _increment;
                        RecordsExported      = RecordsExported + ", " + followUpsTable.Rows.Count.ToString() + " follow-ups";
                    }
                }
            }
            #endregion // Link Data

            return(doc);
        }