Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlServerDataProvider"/> class.
 /// </summary>
 /// <param name="connectionString">The connection string.</param>
 internal SqlServerDataProvider(string connectionString)
     : base(connectionString)
 {
     var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(this.ConnectionString);
     var oleDbConnectionStringBuilder = new OleDbConnectionStringBuilder();
     oleDbConnectionStringBuilder.DataSource = sqlConnectionStringBuilder.DataSource;
     oleDbConnectionStringBuilder.Provider = "SQLOLEDB";
     oleDbConnectionStringBuilder["database"] = sqlConnectionStringBuilder.InitialCatalog;
     oleDbConnectionStringBuilder["trusted_connection"] = sqlConnectionStringBuilder.IntegratedSecurity ? "yes" : "no";
     this.oleDbConnectionString = oleDbConnectionStringBuilder.ToString();
 }
Exemplo n.º 2
0
 public static OleDbConnection getCon()
 {
     if (conexion == null)
     {
         OleDbConnectionStringBuilder b = new OleDbConnectionStringBuilder();
         b.Provider = "Microsoft.ACE.OLEDB.12.0";
         b.DataSource = "cyberman.accdb";
         conexion = new OleDbConnection(b.ToString());
         conexion.Open();
     }
     return conexion;
 }
Exemplo n.º 3
0
        public ExcelReader(string path, bool hasHeaders, bool hasMixedData)
        {
            this.path = path;
            OleDbConnectionStringBuilder strBuilder = new OleDbConnectionStringBuilder();
            strBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
            strBuilder.DataSource = path;
            strBuilder.Add("Extended Properties", "Excel 8.0;"+
                "HDR=" + (hasHeaders ? "Yes" : "No") + ';' +
                "Imex=" + (hasMixedData ? "2" : "0") + ';' +
              "");

            strConnection = strBuilder.ToString();
        }
Exemplo n.º 4
0
        /// <summary>
        /// ���� DataSource ���\���f�[�^�\�[�X�ւ̐ڑ�����݂܂��B
        /// </summary>
        /// <returns></returns>
        public override DbConnection getConnection()
        {
            OleDbConnectionStringBuilder connection_builder = new OleDbConnectionStringBuilder();

            //connection_builder.ConnectTimeout = base.loginTimeout;

            connection_builder["Provider"] = OLEDBProviderFactory.provider;
            connection_builder["Persist Security Info"] = base.integrated_security_;
            connection_builder["Data Source"] = base.data_source_;

            OleDbConnection result_connection = new OleDbConnection( connection_builder.ToString() );
            result_connection.InfoMessage += onInfoMessage;

            return result_connection;
        }
Exemplo n.º 5
0
 private static void AddTable(OleDbConnectionStringBuilder csb)
 {
     // check if table exists
     var con = new ADODB.Connection();
     con.Open(csb.ToString());
     var db = new ADOX.Catalog();
     db.ActiveConnection = con;
     try
     {
         var table = db.Tables[_logFileProcessor.TableName];
     }
     catch (COMException)
     {
         db.Tables.Append(_logFileProcessor.GetTable());
     }
     finally
     {
         con.Close();
     }
 }
Exemplo n.º 6
0
        /*
         * Obtaining the name of the excel sheets and placing them on a list.
         * This method was obtained from: http://stackoverflow.com/questions/1164698/using-excel-oledb-to-get-sheet-names-in-sheet-order
         */
        public List<string> ListSheetInExcel(string filePath)
        {
            OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
            String strExtendedProperties = String.Empty;
            sbConnection.DataSource = filePath;

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

            if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
            {
                sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
                strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
            }
            else if (Path.GetExtension(filePath).Equals(".xlsx"))  //for 2007 Excel file
            {
                sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
                strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
            }

            sbConnection.Add("Extended Properties", strExtendedProperties);

            using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
            {
                conn.Open();
                DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                foreach (DataRow drSheet in dtSheet.Rows)
                {
                    if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
                    {
                        listSheet.Add(drSheet["TABLE_NAME"].ToString());
                    }
                }
            }
            return listSheet;
        }
Exemplo n.º 7
0
 /// <summary>
 /// Method: ListSheetInExcel
 /// This method will return a list of worksheets of the Excel file selected by name
 /// </summary>
 /// <returns>List of Worksheets of a single excel file</returns>
 public static List<string> ListSheetInExcel()
 {
     // List<T> for Excel Worksheets
     List<string> listSheet = new List<string>();
     // OleDbConnectionStringBuilder
     OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
     // String variable for ExtendedProperties
     String strExtendedProperties = String.Empty;
     // Set Datasource for Excel Connection
     sbConnection.DataSource = WinPath;
     // Evaluate which version is the current excel file
     // Excel 2003
     if (Version().Equals(ExcelVersion.ExcelVersion2003))
     {
         // Set provider for 2003
         sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
         strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=0;ReadOnly=true";
     }
     // Excel 2007+
     else if (Version().Equals(ExcelVersion.ExcelVersion2007))
     {
         // Set provider for 2007+
         sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
         strExtendedProperties = "Excel 12.0 Xml;HDR=Yes;IMEX=0";
     }
     // Add Extended Properties to Connection String
     sbConnection.Add("Extended Properties", strExtendedProperties);
     // Asign Connection string to static ExcelConnection variable
     ExcelConnection = sbConnection.ToString();
     // Use the current connection
     using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
     {
         // Open current connection
         conn.Open();
         // Get Tables Schema
         DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
         // Loop through each row and get the table name
         foreach (DataRow drSheet in dtSheet.Rows)
         {
             // Check wheter row contains '_xlnm#_Filte rDatabase'
             // or sheet name(i.e. sheet name always ends with $ sign
             if (drSheet["TABLE_NAME"].ToString().Contains("$"))
             {
                 if (!drSheet["TABLE_NAME"].ToString().Contains("xlnm"))
                 {
                     // Add table name to List<T>
                     listSheet.Add(drSheet["TABLE_NAME"].ToString());
                 }
             }
         }
     }
     // Return List<T>
     return listSheet;
 }
        private string GetStringConnection(string fullFileName)
        {
            OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
            String strExtendedProperties = String.Empty;
            sbConnection.DataSource = fullFileName;
            if (Path.GetExtension(fullFileName).Equals(".xls"))//for 97-03 Excel file
            {
                sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
                strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
            }
            else if (Path.GetExtension(fullFileName).Equals(".xlsx"))  //for 2007 Excel file
            {
                sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
                strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
            }
            sbConnection.Add("Extended Properties", strExtendedProperties);

            return sbConnection.ToString();

        }
        private string GetCSVStringConnection(string fullFileName)
        {
            OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
            String strExtendedProperties = String.Empty;
            sbConnection.DataSource = fullFileName;
            sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
            strExtendedProperties = "Text;HDR=YES;FMT=Delimited";

            sbConnection.Add("Extended Properties", strExtendedProperties);

            return sbConnection.ToString();

        }
Exemplo n.º 10
0
        protected override OleDbConnection GetNativeConnection(string connectionString)
        {
            OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
            oleDBCnnStrBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";

            return new OleDbConnection(oleDBCnnStrBuilder.ToString());
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            // read in arguments, parse them for easy consumption
            ParseCommandlineArguments(args);

            // setup log processor
            _logFileProcessor = LogFileProcessor.Create(_type);
            _logFileProcessor.LogFiles = _logs.GetFiles(_logFilter);

            // set up logger
            Logger.DiskLog = _executionLog;

            // Print welcome message
            Logger.Info();
            Logger.Info(" ##################################################");
            Logger.Info(" # Apatche Log Files to Access Database Converter #");
            Logger.Info(" #                                                #");
            Logger.Info(" # Version 0.3                                    #");
            Logger.Info(" # By: Egil Hansen (http://egilhansen.com)        #");
            Logger.Info(" ##################################################");
            Logger.Info();
            Logger.Info("Runtime settings:");
            Logger.Info();
            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Logger.Info("  Database File (db) ................... : {0}", _dbFileName.FullName);
            Logger.Info("  Overwrite Existing DB File (overwrite) : {0}", _overwrite.ToString());
            Logger.Info("  Logs Directory (logs) ................ : {0}", _logs.FullName);
            Logger.Info("  Log filter (filter) .................. : {0}", _logFilter);
            Logger.Info("  Log File Type (type) ................. : {0}", _logFileProcessor.Name);
            Logger.Info("  Runetime Log (runtimelog) ............ : {0}", _executionLog != null ? _executionLog.FullName : "n/a");
            Logger.Info();
            Console.ResetColor();

            // create target database based on log file type
            var csb = new OleDbConnectionStringBuilder { DataSource = _dbFileName.FullName, Provider = "Microsoft.Jet.OLEDB.4.0" };

            // remove existing database file
            if (_dbFileName.Exists && _overwrite)
            {
                _dbFileName.Delete();
            }

            // create database
            if (_dbFileName.Exists)
            {
                AddTable(csb);
            }
            else
            {
                CreateAccessDatabase(csb.ToString());
            }

            // parse each log file, add each log entry to database
            Logger.Info("Starting log file processing . . .");
            Logger.LogOffscreen(string.Empty);
            Logger.LogOffscreen("Start time: {0}", DateTime.Now);
            Logger.Info();

            _logFileProcessor.Process(csb.ToString());
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets table schema information about an OLE database
        /// </summary>
        /// <returns>DataTable with schema information</returns>
        //This function has been fixed in parent class, It should work for all database type  //  zack 1/30/08
        //public override DataTable GetTableSchema()
        //{
        //DataTable schema = base.GetSchema("Tables");
        //foreach (DataRow row in schema.Rows)
        //{
        //    // TODO: This isn't asbolute, should be replaced with search on...
        //    // exact system table names
        //    if (row[ColumnNames.SCHEMA_TABLE_NAME].ToString().StartsWith("MSys", true, CultureInfo.InvariantCulture))
        //    {
        //        row.Delete();
        //    }
        //}
        //schema.AcceptChanges();
        //    return schema;
        //}
        public static string BuildConnectionString(string filePath, string password)
        {
            StringBuilder builder = new StringBuilder();

            if (filePath.EndsWith(".accdb", true, System.Globalization.CultureInfo.InvariantCulture))
            {
                builder.Append("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
            }

            builder.Append(EncodeOleDbConnectionStringValue(filePath));
            builder.Append(";");

            builder.Append("User Id=admin;Password=;");

            if (!string.IsNullOrEmpty(password))
            {
                builder.Append("Jet OLEDB:Database Password="******";");
            }

            // sanity check
            OleDbConnectionStringBuilder connectionBuilder = new OleDbConnectionStringBuilder(builder.ToString());
            return connectionBuilder.ToString();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Extracts file location and replaces relative file paths with full file paths by updating ConnectionString value
        /// </summary>
        protected void ProcessConnectionString()
        {
            this.location = null;
            if (this.connectionString == null) return;

            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder(this.connectionString);

            string filename = builder.DataSource;
            if (File.Exists(filename))
            {
                if (!Path.IsPathRooted(filename))
                {
                    filename = Path.GetFullPath(filename);
                }
                this.location = filename;
                this.DbName = Path.GetFileNameWithoutExtension(this.location);
                this.connectionString = builder.ToString();
            }
        }
Exemplo n.º 14
0
        private DataTable loadExcelFile(string fileName, string sheetName)
        {
            OleDbConnection objConn = null;
            OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
            sbConnection.DataSource = fileName;
            String strExtendedProperties = Path.GetExtension(fileName);
            try
            {
               DataTable table = new DataTable();
               if (Path.GetExtension(fileName).Equals(".xls"))//for 97-03 Excel file
                  {
                      sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
                      strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
                  }
                  else if (Path.GetExtension(fileName).Equals(".xlsx"))  //for 2007 Excel file
                  {
                      sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
                      strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
                  }
                  sbConnection.Add("Extended Properties", strExtendedProperties);
                  objConn = new OleDbConnection(sbConnection.ToString());
                  objConn.Open();
                  using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConn)) //rename sheet if required!
                      dbAdapter.Fill(table);

                if (table == null)
                {
                    return null;
                }
                creator.loadData(table);
                return table;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                // Clean up.
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }
Exemplo n.º 15
0
        private String[] SheetNames(string fileName)
        {
            String[] Sheets = null;
            OleDbConnection objConn = null;
            OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
            sbConnection.DataSource = fileName;
            String strExtendedProperties = Path.GetExtension(fileName);
            try
            {
                if (Path.GetExtension(fileName).Equals(".xls") || Path.GetExtension(fileName).Equals(".xlsx"))//any excel sheet
                {
                    if (Path.GetExtension(fileName).Equals(".xls"))//for 97-03 Excel file
                    {
                        sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
                        strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
                    }
                    else if (Path.GetExtension(fileName).Equals(".xlsx"))  //for 2007 Excel file
                    {
                        sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
                        strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
                    }
                    sbConnection.Add("Extended Properties", strExtendedProperties);
                    objConn = new OleDbConnection(sbConnection.ToString());
                    objConn.Open();
                    dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                    if (dt == null)
                    {
                        return null;
                    }

                    Sheets = new String[dt.Rows.Count];
                    int i = 0;

                    // Add the sheet name to the string array.
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["TABLE_NAME"].ToString().Contains("$")
                            && !row["TABLE_NAME"].ToString().Contains("$Print")
                            && !row["TABLE_NAME"].ToString().Contains("$'Print")
                             && !row["TABLE_NAME"].ToString().Contains("$_"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
                        {
                            Sheets[i] = row["TABLE_NAME"].ToString();
                            //Sheets[i] = Sheets[i].Replace("$", "");
                            //Sheets[i] = Sheets[i].Replace("'", "");
                            i++;
                        }
                    }
                }
                return Sheets;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                // Clean up.
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }
Exemplo n.º 16
0
 protected override OleDbConnection GetNativeConnection(string connectionString)
 {
     OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
     oleDBCnnStrBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
     oleDBCnnStrBuilder.Add("Mode","ReadWrite");
     oleDBCnnStrBuilder.Add("Extended Properties", "Excel 8.0;HDR=Yes");
     return new OleDbConnection(oleDBCnnStrBuilder.ToString());
 }
Exemplo n.º 17
0
        public static string BuildConnectionString(string filePath, string password)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=");

            builder.Append(EncodeOleDbConnectionStringValue(filePath));
            builder.Append(";Extended Properties=\"text;HDR=Yes;FMT=Delimited\";");

            // sanity check
            OleDbConnectionStringBuilder connectionBuilder = new OleDbConnectionStringBuilder(builder.ToString());
            return connectionBuilder.ToString();
        }
Exemplo n.º 18
0
 protected override OleDbConnection GetNativeConnection(string connectionString)
 {
     OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
     oleDBCnnStrBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
     oleDBCnnStrBuilder.Add("Extended Properties", "text;HDR=Yes;FMT=Delimited");
     return new OleDbConnection(oleDBCnnStrBuilder.ToString());
 }
Exemplo n.º 19
0
 protected override OleDbConnection GetNativeConnection(string connectionString)
 {
     OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
     oleDBCnnStrBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
     oleDBCnnStrBuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
     return new OleDbConnection(oleDBCnnStrBuilder.ToString());
 }
Exemplo n.º 20
0
        /// <summary>
        /// Reads the contents of an excel report file into a list of sales arrays;
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="salesDate"></param>
        /// <returns>rows: Supermarket, Data, ProductID, Quantity, Unit Price</returns>
        public static List<string[]> ReadOneExcelFile(OleDbConnectionStringBuilder connectionString, string supermarket, string salesDate)
        {
            List<String[]> data = new List<String[]>();
            using (OleDbConnection connection = new OleDbConnection(connectionString.ToString()))
            {
                connection.Open();
                var command = new OleDbCommand("select * from [Sales$B3:E1000]", connection);
                using (OleDbDataReader oneRow = command.ExecuteReader())
                {
                    oneRow.Read();  // Skip row - ProductID, Quantity, Unit Price

                    while (oneRow.Read())
                    {
                        string productID = oneRow[0].ToString();
                        string quantity = oneRow[1].ToString();
                        string unitPrice = oneRow[2].ToString();
                        int result;  // only to check if the line containd a sale
                        if (int.TryParse(productID, out result))
                        // If not the Last rows
                        {
                            string[] line = { supermarket, salesDate, productID, quantity, unitPrice };
                            data.Add(line);
                        }
                    }
                }
            }
            return data;
        }
Exemplo n.º 21
0
        public static string BuildConnectionString(string filePath, string password)
        {
            StringBuilder builder = new StringBuilder();

            if (filePath.EndsWith(".xls", true, System.Globalization.CultureInfo.InvariantCulture))
            {
                builder.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=");
            }

            builder.Append(EncodeOleDbConnectionStringValue(filePath));
            builder.Append(";ReadOnly=False;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";");

            // sanity check
            OleDbConnectionStringBuilder connectionBuilder = new OleDbConnectionStringBuilder(builder.ToString());
            return connectionBuilder.ToString();
        }
Exemplo n.º 22
0
 /// <summary>
 /// Build a user connection string.
 /// Note that this doesn't modify the Username or Password properties.
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public String BuildConnectionString(String username, String password)
 {
     OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
     if (_conString != null)
     {
         builder.ConnectionString = _conString;
     }
     else
     {
         builder["Provider"] = "SLXOLEDB";
         builder["Data Source"] = _server;
         builder["Initial Catalog"] = _database;
     }
     if(username != null)
         builder["User Id"] = username;
     if(password != null)
         builder["Password"] = password;
     return builder.ToString();
 }
Exemplo n.º 23
0
        private void initialize(string path, bool hasHeaders, bool hasMixedData)
        {
            string fullPath = Path.GetFullPath(path);
            string extension = Path.GetExtension(path);

            if (!File.Exists(fullPath))
                throw new FileNotFoundException("File could not be found.", fullPath);

            string tempFileName = Path.GetTempFileName();
            File.Copy(fullPath, tempFileName, true);

            // Reader Settings
            HasHeaders = hasHeaders;
            HasMixedData = hasMixedData;

            switch (extension)
            {
                case ".xls": Version = "Excel 8.0"; break; // Excel 95-2003
                case ".xlsx": Version = "Excel 12.0"; break; // Excel 2007+
                default: throw new ArgumentException("File type could not be determined by file extension.", "path");
            }

            if (IntPtr.Size == 4 && extension == ".xls")
                Provider = "Microsoft.Jet.OLEDB.4.0";   // for x86/95-2003
            else Provider = "Microsoft.ACE.OLEDB.12.0"; // for x64/95-2007+

            OleDbConnectionStringBuilder strBuilder
                = new OleDbConnectionStringBuilder();

            strBuilder.Provider = Provider;
            strBuilder.DataSource = tempFileName;
            strBuilder.Add("Extended Properties", Version + ";" +
                "HDR=" + (HasHeaders ? "Yes" : "No") + ';' +
                "Imex=" + (HasMixedData ? "2" : "0") + ';');
            strConnection = strBuilder.ToString();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets all players from a ZIP archive
        /// </summary>
        /// <param name="zip">Gets a ZIP archive</param>
        /// <returns>Returns a Dictionary with a key of type string and value ot type List<Player></returns>
        public static Dictionary<string, List<Player>> GetAllPlayers(ZipArchive zip)
        {
            var sales = new List<List<string>>();
            var teamPlayers = new Dictionary<string, List<Player>>();

            foreach (var entry in zip.Entries)
            {
                if (entry.FullName.EndsWith(".xls"))
                {
                    var entryParts = entry.FullName.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    var fileName = entry.FullName;
                    if (entryParts.Length > 1)
                    {
                        fileName = entryParts[entryParts.Length - 1];
                    }

                    using (var ms = new MemoryStream())
                    {
                        var file = File.Create(TempFile);
                        using (file)
                        {
                            CopyStream(entry.Open(), ms);
                            ms.WriteTo(file);
                        }
                    }

                    var connection = new OleDbConnection();
                    var connectionString = new OleDbConnectionStringBuilder
                    {
                        { "Provider", "Microsoft.ACE.OLEDB.12.0" },
                        { "Extended Properties", "Excel 12.0 XML" },
                        { "Data Source", TempFile }
                    };

                    connection.ConnectionString = connectionString.ToString();

                    using (connection)
                    {
                        connection.Open();

                        var excelSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                        var sheetName = excelSchema.Rows[0]["TABLE_NAME"].ToString();

                        var oleDbCommand = new OleDbCommand("SELECT * FROM [" + sheetName + "]", connection);

                        using (var adapter = new OleDbDataAdapter(oleDbCommand))
                        {
                            var dataSet = new DataSet();
                            adapter.Fill(dataSet);

                            using (var reader = dataSet.CreateDataReader())
                            {
                                while (reader.Read())
                                {
                                    var team = fileName.Split('.')[0];
                                    if (!teamPlayers.ContainsKey(team))
                                    {
                                        teamPlayers.Add(team, new List<Player>());
                                    }

                                    var player = new Player()
                                    {
                                        FirstName = reader["FirstName"].ToString(),
                                        LastName = reader["LastName"].ToString(),
                                        Number = int.Parse(reader["Number"].ToString()),
                                        Position =
                                            (Position)Enum.Parse(typeof(Position), reader["Position"].ToString()),
                                        Salary = decimal.Parse(reader["Salary"].ToString()),
                                    };
                                    Console.WriteLine(player.FirstName);
                                    teamPlayers[team].Add(player);
                                }
                            }
                        }
                    }
                }
            }

            File.Delete(TempFile);
            return teamPlayers;
        }
Exemplo n.º 25
0
Arquivo: test.cs Projeto: mono/gert
	static string CreateOleDbConnectionString ()
	{
#if NET_2_0
		OleDbConnectionStringBuilder csb = new OleDbConnectionStringBuilder ();
		csb.Provider = "sqloledb";
#else
		StringBuilder sb = new StringBuilder ();
		sb.Append ("Provider=sqloledb;");
#endif

		string serverName = Environment.GetEnvironmentVariable ("MONO_TESTS_SQL_HOST");
		if (serverName == null)
			throw CreateEnvironmentVariableNotSetException ("MONO_TESTS_SQL_HOST");
#if NET_2_0
		csb.DataSource = serverName;
#else
		sb.AppendFormat ("Data Source={0};", serverName);
#endif

		string dbName = Environment.GetEnvironmentVariable ("MONO_TESTS_SQL_DB");
		if (dbName == null)
			throw CreateEnvironmentVariableNotSetException ("MONO_TESTS_SQL_DB");
#if NET_2_0
		csb.Add ("Initial Catalog", dbName);
#else
		sb.AppendFormat ("Initial Catalog={0};", dbName);
#endif

		string userName = Environment.GetEnvironmentVariable ("MONO_TESTS_SQL_USER");
		if (userName != null)
#if NET_2_0
			csb.Add ("User id", userName);
#else
			sb.AppendFormat ("User id={0};", userName);
#endif

		string pwd = Environment.GetEnvironmentVariable ("MONO_TESTS_SQL_PWD");
		if (pwd != null)
#if NET_2_0
			csb.Add ("Password", pwd);
#else
			sb.AppendFormat ("Password={0};", pwd);
#endif

#if NET_2_0
		return csb.ToString ();
#else
		return sb.ToString ();
#endif
	}
Exemplo n.º 26
0
        /// <summary>
        /// Gets a native connection instance from supplied connection string
        /// </summary>
        /// <returns>Native connection object</returns>
        protected virtual OleDbConnection GetNativeConnection(string connectionString)
        {
            OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
            oleDBCnnStrBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";

            return new OleDbConnection(oleDBCnnStrBuilder.ToString());
        }