public virtual void Initialize()
        {
            TestHelper.SetupLog4NetForTests();
            TestHelper.InitializeContentDirectories();

            Path = TestHelper.CurrentAssemblyDirectory;
            AppDomain.CurrentDomain.SetData("DataDirectory", Path);

            Resolution.Freeze();

            //Delete database file before continueing
            string filePath = string.Concat(Path, "\\UmbracoPetaPocoTests.sdf");
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            //Get the connectionstring settings from config
            var settings = ConfigurationManager.ConnectionStrings[Core.Configuration.GlobalSettings.UmbracoConnectionName];

            //Create the Sql CE database
            var engine = new SqlCeEngine(settings.ConnectionString);
            engine.CreateDatabase();

            SqlSyntaxContext.SqlSyntaxProvider = SqlCeSyntax.Provider;
        }
示例#2
1
        public void MultiRSSqlCE()
        {
            if (File.Exists("Test.sdf"))
                File.Delete("Test.sdf");

            var cnnStr = "Data Source = Test.sdf;";
            var engine = new SqlCeEngine(cnnStr);
            engine.CreateDatabase();

            using (var cnn = new SqlCeConnection(cnnStr))
            {
                cnn.Open();

                cnn.Execute("create table Posts (ID int, Title nvarchar(50), Body nvarchar(50), AuthorID int)");
                cnn.Execute("create table Authors (ID int, Name nvarchar(50))");

                cnn.Execute("insert Posts values (1,'title','body',1)");
                cnn.Execute("insert Posts values(2,'title2','body2',null)");
                cnn.Execute("insert Authors values(1,'sam')");

                var data = cnn.Query<PostCE, AuthorCE, PostCE>(@"select * from Posts p left join Authors a on a.ID = p.AuthorID", (post, author) => { post.Author = author; return post; }).ToList();
                var firstPost = data.First();
                firstPost.Title.IsEqualTo("title");
                firstPost.Author.Name.IsEqualTo("sam");
                data[1].Author.IsNull();
                cnn.Close();
            }
        }
        private void TestConnection(bool showMessage)
        {
            try
            {
                if (createDb)
                {
                    if (!System.IO.File.Exists(builder.DataSource))
                    {
                        using (var eng = new SqlCeEngine(builder.ConnectionString))
                        {
                            eng.CreateDatabase();
                        }
                    }
                }

                using (var conn = new SqlCeConnection(builder.ConnectionString))
                {
                    conn.Open();
                    this.ConnectionString = builder.ConnectionString;
                    if (showMessage)
                    {
                        MessageBox.Show("Test succeeded!");
                    }
                    else
                    {
                        this.DialogResult = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex));
            }
        }
        public override bool CheckConnectionString(string connectionString)
        {
            try
            {
                var builder = new SqlConnectionStringBuilder(connectionString);

                if (File.Exists(builder.DataSource) == false)
                {
                    var containingFolder = builder.DataSource.Substring(0, builder.DataSource.LastIndexOf("\\"));
                    if (Directory.Exists(containingFolder) == false)
                    {
                        GenericUtils.CreateFolderStructure(containingFolder);
                    }

                    var engine = new SqlCeEngine(connectionString);
                    engine.CreateDatabase();
                }
            }
            catch (Exception ex) { Console.WriteLine("Unable to create SQL CE database automatically. The database should be created manually. Error Details : " + ex.Message);  }

            var connectionCretead = CreateConnection(null, connectionString);
            if (connectionCretead != null && connectionCretead.State == System.Data.ConnectionState.Open)
            {
                connectionCretead.Close();
                return true;
            }
            return false;
        }
        public void Can_Assert_Created_Database()
        {
            string path = TestHelper.CurrentAssemblyDirectory;
            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            //Delete database file before continueing
            //NOTE: we'll use a custom db file for this test since we're re-using the one created with BaseDatabaseFactoryTest
            string filePath = string.Concat(path, "\\DatabaseContextTests.sdf");
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            //Get the connectionstring settings from config
            var settings = ConfigurationManager.ConnectionStrings[Core.Configuration.GlobalSettings.UmbracoConnectionName];

            //by default the conn string is: Datasource=|DataDirectory|UmbracoPetaPocoTests.sdf;Flush Interval=1;
            //we'll just replace the sdf file with our custom one:
            //Create the Sql CE database
            var engine = new SqlCeEngine(settings.ConnectionString.Replace("UmbracoPetaPocoTests", "DatabaseContextTests"));
            engine.CreateDatabase();

            SqlSyntaxContext.SqlSyntaxProvider = SqlCeSyntax.Provider;

            //Create the umbraco database
			_dbContext.Database.CreateDatabaseSchema(false);

			bool umbracoNodeTable = _dbContext.Database.TableExist("umbracoNode");
			bool umbracoUserTable = _dbContext.Database.TableExist("umbracoUser");
			bool cmsTagsTable = _dbContext.Database.TableExist("cmsTags");

            Assert.That(umbracoNodeTable, Is.True);
            Assert.That(umbracoUserTable, Is.True);
            Assert.That(cmsTagsTable, Is.True);
        }
示例#6
0
		public void RunApplication(string[] args)
		{
			// example command line args: 
			// ClearCanvas.Dicom.DataStore.SetupApplication.Application "<TrunkPath>\Dicom\DataStore\AuxiliaryFiles\empty_viewer.sdf" "<TrunkPath>\Dicom\DataStore\AuxiliaryFiles\CreateTables.clearcanvas.dicom.datastore.ddl"

			string databaseFile = args[0];
			string scriptFile = args[1];

			File.Delete(databaseFile);

			string connectionString = String.Format("Data Source=\"{0}\"", databaseFile);

			SqlCeEngine engine = new SqlCeEngine(connectionString);
			engine.CreateDatabase();
			engine.Dispose();

			StreamReader reader = new StreamReader(scriptFile);
			string scriptText = reader.ReadToEnd();
			reader.Close();

			SqlCeConnection connection = new SqlCeConnection(connectionString);
			connection.Open();

			SqlCeTransaction transaction = connection.BeginTransaction();
			SqlCeCommand command = new SqlCeCommand();
			command.Connection = connection;
			command.CommandText = scriptText;
			command.ExecuteNonQuery();

			transaction.Commit();
			connection.Close();

		}
示例#7
0
        public override void Initialize(string name, NameValueCollection config)
        {
            try
            {
                // Initialize connection string.
                string path = config["path"];
                if (string.IsNullOrEmpty(path))
                    path = "~/App_Data/DynamicImage/DynamicImageCache.sdf";
                string absolutePath = HttpContext.Current.Server.MapPath(path);
                if (!Directory.Exists(Path.GetDirectoryName(absolutePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(absolutePath));
                _connectionString = string.Format("Data Source={0}", absolutePath);
                if (!File.Exists(absolutePath))
                {
                    using (SqlCeEngine en = new SqlCeEngine(_connectionString))
                        en.CreateDatabase();

                    UseConnection(conn =>
                    {
                        using (DbCommand comm = conn.CreateCommand())
                        {
                            // Create the Version table if it doesn't already exist.
                            comm.CommandText = "CREATE TABLE Version (VersionNumber INT)";
                            comm.ExecuteNonQuery();
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException("Could not initialize connection string.", ex);
            }

            base.Initialize(name, config);
        }
        public override void DatabaseSpecificSetUp()
        {
            string filePath = string.Concat(Path, "\\UmbracoPetaPocoTests.sdf");

            if (!File.Exists(filePath))
            {
                try
                {
                    //Delete database file before continueing                    
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
                catch (Exception)
                {
                    //if this doesn't work we have to make sure everything is reset! otherwise
                    // well run into issues because we've already set some things up
                    TearDown();
                    throw;
                }

                //Create the Sql CE database
                //Get the connectionstring settings from config
                var settings = ConfigurationManager.ConnectionStrings[Core.Configuration.GlobalSettings.UmbracoConnectionName];
                var engine = new SqlCeEngine(settings.ConnectionString);
                engine.CreateDatabase();
            }
            else
            {
                TestHelper.ClearDatabase();
            }
            
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Creates SQL Server CE database using specified file path.
        /// Executes SQL script using specified script value if not null.
        /// </summary>
        /// <param name="path">
        /// Database file path.
        /// </param>
        /// <param name="createScript">
        /// Transact SQL script to execute. Optional (can be null).
        /// Provided script must conform to SQL Server CE.
        /// </param>
        public static void CreateDatabase(string path, string createScript)
        {
            Debug.Assert(path != null);

            bool dbCreated = false;
            try
            {
                // check if specified file exists
                if (File.Exists(path))
                    throw new DataException(Properties.Messages.Error_DbFileExists);

                // build connection string
                string connStr = DatabaseHelper.BuildSqlConnString(path, false);

                // create database
                SqlCeEngine engine = new SqlCeEngine(connStr);
                engine.CreateDatabase();
                dbCreated = true;

                // execute SQL script
                if (createScript != null)
                    ExecuteScript(connStr, createScript, null);
            }
            catch (Exception e)
            {
                Logger.Error(e);

                if (dbCreated)
                    DeleteDatabase(path);

                throw;
            }
        }
        public static void CreateDatabaseIfRequired(string connection, string applicationName)
        {
            lock (_lock)
            {
                SqlCeConnectionStringBuilder builder = new SqlCeConnectionStringBuilder();
                builder.ConnectionString = connection;

                string sdfPath = ReplaceDataDirectory(builder.DataSource);

                if (string.IsNullOrWhiteSpace(sdfPath))
                    return;

                if (!System.IO.File.Exists(sdfPath))
                {
                    //OK, try to create the database file
                    using (var engine = new SqlCeEngine(connection))
                    {
                        engine.CreateDatabase();
                    }

                                        Util.ExecuteSqlUpgradeScript(GalleryDataSchemaUpgradeScript.SqlCeInstallScript);
                                }
                ValidateDatabase(connection, applicationName);

            }
        }
 private static void CreateDatabase()
 {
     if (File.Exists(_fileName))
         File.Delete(_fileName);
     using (var engine = new SqlCeEngine(_connectionString))
         engine.CreateDatabase();
 }
示例#12
0
        public void Can_Assert_Created_Database()
        {
            string path = TestHelper.CurrentAssemblyDirectory;
            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            //Delete database file before continueing
            string filePath = string.Concat(path, "\\UmbracoPetaPocoTests.sdf");
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            //Get the connectionstring settings from config
            var settings = ConfigurationManager.ConnectionStrings[Core.Configuration.GlobalSettings.UmbracoConnectionName];

            //Create the Sql CE database
            var engine = new SqlCeEngine(settings.ConnectionString);
            engine.CreateDatabase();

            SqlSyntaxContext.SqlSyntaxProvider = SqlCeSyntax.Provider;

            //Create the umbraco database
			_dbContext.Database.CreateDatabaseSchema(false);

			bool umbracoNodeTable = _dbContext.Database.TableExist("umbracoNode");
			bool umbracoUserTable = _dbContext.Database.TableExist("umbracoUser");
			bool cmsTagsTable = _dbContext.Database.TableExist("cmsTags");

            Assert.That(umbracoNodeTable, Is.True);
            Assert.That(umbracoUserTable, Is.True);
            Assert.That(cmsTagsTable, Is.True);
        }
示例#13
0
 public void RepairDatabaseRecoverAllPossibleRows(string connectionString)
 {
     using (SqlCeEngine engine = new SqlCeEngine(connectionString))
     {
         engine.Repair(connectionString, RepairOption.RecoverAllPossibleRows);
     }
 }
示例#14
0
 public void VerifyDatabase(string connectionString)
 {
     using (SqlCeEngine engine = new SqlCeEngine(connectionString))
     {
         engine.Verify(VerifyOption.Enhanced);
     }
 }
示例#15
0
 public void RepairDatabaseRecoverAllOrFail(string connectionString)
 {
     using (SqlCeEngine engine = new SqlCeEngine(connectionString))
     {
         engine.Repair(connectionString, RepairOption.RecoverAllOrFail);
     }
 }
示例#16
0
 public void RepairDatabaseDeleteCorruptedRows(string connectionString)
 {
     using (SqlCeEngine engine = new SqlCeEngine(connectionString))
     {
         engine.Repair(connectionString, RepairOption.DeleteCorruptedRows);
     }
 }
示例#17
0
 public void CompactDatabase(string connectionString)
 {
     using (SqlCeEngine engine = new SqlCeEngine(connectionString))
     {
         engine.Compact(null);
     }
 }
示例#18
0
        public void TestFixtureSetup()
        {
            // Initialize the database.

            if (File.Exists("Test.sdf")) {
                File.Delete("Test.sdf");
            }

            using (var engine = new SqlCeEngine(ConfigurationManager.ConnectionStrings["Test"].ConnectionString)) {
                engine.CreateDatabase();
            }

            using (var conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString)) {
                var cmd = conn.CreateCommand();
                conn.Open();

                cmd.CommandText = "create table Users (Id int identity, Name nvarchar(250))";
                cmd.ExecuteNonQuery();

                cmd.CommandText = "create table ManualIdUser (Id int, Name nvarchar(250))";
                cmd.ExecuteNonQuery();

                cmd.CommandText =
                    "create table CompositeKeyUser (Id int not null, Id2 nvarchar(250) not null, Name nvarchar(250), primary key (Id, Id2)) ";
                cmd.ExecuteNonQuery();
            }
        }
示例#19
0
 /// <summary>
 /// 创建新数据源。
 /// </summary>
 public void CreateDatabase()
 {
     using(SqlCeEngine engine = new SqlCeEngine(this.ConnectionString))
     {
         engine.CreateDatabase();
     }
 }
示例#20
0
    public void CreateDatabase(string fileName, string password)
    {
        string connectionString;
        if (System.IO.File.Exists(fileName))
            return;
            //System.IO.File.Delete(fileName);

        // The DataSource must be surrounded with double quotes. The Password, on the other hand, must be surrounded
        // with single quotes
        connectionString = string.Format(
          "DataSource=\"{0}\"; Password='******'", fileName, password);

        // we'll use the SqlServerCe connection object to get the database file path
        using (SqlCeConnection localConnection = new SqlCeConnection(connectionString))
        {
            // The SqlCeConnection.Database property contains the file parth portion
            // of the database from the full connectionstring
            if (!System.IO.File.Exists(localConnection.Database))
            {
                using (SqlCeEngine sqlCeEngine = new SqlCeEngine(connectionString))
                {
                    sqlCeEngine.CreateDatabase();
                    CreateInitialDatabaseObjects(connectionString);
                }
            }
        }
    }
示例#21
0
        public static DataTable ExecuteSqlQuery(string query, params SqlCeParameter[] sqlParams)
        {
            var dt = new DataTable();

            using (var conn = new SqlCeConnection(connStr))
            using (var cmd = new SqlCeCommand(query, conn))
            {
                try
                {
                    SqlCeEngine engine = new SqlCeEngine(conn.ConnectionString);
                    engine.Upgrade(conn.ConnectionString);
                }
                catch
                {
                }

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddRange(sqlParams);

                conn.Open();
                dt.Load(cmd.ExecuteReader());
            }

            return dt;
        }
        public ctlrptActiveCall()
        {
            try
            {
                InitializeComponent();

                ConnectionString = VMuktiAPI.VMuktiInfo.MainConnectionString;
                if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory.ToString() + "rptActiveCall.sdf"))
                {
                    System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory.ToString() + "rptActiveCall.sdf");
                }
                SqlCeEngine clientEngine = new SqlCeEngine(ClientConnectionString);
                clientEngine.CreateDatabase();
                LocalSQLConn = new SqlCeConnection();
                LocalSQLConn.ConnectionString = ClientConnectionString;
                LocalSQLConn.Open();
                fncActiveCallTable();
                LocalSQLConn.Close();

                objRefreshReport = new delRefreshReport(fncRefreshReport);
                NetPeerClient npcActiveCall = new NetPeerClient();
                ((NetP2PBootStrapActiveCallReportDelegates)objActiveCall).EntsvcJoinCall += new NetP2PBootStrapActiveCallReportDelegates.DelsvcJoinCall(ctlrptActiveCall_EntsvcJoinCall);
                ((NetP2PBootStrapActiveCallReportDelegates)objActiveCall).EntsvcGetCallInfo += new NetP2PBootStrapActiveCallReportDelegates.DelsvcGetCallInfo(ctlrptActiveCall_EntsvcGetCallInfo);
                ((NetP2PBootStrapActiveCallReportDelegates)objActiveCall).EntsvcActiveCalls += new NetP2PBootStrapActiveCallReportDelegates.DelsvcActiveCalls(ctlrptActiveCall_EntsvcActiveCalls);
                ((NetP2PBootStrapActiveCallReportDelegates)objActiveCall).EntsvcSetDuration += new NetP2PBootStrapActiveCallReportDelegates.DelsvcSetDuration(ctlrptActiveCall_EntsvcSetDuration);
                ((NetP2PBootStrapActiveCallReportDelegates)objActiveCall).EntsvcUnJoinCall += new NetP2PBootStrapActiveCallReportDelegates.DelsvcUnJoinCall(ctlrptActiveCall_EntsvcUnJoinCall);
                channelNetTcpActiveCall = (INetP2PBootStrapReportChannel)npcActiveCall.OpenClient<INetP2PBootStrapReportChannel>("net.tcp://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + ":6000/NetP2PBootStrapActiveCallReport", "ActiveCallMesh", ref objActiveCall);
                channelNetTcpActiveCall.svcJoinCall(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);

            }
            catch (Exception ex)
            {
                VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "ctlrptActiveCall", "ctlrptActiveCall.xaml.cs");
            }
        }
示例#23
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string CreateDatabase(string fileName)
        {
            try
            {
                using (SqlCeEngine sqlCeEngine = new SqlCeEngine(GetConnectionString(fileName)))
                {
                    sqlCeEngine.CreateDatabase();

                    using (SqlCeConnection connection = new SqlCeConnection(GetConnectionString(fileName)))
                    {
                        connection.Open();

                        using (SqlCeCommand command = new SqlCeCommand(SQL_TABLE_SESSION, connection))
                        {
                            command.ExecuteNonQuery();
                        }

                        using (SqlCeCommand command = new SqlCeCommand(SQL_TABLE_SESSION_PK, connection))
                        {
                            command.ExecuteNonQuery();
                        }
                    }
                }

                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
示例#24
0
 public void ShrinkDatabase(string connectionString)
 {
     using (SqlCeEngine engine = new SqlCeEngine(connectionString))
     {
         engine.Shrink();
     }
 }
示例#25
0
 /// <summary>
 /// Reclaims wasted space in the database and recalculates identity column values. Applies only to SQL CE.
 /// </summary>
 internal static void Compact()
 {
     using (SqlCeEngine engine = new SqlCeEngine(Util.ConnectionString))
     {
         engine.Compact(null);
     }
 }
        public static void CreateDatabaseIfRequired(string connection, string applicationName)
        {
            string dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string;

            string physConnectionString = connection.Replace("|DataDirectory|" + System.IO.Path.DirectorySeparatorChar, dataDirectory +  System.IO.Path.DirectorySeparatorChar);

            physConnectionString = physConnectionString.Replace("|DataDirectory|", dataDirectory + System.IO.Path.DirectorySeparatorChar);

            string sdfPath = string.Empty;
            lock (_lock)
            {
                SqlCeConnectionStringBuilder builder = new SqlCeConnectionStringBuilder();
                builder.ConnectionString = physConnectionString;

                sdfPath = builder.DataSource;

                if (string.IsNullOrWhiteSpace(sdfPath))
                    return;

                if (!System.IO.File.Exists(sdfPath))
                {
                    //OK, try to create the database file
                    using (var engine = new SqlCeEngine(connection))
                    {
                        engine.CreateDatabase();
                    }
                }
                ValidateDatabase(connection, applicationName);

            }
        }
示例#27
0
        public Database()
        {
            //Data Source=Mobile Device\SD-MMC Card\EnviDATA.sdf;Persist Security Info=True

            // Create new database
            try
            {
                m_FilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            }
            catch (Exception ex)
            {
                //Silent catch
                //ClassLibrary.Global.HandleError(null, ex);
                MessageBox.Show(ex.Message);
            }

            string _Path = string.Format("{0}\\{1}", m_FilePath, m_FileName);
            if (!File.Exists(_Path))
            {
                //check
            }

            m_ConectionString = string.Format("Data Source={0};Persist Security Info=True;Password ='******'", _Path, m_Password);

            m_Engine = new SqlCeEngine(m_ConectionString);

            Database.CheckIntegrity();
        }
示例#28
0
        public void EnsureDatabase()
        {
            try
            {
                if (sqlCeFilePath.Length > 0)
                {
                    
                    //string connectionString = "Data Source=" + sqlCeFilePath + ";Persist Security Info=False;";

                    if (!File.Exists(sqlCeFilePath))
                    {
                        lock (theLock)
                        {
                            if (!File.Exists(sqlCeFilePath))
                            {
                                using (SqlCeEngine engine = new SqlCeEngine(connectionString))
                                {
                                    engine.CreateDatabase();
                                }
                            }

                        }

                    }

                }
            }
            catch (Exception ex)
            {
                log.LogError("SqlCe database file is not present, tried to create it but this error occurred.", ex);

            }

        }
示例#29
0
        private static void Setup()
        {
            var projLoc    = Assembly.GetAssembly(typeof(Program)).Location;
            var projFolder = Path.GetDirectoryName(projLoc);

            if (File.Exists(projFolder + "\\Test.sdf"))
            {
                File.Delete(projFolder + "\\Test.sdf");
            }
            var connectionString = "Data Source = " + projFolder + "\\Test.sdf;";
            var engine           = new SqlCeEngine(connectionString);

            engine.CreateDatabase();
            using (var connection = new SqlCeConnection(connectionString))
            {
                connection.Open();
                connection.Execute(@" create table Users (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, Age int not null, ScheduledDayOff int null) ");
                connection.Execute(@" create table Car (CarId int IDENTITY(1,1) not null, Make nvarchar(100) not null, Model nvarchar(100) not null) ");
            }
            Console.WriteLine("Created database");
        }
示例#30
0
 public static void UpgradeDatabase(string connectionString)
 {
     try
     {
         using (SqlCeEngine sqlCeEngine = new SqlCeEngine(connectionString))
         {
             sqlCeEngine.Upgrade();
         }
     }
     catch (Exception ex)
     {
         if (ex.Message.ToLower().Contains("database upgrade is not required"))
         {
             // do nothing -- the database has already been upgraded
         }
         else
         {
             throw;
         }
     }
 }
示例#31
0
        public static void CreateDatabaseAndTables()
        {
            using (var engine = new SqlCeEngine($"Data Source=\"{AppDomain.CurrentDomain.BaseDirectory}Data\\UserData.sdf\"; Password=\"test_password\""))
            {
                if (!engine.Verify())
                {
                    engine.CreateDatabase();
                    using (var connection = new SqlCeConnection($"Data Source=\"{AppDomain.CurrentDomain.BaseDirectory}Data\\UserData.sdf\"; Password=\"test_password\""))
                    {
                        connection.Execute(@"REMOVE TABLE TestUser;");
                        connection.Execute(@"CREATE TABLE User(
												[UserId] [INT] IDENTITY(1,1) PRIMARY KEY NOT NULL,
												[FirstName] [NVARCHAR](256) NOT NULL,
												[LastName] [NVARCHAR](256) NOT NULL,
												[EmailAddress] [NVARCHAR](256) NOT NULL,
												[CreatedDate] [DATETIME]  NOT NULL DEFAULT(GETDATE()),
												[ModifiedDate] [DATETIME] NOT NULL DEFAULT(GETDATE()));"                                                );
                    }
                }
            }
        }
示例#32
0
        public void CreateDatabase(string filename, string password, int?maxDatabaseSize)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }

            var connStr = "Data Source=" + filename;

            if (!string.IsNullOrEmpty(password))
            {
                connStr += "; Password="******"; Max Database Size=" + maxDatabaseSize.Value;
            }

            using (var engine = new SqlCeEngine(connStr))
                engine.CreateDatabase();
        }
        public void CreateDB()
        {
            if (FSDK.FSDKE_OK != FSDK.ActivateLibrary("VBsVmYmHr/5JxUlk3q0KHjILz7R3Hb5OEhCQ7KdCg/tPbQqJfAaz8ok/9+iTgDp/KjGjkBi23HeCaUq8KKtKeXXN3xbe+bKfQ8q/3mfG6sad3AGUYDj6E+Qi2pzCWFgb4vqWDB3pLzUw+hnOZ7///CBV63IaB1kh7XF6VCaGtNw="))
            {
                MessageBox.Show("Please run the License Key Wizard (Start - Luxand - FaceSDK - License Key Wizard)", "Error activating FaceSDK", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (FSDK.InitializeLibrary() != FSDK.FSDKE_OK)
            {
                MessageBox.Show("Error initializing FaceSDK!", "Error");
            }

            SqlCeEngine en = new SqlCeEngine(stringCon);

            if (!File.Exists("FaceDB.sdf"))
            {
                en.CreateDatabase();
                CreateTable();
                CreateSettingsTable();
            }
        }
示例#34
0
        public void BeforeDatabaseIntegration()
        {
            if (File.Exists("TestDB.sdf"))
            {
                File.Delete("TestDB.sdf");
            }

            sqlCeEngine = new SqlCeEngine(TestDbConnectionString);
            sqlCeEngine.CreateDatabase();

            using (var connection = new SqlCeConnection(TestDbConnectionString))
            {
                connection.Execute(@"
                   create table Posts (
                      Id INT Primary Key Identity(1,1),
                      CreateDate DATETIME NOT NULL,
                      Author nvarchar(100),
                      Body nvarchar(4000)
                    )");
            }
        }
示例#35
0
 public void pv_Create_RegistrBase(String ls_BasePath)
 {
     sql_SQL_Engine = new SqlCeEngine("Data Source='" + ls_BasePath + "';");
     sql_SQL_Engine.CreateDatabase();
     sql_SQL_Connection = new SqlCeConnection(sql_SQL_Engine.LocalConnectionString);
     sql_SQL_Connection.Open();
     sql_SQL_Command             = sql_SQL_Connection.CreateCommand();
     sql_SQL_Command.CommandText =
         "CREATE TABLE Registration(N int IDENTITY(1,1)," +
         "Login nvarchar(50)," +
         "Password nvarchar(50)," +
         "UID nvarchar(50)," +
         "Date nvarchar(50)," +
         "Name nvarchar(50)," +
         "Surname nvarchar(50)," +
         "Mail nvarchar(50)," +
         "Permission nvarchar(50)," +
         "Attribute nvarchar(50))";
     sql_SQL_Command.ExecuteNonQuery();
     sql_SQL_Connection.Close();
 }
示例#36
0
        protected override SqlCeConnection GetConnection()
        {
            DataPath     = ConfigurationService.DatabasePath;
            DatabaseName = ConfigurationService.DatabaseName;
            var password = ConfigurationService.Password;

            if (!Directory.Exists(DataPath))
            {
                Directory.CreateDirectory(DataPath);
            }

            var filename   = Path.Combine(DataPath, DatabaseName + ".db");
            var connString = string.Format(@"Data Source={0};Password={1}", filename, password);

            if (!File.Exists(filename))
            {
                var engine = new SqlCeEngine(connString);
                engine.CreateDatabase();
            }
            return(new SqlCeConnection(connString));
        }
示例#37
0
 public SqliteDB()
 {
     filePath = "DataSource=\"appDB.sdf\"; Password=\"d7a7a247-51bd-4244-81c7-2b406a23cc69\"; Max Database Size=4000;";
     engine   = new SqlCeEngine(filePath);
     if (!System.IO.Directory.Exists("images"))
     {
         System.IO.Directory.CreateDirectory("images");
     }
     if (!System.IO.File.Exists(".\\appDB.sdf"))
     {
         Console.WriteLine("DB not found. Creating DB...");
         engine.CreateDatabase();
         OpenConnection();
         GenerateTables();
     }
     else
     {
         OpenConnection();
         Console.WriteLine("DB found and connected.");
     }
 }
示例#38
0
        public bool CreateSpeedBotDb()
        {
            string connectionString;
            string fileName = "SpeedBot.sdf";
            string password = "******";

            if (File.Exists(fileName))
            {
                return(false);
            }

            connectionString = string.Format(
                "DataSource=\"{0}\"; Password='******'", fileName, password);

            SqlCeEngine en = new SqlCeEngine(connectionString);

            en.CreateDatabase();


            return(true);
        }
示例#39
0
        public MSSQLDB()
        {
            SqlCeEngine en = null;

            try
            {
                en = new SqlCeEngine(connstr);
                //en.CreateDatabase();
                //createTables();
            }

            catch (SqlCeException e)
            {
                //MessageBox.Show(e.GetBaseException().StackTrace);
                //MessageBox.Show(e.GetBaseException().Message);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.GetBaseException().Message + " " + e.GetBaseException().StackTrace);
            }
        }
示例#40
0
        private void butCompact_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string connStr = CoreEA.ConnSTR.DbConnectionString.SSCE.GetSSCEConnectionString(txtDbPath.Text,
                                                                                                txtPwd.Password, (bool)chkIsEncrypted.IsChecked);
                string targetFile = Guid.NewGuid().ToString();
                targetFile += ".sdf";

                SqlCeEngine ce       = new SqlCeEngine(connStr);
                string      connStr2 = CoreEA.ConnSTR.DbConnectionString.SSCE.GetSSCEConnectionString(targetFile,
                                                                                                      "", false);

                ce.Compact(connStr2);
                ("Compact successful to" + targetFile).Show();
            }
            catch (Exception eee)
            {
                eee.HandleMyException();
            }
        }
示例#41
0
        private static void CreateTestDb()
        {
            var en = new SqlCeEngine(ConnectionString);

            en.CreateDatabase();

            var sql = string.Format("CREATE TABLE {0} (" +
                                    "MessageId uniqueidentifier CONSTRAINT PK_MessageId PRIMARY KEY," +
                                    "Topic nvarchar(255)," +
                                    "MessageType nvarchar(32)," +
                                    "Body ntext" +
                                    ")", TableName);

            using (var cnn = new SqlCeConnection(ConnectionString))
                using (var cmd = cnn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cnn.Open();
                    cmd.ExecuteNonQuery();
                }
        }
示例#42
0
        public override void Initialize()
        {
            base.Initialize();

            string path = TestHelper.CurrentAssemblyDirectory;
            //Delete database file before continueing
            string filePath = string.Concat(path, "\\test.sdf");

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            //Create the Sql CE database
            var engine = new SqlCeEngine("Datasource=|DataDirectory|test.sdf;Flush Interval=1;");

            engine.CreateDatabase();

            _database = new Database("Datasource=|DataDirectory|test.sdf;Flush Interval=1;",
                                     "System.Data.SqlServerCe.4.0");
        }
示例#43
0
        public static IDatabase CreateInstance(String databaseName, String password)
        {
            // Create the connection string.
            String connectionString = password == null?String.Format("datasource='{0}';", databaseName) : String.Format("datasource='{0}'; ssce:database password={1};", databaseName, password);

            // Check if the file exists.
            String fullDatabasePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), databaseName);

            if (System.IO.File.Exists(fullDatabasePath))
            {
                Debug.WriteLine("File exists");
            }
            else
            {
                // Create database.
                SqlCeEngine engine = new SqlCeEngine(connectionString);
                engine.CreateDatabase();
                engine.Dispose();
            }
            return(new SqlServerCEBase(connectionString));
        }
        // Create Database in Configured Path

        internal bool createDatabase(string dbpath)
        {
            string completePath = dbpath + "\\" + Global.ROOT_DATA_FOLDER + "\\" + Global.DB_NAME_PREFIX + ".sdf";
            string dbconnstr    = "Data Source =" + completePath + "; Persist Security Info=False; " +
                                  "Password="******"; Max Database Size=2048; Max Buffer Size=2048;";

            try
            {
                if (!File.Exists(completePath))
                {
                    SqlCeEngine engine = new SqlCeEngine(dbconnstr);
                    engine.CreateDatabase();
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#45
0
        public override void Initialize()
        {
            TestHelper.SetupLog4NetForTests();
            TestHelper.InitializeContentDirectories();

            string path = TestHelper.CurrentAssemblyDirectory;

            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            //Delete database file before continueing
            string filePath = string.Concat(path, "\\test.sdf");

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            //Create the Sql CE database
            var engine = new SqlCeEngine("Datasource=|DataDirectory|test.sdf");

            engine.CreateDatabase();

            RepositoryResolver.Current = new RepositoryResolver(
                new RepositoryFactory());

            Resolution.Freeze();
            ApplicationContext.Current = new ApplicationContext(
                //assign the db context
                new DatabaseContext(new DefaultDatabaseFactory()),
                //assign the service context
                new ServiceContext(new PetaPocoUnitOfWorkProvider(), new FileUnitOfWorkProvider(), new PublishingStrategy()))
            {
                IsReady = true
            };

            SqlSyntaxContext.SqlSyntaxProvider = SqlCeSyntax.Provider;

            _database = new Database("Datasource=|DataDirectory|test.sdf",
                                     "System.Data.SqlServerCe.4.0");
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Creates SQL Server CE database using specified file path.
        /// Executes SQL script using specified script value if not null.
        /// </summary>
        /// <param name="path">
        /// Database file path.
        /// </param>
        /// <param name="createScript">
        /// Transact SQL script to execute. Optional (can be null).
        /// Provided script must conform to SQL Server CE.
        /// </param>
        public static void CreateDatabase(string path, string createScript)
        {
            Debug.Assert(path != null);

            bool dbCreated = false;

            try
            {
                // check if specified file exists
                if (File.Exists(path))
                {
                    throw new DataException(Properties.Messages.Error_DbFileExists);
                }

                // build connection string
                string connStr = DatabaseHelper.BuildSqlConnString(path, false);

                // create database
                SqlCeEngine engine = new SqlCeEngine(connStr);
                engine.CreateDatabase();
                dbCreated = true;

                // execute SQL script
                if (createScript != null)
                {
                    ExecuteScript(connStr, createScript, null);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);

                if (dbCreated)
                {
                    DeleteDatabase(path);
                }

                throw;
            }
        }
示例#47
0
        public virtual void Setup()
        {
            string connectionString = string.Format("Data Source=.\\dapperTest_{0}.sdf", Guid.NewGuid());

            string[] connectionParts = connectionString.Split(';');
            string   file            = connectionParts
                                       .ToDictionary(k => k.Split('=')[0], v => v.Split('=')[1])
                                       .Where(d => d.Key.Equals("Data Source", StringComparison.OrdinalIgnoreCase))
                                       .Select(k => k.Value).Single();

            if (File.Exists(file))
            {
                File.Delete(file);
            }

            using (SqlCeEngine ce = new SqlCeEngine(connectionString))
            {
                ce.CreateDatabase();
            }

            SqlCeConnection connection   = new SqlCeConnection(connectionString);
            var             config       = new DapperExtensionsConfiguration(typeof(AutoClassMapper <>), new List <Assembly>(), new SqlCeDialect());
            var             sqlGenerator = new SqlGeneratorImpl(config);

            Db = new Database(connection, sqlGenerator);

            var files = new List <string>
            {
                ReadScriptFile("CreateAnimalTable"),
                ReadScriptFile("CreateFooTable"),
                ReadScriptFile("CreateMultikeyTable"),
                ReadScriptFile("CreatePersonTable"),
                ReadScriptFile("CreateCarTable")
            };

            foreach (var setupFile in files)
            {
                connection.Execute(setupFile);
            }
        }
示例#48
0
        public static void LoadDatabase(string databaseName)
        {
            if (File.Exists(databaseName))
            {
                File.Delete(databaseName);
            }

            string connectionString = "Data Source=" + databaseName;

            using (SqlCeEngine ce = new SqlCeEngine(connectionString))
            {
                ce.CreateDatabase();
            }

            using (SqlCeConnection connection = GetConnection(databaseName))
            {
                using (SqlCeCommand cmd = new SqlCeCommand(ReadScriptFile("CreatePersonTable"), connection))
                {
                    cmd.ExecuteNonQuery();
                }

                using (SqlCeCommand cmd = new SqlCeCommand(ReadScriptFile("CreateMultikeyTable"), connection))
                {
                    cmd.ExecuteNonQuery();
                }

                using (SqlCeCommand cmd = new SqlCeCommand(ReadScriptFile("CreateAnimalTable"), connection))
                {
                    cmd.ExecuteNonQuery();
                }

                using (SqlCeCommand cmd = new SqlCeCommand(ReadScriptFile("CreateFooTable"), connection))
                {
                    cmd.ExecuteNonQuery();
                }

                connection.Close();
            }
        }
示例#49
0
        private void NewDatabase()
        {
            if (File.Exists(dbFileName))
            {
                File.Delete(dbFileName);
            }

            using (var engine = new SqlCeEngine(connectionString))
            {
                engine.CreateDatabase();
            }

            using (var connection = new SqlCeConnection(connectionString))
            {
                connection.Open();

                using (var command = new SqlCeCommand("CREATE TABLE Items(Id INTEGER PRIMARY KEY, Value BINARY(128))", connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
示例#50
0
 public static bool CreateNewDatabase()
 {
     try
     {
         if (!Directory.Exists(databasePath))
         {
             Directory.CreateDirectory(databasePath);
         }
         if (File.Exists(databaseFile))
         {
             File.Delete(databaseFile);
         }
         SqlCeEngine engine = new SqlCeEngine(connString);
         engine.CreateDatabase();
         return(CreateTables());
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         return(false);
     }
 }
示例#51
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            //If the file "CEDataAccess.sdf" exists, delete it.

            if (System.IO.File.Exists("\\My Documents\\CEDataAccess.sdf"))
            {
                System.IO.File.Delete("\\My Documents\\CEDataAccess.sdf");
            }

            //Create the new database.

            SqlCeEngine engine = new SqlCeEngine("Data Source = \\My Documents\\CEDataAccess.sdf");

            engine.CreateDatabase();

            //Create a connection to the new database.
            ssceconn = new SqlCeConnection("Data Source = \\My Documents\\CEDataAccess.sdf");

            //Create the createTable command on the connection.
            SqlCeCommand createTable = ssceconn.CreateCommand();

            createTable.CommandText = "Create TABLE Customer(cust_id int IDENTITY(1,1) PRIMARY KEY, f_name ntext, l_name ntext, address ntext, city ntext, state ntext, pin ntext, country ntext, phone ntext)";
            //Open the connection, execute the queries
            ssceconn.Open();
            createTable.ExecuteNonQuery();

            //Create the insertRow command on the connection.
            SqlCeCommand insertRow = ssceconn.CreateCommand();

            insertRow.CommandText = "INSERT INTO Customer(f_name, l_name, address, city, state, pin, country, phone) VALUES ('Vandana', 'Singal', '102, Sai Madhavi Enclave', 'Hyderabad', 'AP', '500016', 'India', '919866224567')";
            insertRow.ExecuteNonQuery();
            insertRow.CommandText = "INSERT INTO Customer(f_name, l_name, address, city, state, pin, country, phone) VALUES ('Rajeev', 'Agarwal', '103, Krishna Enclave', 'Hyderabad', 'AP', '500016', 'India', '919866334568')";
            insertRow.ExecuteNonQuery();
            insertRow.CommandText = "INSERT INTO Customer(f_name, l_name, address, city, state, pin, country, phone) VALUES ('Anurag', 'Rastogi', '101, Krishna Enclave', 'Hyderabad', 'AP', '500016', 'India', '9166789876')";
            insertRow.ExecuteNonQuery();
            MessageBox.Show("Database Created");
            btnDatabase.Enabled = false;
            panel1.Enabled      = true;
        }
        public override void Init(int flowCount, long flowRecordCount)
        {
            SqlCeEngine engine = new SqlCeEngine(ConnectionString);

            if (File.Exists(DatabaseFile))
            {
                File.Delete(DatabaseFile);
            }
            engine.CreateDatabase();

            connections = new IDbConnection[flowCount];
            commands    = new IDbCommand[flowCount];

            for (int i = 0; i < flowCount; i++)
            {
                IDbConnection connection = GetConnection();
                connections[i] = connection;
                commands[i]    = CreateCommand(connection);
            }

            connections[0].ExecuteNonQuery(CreateTableQuery(CollectionName));
        }
示例#53
0
        ///<summary>Creates an empty database file.</summary>
        ///<param name="filePath">The path to the file.  If the file already exists, it will be overwritten.</param>
        ///<param name="format">The format of the file.</param>
        ///<returns>A DBConnector that connects to the path.</returns>
        public static DBConnector CreateFile(string filePath, DatabaseFile format)
        {
            switch (format)
            {
            case DatabaseFile.Access:
            case DatabaseFile.Access2007:
                //OleDB can't create Access databases, so I
                //embedded empty databases in the assembly.
                //I append a dummy extension so Web Publish
                //doesn't break.
                //https://connect.microsoft.com/VisualStudio/feedback/details/808438/loading-an-access-accdb-database-breaks-ftp-web-publish
                using (var originalStream = typeof(DB).Assembly.GetManifestResourceStream("ShomreiTorah.Common.Data." + format.ToString() + format.GetExtension() + ".template"))
                    using (var file = File.Create(filePath)) {
                        originalStream.CopyTo(file);
                    }
                break;

            case DatabaseFile.Excel:
            case DatabaseFile.Excel2007:
            case DatabaseFile.Excel2007Binary:
            case DatabaseFile.Excel2007Macro:
                //It is not possible to have an empty Excel
                //file, so I just delete any existing file.
                //The file will be automatically created if
                //the client creates a table.
                File.Delete(filePath);
                break;

            case DatabaseFile.SqlCe:
                using (var engine = new SqlCeEngine(CreateSqlCeConnectionString(filePath)))
                    engine.CreateDatabase();
                break;

            default:
                break;
            }

            return(DB.OpenFile(filePath, format));
        }
示例#54
0
        private void mitemCreateDB_Click(object sender, System.EventArgs e)
        {
            if (File.Exists(strFile))
            {
                File.Delete(strFile);
            }

            SqlCeEngine dbEngine = new SqlCeEngine();

            dbEngine.LocalConnectionString = strConn;
            try
            {
                dbEngine.CreateDatabase();
            }
            catch (SqlCeException exSQL)
            {
                MessageBox.Show("Unable to create database at " +
                                strFile +
                                ". Reason:  " +
                                exSQL.Errors[0].Message);
            }
        }
示例#55
0
        private void Form1_Load(object sender, EventArgs e)
        {
            this.TopMost        = true;
            groupBox1.Location  = new Point(30, 116);
            groupBox2.Location  = new Point(30, 116);
            groupBox3.Location  = new Point(100, 116);
            groupSynth.Location = new Point(30, 116);
            this.Size           = new Size(711, 434);
            // DBPath =  "Z:\\Database\\bd_archimede.sdf";
            DBPath = Application.StartupPath + "\\bd_archimede.sdf";

            // create db if not exists
            if (!File.Exists(DBPath))
            {
                using (SqlCeEngine se = new SqlCeEngine("Data Source=" + DBPath))
                {
                    se.CreateDatabase();
                    connect_db();
                    create_table();
                    se.Dispose();
                }
            }
            else
            {
                connect_db();
                using (SqlCeCommand com = new SqlCeCommand("DELETE FROM patient", conn))
                {
                    com.ExecuteNonQuery();
                    MessageBox.Show("Base de donnée vidée !");
                }
            }

            connect_db();

            groupBox1.Visible  = false;
            groupBox2.Visible  = false;
            groupBox3.Visible  = false;
            groupSynth.Visible = false;
        }
        public ExternalLoginStore()
        {
            if (!System.IO.File.Exists(IOHelper.MapPath("~/App_Data/UmbracoIdentity.sdf")))
            {
                using (var en = new SqlCeEngine(ConnString))
                {
                    en.CreateDatabase();
                }
            }

            _db = new UmbracoDatabase(ConnString, "System.Data.SqlServerCe.4.0");
            if (!_db.TableExist("ExternalLogins"))
            {
                //unfortunately we'll get issues if we just try this because of differing sql syntax providers. In newer
                // umbraco versions we'd just use the DatabaseSchemaHelper. So in the meantime we have to just
                // do this manually and use reflection :(;
                //_db.CreateTable<ExternalLoginDto>();

                var sqlceProvider = new SqlCeSyntaxProvider();
                CreateTable(false, typeof(ExternalLoginDto), sqlceProvider);
            }
        }
示例#57
0
        static SqlCETestSuite()
        {
            if (File.Exists(FileName))
            {
                File.Delete(FileName);
            }
            var engine = new SqlCeEngine(ConnectionString);

            engine.CreateDatabase();
            using (var connection = new SqlCeConnection(ConnectionString))
            {
                connection.Open();
                connection.Execute(@"CREATE TABLE Stuff (TheId int IDENTITY(1,1) not null, Name nvarchar(100) not null, Created DateTime null) ");
                connection.Execute(@"CREATE TABLE People (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null) ");
                connection.Execute(@"CREATE TABLE Users (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, Age int not null) ");
                connection.Execute(@"CREATE TABLE Automobiles (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null) ");
                connection.Execute(@"CREATE TABLE Results (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, [Order] int not null) ");
                connection.Execute(@"CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null) ");
                connection.Execute(@"CREATE TABLE ObjectY (ObjectYId int not null, Name nvarchar(100) not null) ");
            }
            Console.WriteLine("Created database");
        }
        private void SetupSqlCe(string path, ILogger logger)
        {
            var dbName = string.Concat("Umb", Guid.NewGuid(), ".sdf");

            AppDomain.CurrentDomain.SetData("DataDirectory", path);
            var sqlCeConnectionString = $"Datasource=|DataDirectory|\\{dbName};Flush Interval=1;";

            _dbFile = Path.Combine(path, dbName);

            //only create the db one time
            if (_initDbBytes == null)
            {
                using (var engine = new SqlCeEngine(sqlCeConnectionString))
                {
                    engine.CreateDatabase();
                }

                //use the db  to create the initial schema so we can reuse in each bench
                using (_dbSqlCe = new UmbracoDatabase(
                           sqlCeConnectionString,
                           Constants.DatabaseProviders.SqlCe,
                           logger))
                {
                    var creation = new DatabaseSchemaCreation(_dbSqlCe, logger, _sqlCeSyntax);
                    creation.InitializeDatabaseSchema();
                }
                _initDbBytes = File.ReadAllBytes(_dbFile);
            }
            else
            {
                File.WriteAllBytes(_dbFile, _initDbBytes);
            }

            //create the db
            _dbSqlCe = new UmbracoDatabase(
                sqlCeConnectionString,
                Constants.DatabaseProviders.SqlCe,
                logger);
        }
示例#59
-1
        /// <summary>
        /// Create the initial database
        /// </summary>
        private void CreateDB()
        {
            var connection = new SqlCeConnection(this.path);

            try
            {
                var eng = new SqlCeEngine(this.path);
                var cleanup = new System.Threading.Tasks.Task(eng.Dispose);
                eng.CreateDatabase();
                cleanup.Start();
            }
            catch (Exception e)
            {
                EventLogging.WriteError(e);
            }

            connection.Open();
            var usersDB =
                new SqlCeCommand(
                    "CREATE TABLE Users_DB("
                    + "UserID int IDENTITY (100,1) NOT NULL UNIQUE, "
                    + "UserName nvarchar(128) NOT NULL UNIQUE, "
                    + "PassHash nvarchar(128) NOT NULL, "
                    + "Friends varbinary(5000), "
                    + "PRIMARY KEY (UserID));",
                    connection);
            usersDB.ExecuteNonQuery();
            usersDB.Dispose();
            connection.Dispose();
            connection.Close();
        }
示例#60
-1
    public SQLCEDatabase()
    {
      try
      {
        IPathManager pathManager = ServiceRegistration.Get<IPathManager>();
        string dataDirectory = pathManager.GetPath("<DATABASE>");
        string databaseFile = Path.Combine(dataDirectory, DEFAULT_DATABASE_FILE);

        int databaseSize = INITIAL_MAX_DATABASE_SIZE;
        FileInfo databaseFileInfo = new FileInfo(databaseFile);
        if (databaseFileInfo.Exists)
        {
          int bufferFileSize = (int) (databaseFileInfo.Length/(1024*1024)) + DATABASE_SIZE_BUFFER;
          if (bufferFileSize > databaseSize)
            databaseSize = bufferFileSize;
        }

        _connectionString = "Data Source='" + databaseFile + "'; Default Lock Timeout=" + LOCK_TIMEOUT + "; Max Buffer Size = " + MAX_BUFFER_SIZE + "; Max Database Size = " + databaseSize;
        SqlCeEngine engine = new SqlCeEngine(_connectionString);
        if (File.Exists(databaseFile))
          CheckUpgrade(engine);
        else
        {
          Directory.CreateDirectory(dataDirectory);
          engine.CreateDatabase();
          engine.Dispose();
        }
      }
      catch (Exception e)
      {
        ServiceRegistration.Get<ILogger>().Critical("Error establishing database connection", e);
        throw;
      }
    }