public void getData(string filename, string filterstring = null)
        {
            string configFilePath = "..\\..\\..\\Build\\Debug\\Configuration\\EpiInfo.Config.xml";

            Epi.DataSets.Config configDataSet = new Epi.DataSets.Config();
            configDataSet.ReadXml(configFilePath);
            Epi.Configuration.Load(configFilePath);
            System.Data.Common.DbConnectionStringBuilder dbCnnStringBuilder = new System.Data.Common.DbConnectionStringBuilder();
            string           provider  = "Epi.Data.Office.CsvFileFactory, Epi.Data.Office";
            IDbDriverFactory dbFactory = null;

            dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(provider);
            IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

            db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\Data;Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
            object selectedDataSource = db;

            IDbDriver dbDriver = (IDbDriver)selectedDataSource;

            DashboardHelper = new DashboardHelper(filename + "#csv", dbDriver);
            IGadgetParameters inputs = new GadgetParameters();

            DashboardHelper.UserVarsNeedUpdating = true;
            string fs = null;

            if (!String.IsNullOrEmpty(filterstring))
            {
                fs = "select * from " + filename + "#csv where " + filterstring;
            }
            PopulateDataSet(inputs, fs);
        }
示例#2
0
        private void LoadTablesFromDatabase(RecentDataSourceInfo info)
        {
            string connectionString = Configuration.Decrypt(info.ConnStr);
            string name             = info.Name;
            string provider         = info.Provider;

            mruSelectedDatabaseName = name;
            selectedDataProvider    = provider;

            IDbDriverFactory dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(provider);

            if (dbFactory.ArePrerequisitesMet())
            {
                DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
                db.ConnectionString = connectionString;

                try
                {
                    db.TestConnection();

                    cmbDatabaseType.Text = info.ProviderDesc;

                    LoadTablesFromDatabase(db);
                }
                catch (Exception ex)
                {
                    Epi.Windows.MsgBox.ShowException(ex);
                    return;
                }

                this.selectedDataSource = db;
            }
        }
示例#3
0
        private IDbDriver GetDbDriver(string pKey)
        {
            IDbDriverFactory dbFactory = null;

            switch (pKey)
            {
            case "Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer":
                dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.SqlDriver);
                break;

            case "Epi.Data.MySQL.MySQLDBFactory, Epi.Data.MySQL":
                dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.MySQLDriver);

                break;

            case "Epi.Data.Office.AccessDBFactory, Epi.Data.Office":
                dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
                break;

            //case "":
            //    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.ExcelDriver);
            //  break;
            default:
                dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
                break;
            }


            DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
            IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

            db.ConnectionString = dbCnnStringBuilder.ToString();

            return(db);
        }
        /// <summary>
        /// Constructor for the class for Epi 2000 projects
        /// </summary>
        /// <param name="proj">Project the metadata belongs to</param>
        public MetadataDbProvider(Project proj)
        {
            IDbDriverFactory             dbFactory     = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
            OleDbConnectionStringBuilder cnnStrBuilder = new OleDbConnectionStringBuilder();

            cnnStrBuilder.DataSource = proj.FilePath;
            this.db = dbFactory.CreateDatabaseObject(cnnStrBuilder);
        }
        private void cmbRecentSources_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //this.RefreshForm();
                if (cmbRecentSources.SelectedItem != null && !string.IsNullOrEmpty(cmbRecentSources.SelectedItem.ToString()))
                {
                    string connectionString = Configuration.Decrypt(((ComboBoxItem)cmbRecentSources.SelectedItem).Value.ToString());
                    string name             = ((ComboBoxItem)cmbRecentSources.SelectedItem).Text.ToString();
                    string provider         = ((ComboBoxItem)cmbRecentSources.SelectedItem).Key.ToString();

                    mruSelectedDatabaseName = name;
                    selectedDataProvider    = provider;

                    if (name.ToLowerInvariant().EndsWith(".prj"))
                    {
                        Project project = new Project(connectionString);
                        this.selectedDataSource = project;
                        this.selectedProject    = project;
                    }
                    else
                    {
                        IDbDriverFactory dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(provider);
                        if (dbFactory.ArePrerequisitesMet())
                        {
                            DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                            IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
                            db.ConnectionString     = connectionString;
                            this.selectedDataSource = db;
                        }
                    }
                }
                else if (cmbRecentSources.SelectedItem != null && string.IsNullOrEmpty(cmbRecentSources.SelectedItem.ToString()))
                {
                    mruSelectedDatabaseName = string.Empty;
                }

                RefreshForm();
            }
            catch (DirectoryNotFoundException ex)
            {
                MsgBox.ShowException(ex);
                mruSelectedDatabaseName        = string.Empty;
                cmbRecentSources.SelectedIndex = -1;
            }
            catch (FileNotFoundException ex)
            {
                MsgBox.ShowException(ex);
                mruSelectedDatabaseName        = string.Empty;
                cmbRecentSources.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                MsgBox.ShowException(ex);
                mruSelectedDatabaseName        = string.Empty;
                cmbRecentSources.SelectedIndex = -1;
            }
        }
示例#6
0
        /// <summary>
        /// Constructor for CollectedDataProvider
        /// </summary>
        /// <param name="proj"></param>
        public CollectedDataProvider(Project proj)
        {
            IDbDriverFactory             dbFactory     = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
            OleDbConnectionStringBuilder cnnStrBuilder = new OleDbConnectionStringBuilder();

            cnnStrBuilder.DataSource = proj.FilePath;
            this.db = dbFactory.CreateDatabaseObject(cnnStrBuilder);

            //this.db = dbFactory.CreateDatabaseObjectByConfiguredName(proj.FilePath);
            //db = DatabaseFactoryCreator.CreateDatabaseInstanceByFileExtension(proj.FilePath);
        }
        /// <summary>
        /// Populate internal translation table using Epi 3.x db
        /// </summary>
        /// <param name="legacyLanguageDatabasePath"></param>
        public void ReadDatabase(string legacyLanguageDatabasePath)
        {
            //IDbDriver db = DatabaseFactory.CreateDatabaseInstanceByFileExtension(legacyLanguageDatabasePath);
            IDbDriverFactory             dbFactory          = DbDriverFactoryCreator.GetDbDriverFactory(Epi.Configuration.AccessDriver);
            OleDbConnectionStringBuilder dbCnnStringBuilder = new OleDbConnectionStringBuilder();

            dbCnnStringBuilder.FileName = legacyLanguageDatabasePath;
            IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

            List <string> tableNames = db.GetTableNames();

            foreach (string tableName in tableNames)
            {
                List <string> columnNames = db.GetTableColumnNames(tableName);
                if (columnNames.Contains("English") && columnNames.Count == 2)
                {
                    DataTable span = db.Select(db.CreateQuery("select * from " + tableName));


                    int sourceColumnOrdinal, translationColumnOrdinal;

                    if (string.Compare(span.Columns[0].ColumnName, "English", true) == 0)
                    {
                        sourceColumnOrdinal      = 0;
                        translationColumnOrdinal = 1;
                    }
                    else
                    {
                        sourceColumnOrdinal      = 1;
                        translationColumnOrdinal = 0;
                    }

                    foreach (DataRow row in span.Rows)
                    {
                        AddTranslationTableEntry(sourceColumnOrdinal, translationColumnOrdinal, row);
                    }
                }
            }
        }
示例#8
0
        private void OpenSelectDataSourceDialog()
        {
            ComboBoxItem selectedPlugIn = cmbDataFormats.SelectedItem as ComboBoxItem;

            if (selectedPlugIn == null)
            {
                throw new GeneralException("No data source plug-in is selected in combo box.");
            }

            if (selectedPlugIn.Key == null) // default project
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title  = SharedStrings.SELECT_DATA_SOURCE;
                openFileDialog.Filter = "Epi Info " + SharedStrings.PROJECT_FILE + " (*.prj)|*.prj";

                openFileDialog.FilterIndex = 1;
                openFileDialog.Multiselect = false;

                DialogResult result = openFileDialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName.Trim();
                    if (System.IO.File.Exists(filePath))
                    {
                        try
                        {
                            selectedDataSource = new Project(filePath);
                            txtDataSource.Text = filePath;
                            LoadTables();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Could not load project: \n\n" + ex.Message);
                            return;
                        }
                    }
                }
            }
            else
            {
                IDbDriverFactory dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(selectedPlugIn.Key);
                if (dbFactory.ArePrerequisitesMet())
                {
                    DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                    IDbDriver            db     = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
                    IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
                    DialogResult         result = ((Form)dialog).ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        bool success = false;

                        db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();
                        txtDataSource.Text  = db.ConnectionDescription;

                        try
                        {
                            success = db.TestConnection();
                        }
                        catch
                        {
                            success = false;
                            MessageBox.Show("Could not connect to selected data source.");
                        }

                        if (success)
                        {
                            this.selectedDataSource = db;
                        }
                        else
                        {
                            this.selectedDataSource = null;
                        }
                    }
                    else
                    {
                        this.selectedDataSource = null;
                    }
                }
                LoadTables();
            }
        }
示例#9
0
        /// <summary>
        /// Constructor initialization.
        /// </summary>
        /// <param name="MetaDbInfo">Database driver information.</param>
        /// <param name="driver">Database driver name.</param>
        /// <param name="createDatabase">Create database flag.</param>
        public void Initialize(DbDriverInfo MetaDbInfo, string driver, bool createDatabase)
        {
            dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(driver);
            if (createDatabase)
            {
                this.CreateDatabase(MetaDbInfo); //\\ + Path.DirectorySeparatorChar + DbDriverInfo.PreferredDatabaseName);
                db = dbFactory.CreateDatabaseObject(MetaDbInfo.DBCnnStringBuilder);
                CreateMetadataTables();
            }
            else
            {
                db = dbFactory.CreateDatabaseObject(MetaDbInfo.DBCnnStringBuilder);

            }
            db.TestConnection();
        }
        /// <summary>
        /// Creates database 
        /// </summary>
        /// <param name="collectDbInfo">Database information.</param>
        /// <param name="driver">Database driver.</param>
        /// <param name="createDatabase">Create database.</param>
        public void Initialize(DbDriverInfo collectDbInfo, string driver, bool createDatabase)
        {
            dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(driver);
            dbDriver = dbFactory.CreateDatabaseObject(collectDbInfo.DBCnnStringBuilder);
            dbDriverInitialRead = dbFactory.CreateDatabaseObject(collectDbInfo.DBCnnStringBuilder);

            if (createDatabase)
            {
                this.CreateDatabase(collectDbInfo);
            }
        }
示例#11
0
        private void OpenSelectDataSourceDialog()
        {
            ComboBoxItem selectedPlugIn = cmbDataSourcePlugIns.SelectedItem as ComboBoxItem;

            if (selectedPlugIn == null)
            {
                throw new GeneralException("No data source plug-in is selected in combo box.");
            }

            if (selectedPlugIn.Key == null) // default project
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title  = SharedStrings.SELECT_DATA_SOURCE;
                openFileDialog.Filter = "Epi Info " + SharedStrings.PROJECT_FILE + " (*.prj)|*.prj";

                openFileDialog.FilterIndex = 1;
                openFileDialog.Multiselect = false;

                DialogResult result = openFileDialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName.Trim();
                    if (System.IO.File.Exists(filePath))
                    {
                        try
                        {
                            IProjectManager manager = Module.GetService(typeof(IProjectManager)) as IProjectManager;
                            if (manager == null)
                            {
                                throw new GeneralException("Project manager is not registered.");
                            }
                            selectedDataSource = manager.OpenProject(filePath);
                            this.SelectedTable = null;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Could not load project: \n\n" + ex.Message);
                            return;
                        }
                    }
                }
            }
            else
            {
                IDbDriverFactory dbFactory = null;
                switch (selectedPlugIn.Key)
                {
                case Configuration.SqlDriver:    //"Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.SqlDriver);
                    break;

                case Configuration.MySQLDriver:     //"Epi.Data.MySQL.MySQLDBFactory, Epi.Data.MySQL":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.MySQLDriver);
                    break;

                case Configuration.PostgreSQLDriver:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.PostgreSQLDriver);
                    break;

                case Configuration.ExcelDriver:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.ExcelDriver);
                    break;

                case Configuration.Excel2007Driver:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Excel2007Driver);
                    break;

                case Configuration.AccessDriver:     //"Epi.Data.Office.AccessDBFactory, Epi.Data.Office":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
                    break;

                case Configuration.Access2007Driver:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Access2007Driver);
                    break;

                case Configuration.CsvDriver:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.CsvDriver);
                    break;

                case Configuration.WebDriver:     //"Epi.Data.WebDriver":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.WebDriver);
                    break;

                default:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
                    break;
                }


                DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
                //IDbDriver db = DatabaseFactoryCreator.CreateDatabaseInstance(selectedPlugIn.Key);
                //IConnectionStringGui dialog = db.GetConnectionStringGuiForExistingDb();
                ////IConnectionStringGui dialog = this.selectedProject.Metadata.DBFactory.GetConnectionStringGuiForExistingDb();
                IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
                DialogResult         result = ((Form)dialog).ShowDialog();
                if (result == DialogResult.OK)
                {
                    bool success = false;

                    db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();
                    txtDataSource.Text  = db.ConnectionDescription;

                    try
                    {
                        success = db.TestConnection();
                    }
                    catch
                    {
                        success = false;
                        MessageBox.Show("Could not connect to selected data source.");
                    }

                    if (success)
                    {
                        this.selectedDataSource = db;
                        this.SelectedTable      = null;
                    }
                    else
                    {
                        this.selectedDataSource = null;
                        this.SelectedTable      = null;
                    }
                }
                else
                {
                    this.selectedDataSource = null;
                    this.SelectedTable      = null;
                }
            }

            RefreshForm();
        }
        private void SetupOutputDataSource()
        {
            try
            {
                ComboBoxItem     selectedPlugIn = cmbDataFormats.SelectedItem as ComboBoxItem;
                IDbDriverFactory dbFactory      = null;

                string plugin = string.Empty;
                foreach (Epi.DataSets.Config.DataDriverRow row in dashboardHelper.Config.DataDrivers)
                {
                    string content = selectedPlugIn.Content.ToString();
                    if (content.Equals(row.DisplayName))
                    {
                        plugin = row.Type;
                    }
                }

                selectedDataProvider = plugin;
                bool isFlatFile = false;
                dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(plugin);
                if (dbFactory.ArePrerequisitesMet())
                {
                    DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                    db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

                    IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
                    dialog.ShouldIgnoreNonExistance = true;

                    System.Windows.Forms.DialogResult result = ((System.Windows.Forms.Form)dialog).ShowDialog();

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        //this.savedConnectionStringDescription = dialog.ConnectionStringDescription;
                        bool success = false;
                        db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();
                        DbDriverInfo dbInfo = new DbDriverInfo();
                        dbInfo.DBCnnStringBuilder = dbFactory.RequestNewConnection(db.DataSource);

                        if (db.ConnectionDescription.ToLower().Contains("csv file:"))
                        {
                            isFlatFile = true;
                        }

                        if (!isFlatFile)
                        {
                            if (!db.CheckDatabaseExistance(db.ConnectionString, "", true))
                            {
                                dbFactory.CreatePhysicalDatabase(dbInfo);
                            }

                            try
                            {
                                success = db.TestConnection();
                            }
                            catch
                            {
                                success = false;
                                MessageBox.Show("Could not connect to selected data source.");
                            }
                        }
                        else
                        {
                            success = true;
                        }

                        if (success)
                        {
                            this.SelectedDataSource       = db;
                            controlNeedsRefresh           = true;
                            txtConnectionInformation.Text = db.ConnectionString;
                        }
                        else
                        {
                            this.SelectedDataSource = null;
                        }
                    }
                    else
                    {
                        this.SelectedDataSource = null;
                    }
                }
                else
                {
                    MessageBox.Show(dbFactory.PrerequisiteMessage, "Prerequisites not found");
                }

                if (selectedDataSource is IDbDriver)
                {
                    db = selectedDataSource as IDbDriver;
                    //this.txtDataSource.Text = db.ConnectionString;

                    if (!isFlatFile)
                    {
                        System.Collections.Generic.List <string> tableNames = db.GetTableNames();
                        foreach (string tableName in tableNames)
                        {
                            ComboBoxItem newItem = new ComboBoxItem();//tableName, tableName, tableName);
                            newItem.Content = tableName;
                            cmbDestinationTable.Items.Add(tableName);
                            //this.cmbDataTable.Items.Add(newItem);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
            }
            finally
            {
                messagePanel.Visibility = System.Windows.Visibility.Hidden;
            }
        }
示例#13
0
        private void OpenSelectDataSourceDialog()
        {
            bool formNeedsRefresh = false;

            ComboBoxItem selectedPlugIn = cmbDataSourcePlugIns.SelectedItem as ComboBoxItem;

            if (selectedPlugIn == null)
            {
                throw new GeneralException("No data source plug-in is selected in combo box.");
            }

            if (selectedPlugIn.Key == null)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title            = SharedStrings.SELECT_DATA_SOURCE;
                openFileDialog.Filter           = "Epi Info " + SharedStrings.PROJECT_FILE + " (*.prj)|*.prj";
                openFileDialog.InitialDirectory = config.Directories.Project;
                openFileDialog.FilterIndex      = 1;
                openFileDialog.Multiselect      = false;

                DialogResult result = openFileDialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName.Trim();
                    if (System.IO.File.Exists(filePath))
                    {
                        try
                        {
                            selectedDataSource = new Project(filePath);
                            formNeedsRefresh   = true;
                        }
                        catch (System.Security.Cryptography.CryptographicException ex)
                        {
                            MsgBox.ShowError(string.Format(SharedStrings.ERROR_CRYPTO_KEYS, ex.Message));
                            return;
                        }
                        catch (Exception ex)
                        {
                            MsgBox.ShowError(SharedStrings.CANNOT_OPEN_PROJECT_FILE + "\n\nError details: " + ex.Message);
                            return;
                        }
                    }
                }
            }
            else
            {
                IDbDriverFactory dbFactory = null;

                selectedDataProvider = selectedPlugIn.Key;

                dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(selectedPlugIn.Key);
                if (dbFactory.ArePrerequisitesMet())
                {
                    DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                    IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

                    IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();

                    if (!string.IsNullOrEmpty(savedConnectionStringDescription))
                    {
                        int splitIndex = savedConnectionStringDescription.IndexOf("::");
                        if (splitIndex > -1)
                        {
                            string serverName   = savedConnectionStringDescription.Substring(0, splitIndex);
                            string databaseName = savedConnectionStringDescription.Substring(splitIndex + 2, savedConnectionStringDescription.Length - splitIndex - 2);
                            dialog.SetDatabaseName(databaseName);
                            dialog.SetServerName(serverName);
                        }
                    }

                    DialogResult result = ((Form)dialog).ShowDialog();
                    //  dialog.UseManagerService
                    if (result == DialogResult.OK && dialog.DbConnectionStringBuilder != null)
                    {
                        this.savedConnectionStringDescription = dialog.ConnectionStringDescription;
                        bool success = false;
                        db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();

                        try
                        {
                            success = db.TestConnection();
                        }
                        catch
                        {
                            success = false;
                            MessageBox.Show("Could not connect to selected data source.");
                        }

                        if (success)
                        {
                            this.selectedDataSource = db;
                            formNeedsRefresh        = true;
                        }
                        else
                        {
                            this.selectedDataSource = null;
                        }
                    }
                    else
                    {
                        if (selectedPlugIn.Text == "Epi Info Web & Cloud Services")
                        {
                        }

                        else
                        {
                            this.selectedDataSource = null;
                        }
                    }
                }
                else
                {
                    MessageBox.Show(dbFactory.PrerequisiteMessage, "Prerequisites not found");
                }
            }
            if (formNeedsRefresh)
            {
                RefreshForm();
            }
        }
示例#14
0
        private void btnGetFile_Click(object sender, System.EventArgs e)
        {
            ComboBoxItem selectedPlugIn = cmbOutputFormat.SelectedItem as ComboBoxItem;

            if (selectedPlugIn == null)
            {
                throw new GeneralException("No data source plug-in is selected in combo box.");
            }

            if (selectedPlugIn.Key == null) // default project
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (cmbOutputFormat.Text == "Text" || cmbOutputFormat.Text.ToUpperInvariant() == "FLAT ASCII FILE")
                {
                    dlg.Filter = "Text Files (*.txt) |*.txt";
                }
                else
                {
                    dlg.Filter = "Database Files (*.mdb) |*.mdb";
                }
                dlg.CheckFileExists = false;
                dlg.CheckPathExists = false;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (cmbOutputFormat.Text.ToUpperInvariant() == "TEXT" || cmbOutputFormat.Text.ToUpperInvariant() == "FLAT ASCII FILE")
                    {
                        if (!dlg.FileName.EndsWith(".txt") && dlg.FileName.EndsWith(".csv"))
                        {
                            txtFileName.Text = dlg.FileName + ".csv";
                        }
                        else
                        {
                            txtFileName.Text = dlg.FileName;
                        }
                    }
                    else
                    {
                        txtFileName.Text = dlg.FileName;
                    }
                }
            }
            else
            {
                IDbDriverFactory dbFactory = null;
                switch (selectedPlugIn.Key)
                {
                case "Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.SqlDriver);
                    break;

                case "Epi.Data.MySQL.MySQLDBFactory, Epi.Data.MySQL":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.MySQLDriver);

                    break;

                case "Epi.Data.Office.AccessDBFactory, Epi.Data.Office":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
                    break;

                case "Epi.Data.Office.ExcelWBFactory, Epi.Data.Office":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.ExcelDriver);
                    break;

                case "Epi.Data.Office.Access2007DBFactory, Epi.Data.Office":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Access2007Driver);
                    break;

                case "Epi.Data.Office.Excel2007WBFactory, Epi.Data.Office":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Excel2007Driver);
                    break;

                case "Epi.Data.Office.CsvFileFactory, Epi.Data.Office":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.CsvDriver);
                    break;

                case "Epi.Data.PostgreSQL.PostgreSQLDBFactory, Epi.Data.PostgreSQL":
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.PostgreSQLDriver);
                    break;

                default:
                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
                    break;
                }

                DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                IDbDriver            db     = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
                IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
                dialog.ShouldIgnoreNonExistance = true;
                DialogResult result = ((Form)dialog).ShowDialog();
                if (result == DialogResult.OK)
                {
                    bool success = false;

                    db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();
                    txtFileName.Text    = db.ConnectionString;

                    try
                    {
                        success = db.TestConnection();
                    }
                    catch
                    {
                        success = false;
                        //MessageBox.Show("Could not connect to selected data source.");
                    }

                    if (success)
                    {
                        this.selectedDataSource = db;
                    }
                    else
                    {
                        this.selectedDataSource = null;
                    }
                }
                else
                {
                    this.selectedDataSource = null;
                }
            }

            if (selectedDataSource is IDbDriver)
            {
                IDbDriver db = selectedDataSource as IDbDriver;
                //this.txtDataSource.Text = db.ConnectionString;

                System.Collections.Generic.List <string> tableNames = db.GetTableNames();

                foreach (string tableName in tableNames)
                {
                    ComboBoxItem newItem = null;
                    if (tableName.EndsWith("$") & (selectedPlugIn.Key == "Epi.Data.Office.ExcelWBFactory, Epi.Data.Office") ||
                        (selectedPlugIn.Key == "Epi.Data.Office.Excel2007WBFactory, Epi.Data.Office"))
                    {
                        newItem = new ComboBoxItem(tableName.Remove(tableName.Length - 1), tableName.Remove(tableName.Length - 1), tableName);
                    }
                    else
                    {
                        newItem = new ComboBoxItem(tableName, tableName, tableName);
                    }
                    this.cmbDataTable.Items.Add(newItem);
                }
            }
            else if (selectedDataSource is Project)
            {
                Project project = selectedDataSource as Project;
                //txtDataSource.Text = (selectedDataSource == selectedProject) ? SharedStrings.CURRENT_PROJECT : project.FullName;

                foreach (string s in project.GetViewNames())
                {
                    ComboBoxItem newItem = new ComboBoxItem(s, s, s);
                    this.cmbDataTable.Items.Add(newItem);
                }
            }
        }
示例#15
0
        /// <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.ToUpper());
                        }
                    }
                    else
                    {
                        TempVariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpper());
                    }
                }
            }
            else
            {
                for (int i = 0; i < this.IdentifierList.Length; i++)
                {
                    TempVariableList.Add(this.IdentifierList[i].ToUpper());
                }
            }

            if (isExceptionList)
            {
                for (int i = CurrentDataTable.Columns.Count - 1; i > -1; i--)
                {
                    if (TempVariableList.Contains(CurrentDataTable.Columns[i].ColumnName.ToUpper()))
                    {
                        //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.ToUpper());
                                }
                            }
                        }
                        else
                        {
                            VariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpper());
                        }
                    }
                }
            }
            else // is NOT an isExceptionList
            {
                for (int i = 0; i < CurrentDataTable.Columns.Count; i++)
                {
                    if (TempVariableList.Contains(CurrentDataTable.Columns[i].ColumnName.ToUpper()))
                    {
                        VariableList.Add(CurrentDataTable.Columns[i].ColumnName.ToUpper());
                    }
                    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);
                }

                if (this.WriteMode.Equals("REPLACE", StringComparison.OrdinalIgnoreCase) && DBReadExecute.CheckDatabaseTableExistance(FilePath, TableName, this.isConnectionString))
                {
                    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.ToUpper()))
                        {
                            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.ToUpper() == columnName.ToUpper())
                            {
                                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.ToUpper()))
                            {
                                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.ToUpper()))
                            {
                                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);

                    StringBuilder ColumnSQL = new StringBuilder();

                    OutputDriver.IsBulkOperation = true;
                    foreach (string column in VariableList)
                    {
                        string columnName = String.Empty;
                        if (!column.Contains(".") && !OutputDriver.ColumnExists(TableName, column))
                        {
                            //add column
                            columnName = column;
                            Query qr = OutputDriver.CreateQuery("alter table [" + TableName + "] add [" + columnName + "] " + DBReadExecute.SQLGetType(CurrentDataTable.Columns[column]));
                            OutputDriver.ExecuteNonQuery(qr);
                        }

                        ColumnSQL.Append(" [");
                        ColumnSQL.Append(column);
                        ColumnSQL.Append("],");
                    }
                    OutputDriver.IsBulkOperation = false;

                    ColumnSQL.Length = ColumnSQL.Length - 1;

                    //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.ToUpper()))
                        {
                            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.";

                }
            }
            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;
        }
        /// <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);
        }
示例#17
0
        /// <summary>
        /// Creates a project file and project object for a given database.
        /// </summary>
        /// <param name="connectionString">The database file name or connection string.</param>
        /// <param name="createPRJFile">Whether or not to create the PRJ file on disk.</param>
        /// <param name="prjFileName">The name of the desired PRJ file</param>
        /// <param name="prjFileLocation">The directory to the desired PRJ file</param>
        /// <returns>An Epi Info project object</returns>
        public static Project CreateProjectFileFromDatabase(string connectionString, bool createPRJFile, string prjFileLocation = "", string prjFileName = "")
        {
            if (IsDatabaseEpiProject(connectionString, true) == false)
            {
                return(null);
            }

            Project project = new Project();

            DbDriverInfo     collectedDataDBInfo = new DbDriverInfo();
            IDbDriverFactory collectedDBFactory  = DbDriverFactoryCreator.GetDbDriverFactory("Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer");
            string           GUID = System.Guid.NewGuid().ToString();

            //collectedDataDBInfo.DBCnnStringBuilder = collectedDBFactory.RequestNewConnection(connectionInfo);

            string[] pieces = connectionString.Split(';');

            foreach (string piece in pieces)
            {
                if (!piece.ToLowerInvariant().StartsWith("password"))
                {
                    string[] parts = piece.Split('=');
                    collectedDataDBInfo.DBCnnStringBuilder[parts[0]] = parts[1];
                }
                else
                {
                    string[] parts    = piece.Split('=');
                    int      indexOf  = piece.IndexOf("=");
                    string   password = piece.Substring(indexOf + 1);
                    password = password.TrimStart('\"').TrimEnd('\"');;
                    collectedDataDBInfo.DBCnnStringBuilder[parts[0]] = password;
                }
            }

            IDbDriver driver = collectedDBFactory.CreateDatabaseObject(collectedDataDBInfo.DBCnnStringBuilder);

            project.CollectedData.Initialize(collectedDataDBInfo, "Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer", false);

            project.Name     = prjFileName;     //fi.Name.Substring(0, fi.Name.Length - 4);
            project.Location = prjFileLocation; //directory;

            project.Id          = project.GetProjectId();
            project.Description = string.Empty;

            project.CollectedDataDbInfo           = collectedDataDBInfo;
            project.CollectedDataDriver           = "Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer";
            project.CollectedDataConnectionString = connectionString;

            project.MetadataSource = MetadataSource.SameDb;
            project.Metadata.AttachDbDriver(project.CollectedData.GetDbDriver());

            if (createPRJFile)
            {
                try
                {
                    project.Save();
                }
                catch (UnauthorizedAccessException ex)
                {
                    return(null);
                }
            }

            return(project);
        }
示例#18
0
        /// <summary>
        /// GetDataTable
        /// </summary>
        /// <param name="pFileString">File String</param>
        /// <param name="pSQL">SQL Statement</param>
        /// <returns>DataTable of results</returns>
        public static DataTable GetDataTable(string pFileString, string pSQL)
        {
            System.Data.DataTable result = new System.Data.DataTable();

            string connString = ParseConnectionString(pFileString);

            if (DataSource != null)
            {
                IDbDriver driver = DataSource.CreateDatabaseObject(new System.Data.Common.DbConnectionStringBuilder());
                driver.ConnectionString = connString;
                Query query = driver.CreateQuery(pSQL);
                driver.Select(query, result);
            }

            return(result);
        }
示例#19
0
        private void btnConnectionBrowse_Click(object sender, RoutedEventArgs e)
        {
            if (cmbDatabaseType.SelectedIndex >= 0)
            {
                ComboBoxItem item = cmbDatabaseType.SelectedItem as ComboBoxItem;
                switch (item.Text)
                {
                case "Epi Info 7 Project":
                    System.Windows.Forms.OpenFileDialog projectDialog = new System.Windows.Forms.OpenFileDialog();
                    projectDialog.InitialDirectory = config.Directories.Project;
                    projectDialog.Filter           = "Epi Info 7 Project File|*.prj";

                    System.Windows.Forms.DialogResult projectDialogResult = projectDialog.ShowDialog();

                    if (projectDialogResult == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            Project project = new Project(projectDialog.FileName);
                            LoadFormsFromProject(project);
                        }
                        catch (System.Security.Cryptography.CryptographicException ex)
                        {
                            Epi.Windows.MsgBox.ShowError(string.Format(SharedStrings.ERROR_CRYPTO_KEYS, ex));
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                    break;

                default:
                    IDbDriverFactory dbFactory = null;

                    selectedDataProvider = item.Key;

                    dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(item.Key);
                    if (dbFactory.ArePrerequisitesMet())
                    {
                        DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                        IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

                        IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();

                        if (!string.IsNullOrEmpty(savedConnectionStringDescription))
                        {
                            int splitIndex = savedConnectionStringDescription.IndexOf("::");
                            if (splitIndex > -1)
                            {
                                string serverName   = savedConnectionStringDescription.Substring(0, splitIndex);
                                string databaseName = savedConnectionStringDescription.Substring(splitIndex + 2, savedConnectionStringDescription.Length - splitIndex - 2);
                                dialog.SetDatabaseName(databaseName);
                                dialog.SetServerName(serverName);
                            }
                        }

                        System.Windows.Forms.DialogResult result = ((System.Windows.Forms.Form)dialog).ShowDialog();

                        if (result == System.Windows.Forms.DialogResult.OK)
                        {
                            this.savedConnectionStringDescription = dialog.ConnectionStringDescription;
                            bool success = false;
                            db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();

                            try
                            {
                                success = db.TestConnection();
                            }
                            catch
                            {
                                success = false;
                                MessageBox.Show("Could not connect to selected data source.");
                            }

                            if (success)
                            {
                                this.selectedDataSource = db;
                                LoadTablesFromDatabase(db);
                                //formNeedsRefresh = true;
                            }
                            else
                            {
                                this.selectedDataSource = null;
                            }
                        }
                        else
                        {
                            this.selectedDataSource = null;
                        }
                    }
                    else
                    {
                        MessageBox.Show(dbFactory.PrerequisiteMessage, "Prerequisites not found");
                    }
                    break;
                }
            }
        }
        private void SetupOutputDataSource()
        {
            ComboBoxItem     selectedPlugIn = cmbSourceDataFormat.SelectedItem as ComboBoxItem;
            IDbDriverFactory dbFactory      = null;

            string plugin = string.Empty;

            foreach (Epi.DataSets.Config.DataDriverRow row in dashboardHelper.Config.DataDrivers)
            {
                string content = selectedPlugIn.Content.ToString();
                if (content.Equals(row.DisplayName))
                {
                    plugin = row.Type;
                }
            }

            selectedDataProvider = plugin;

            dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(plugin);
            if (dbFactory.ArePrerequisitesMet())
            {
                DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
                db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);

                IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
                dialog.ShouldIgnoreNonExistance = true;

                System.Windows.Forms.DialogResult result = ((System.Windows.Forms.Form)dialog).ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    //this.savedConnectionStringDescription = dialog.ConnectionStringDescription;
                    bool success = false;
                    db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();

                    try
                    {
                        success = db.TestConnection();
                    }
                    catch
                    {
                        success = false;
                        MessageBox.Show("Could not connect to selected data source.");
                    }

                    if (success)
                    {
                        this.SelectedDataSource       = db;
                        controlNeedsRefresh           = true;
                        txtConnectionInformation.Text = db.ConnectionString;
                    }
                    else
                    {
                        this.SelectedDataSource = null;
                    }
                }
                else
                {
                    this.SelectedDataSource = null;
                }
            }
            else
            {
                MessageBox.Show(dbFactory.PrerequisiteMessage, "Prerequisites not found");
            }

            if (selectedDataSource is IDbDriver)
            {
                db = selectedDataSource as IDbDriver;
                //this.txtDataSource.Text = db.ConnectionString;

                System.Collections.Generic.List <string> tableNames = db.GetTableNames();

                foreach (string tableName in tableNames)
                {
                    ComboBoxItem newItem = new ComboBoxItem();//tableName, tableName, tableName);
                    newItem.Content = tableName;
                    cmbSourceTable.Items.Add(tableName);
                    //this.cmbDataTable.Items.Add(newItem);
                }
            }

            pnlProgress.Visibility = System.Windows.Visibility.Collapsed;
        }