コード例 #1
0
 string UtilityConnString(TestDatabase database) {
     string connString;
     if (!string.IsNullOrEmpty(database.ConnectionString)) {
         var helper = new ConnectionStringParser(database.ConnectionString);
         helper.RemovePartByName("DatabaseName");
         helper.RemovePartByName("DBN");
         helper.RemovePartByName("DatabaseFile");
         helper.RemovePartByName("DBF");
         connString = helper.GetConnectionString();
     } else {
         string uid;
         string pwd;
         if (database.Login != null && !string.IsNullOrEmpty(database.Login.UserID)) {
             uid = database.Login.UserID;
         } else {
             uid = "dba";
         }
         if (database.Login != null && !string.IsNullOrEmpty(database.Login.Password)) {
             pwd = database.Login.Password;
         } else {
             pwd = "sql";
         }
         connString = string.Format("eng={0};uid={1};pwd={2};", database.Server, uid, pwd);
     }
     return "DBN=utility_db;" + connString;
 }
コード例 #2
0
ファイル: ErrorLogger.cs プロジェクト: scalien/scaliendb
        public void Close()
        {
            if (database == null)
                return;

            database.Close();
            database = null;
        }
コード例 #3
0
ファイル: TestTable.cs プロジェクト: mikeobrien/Gribble
 public TestTable(TestDatabase database, string tableColumnSchema, int recordCount, string tableDataColumns, string tableData)
 {
     _database = database;
     _recordCount = recordCount;
     _tableColumnSchema = tableColumnSchema;
     _tableDataColumns = tableDataColumns;
     _tableData = tableData;
 }
コード例 #4
0
 public void Drop(TestDatabase database) {
     using (var conn = DbConnection(database)) {
         conn.Open();
         try {
             DropDB(conn, database);
         } finally {
             conn.Close();
         }
     }
 }
コード例 #5
0
ファイル: ErrorLogger.cs プロジェクト: scalien/scaliendb
 public ErrorLogger(string connectionString)
 {
     try
     {
         database = new TestDatabase(connectionString);
     }
     catch (Exception e)
     {
         // ignore for now
     }
 }
コード例 #6
0
 public void Drop(TestDatabase database) {
     var connectionString = ParseConnectionString(database);
     using (var conn = database.DbConnection(connectionString, AssemblyName, TypeName)) {
         conn.Open();
         try {
             DropDB(conn, database);
         } finally {
             conn.Close();
         }
     }
 }
コード例 #7
0
 protected virtual void KillConnections(TestDatabase database)
 {
     string serverName = database.Server;
     if (string.IsNullOrEmpty(serverName))
     {
         serverName = DefaultInstance;
     }
     using (SqlConnection connection = new SqlConnection(string.Format(DefaultConnString, serverName, MasterDB)))
     {
         connection.Open();
         try
         {
             SqlCommand command = new SqlCommand("sp_who", connection);
             SqlDataReader reader = command.ExecuteReader();
             try
             {
                 int ordinal = reader.GetOrdinal("dbname");
                 while (reader.Read())
                 {
                     if (!reader.IsDBNull(ordinal) && (reader.GetString(ordinal) == database.DBName))
                     {
                         SqlConnection connection2 = new SqlConnection(connection.ConnectionString);
                         try
                         {
                             try
                             {
                                 connection2.Open();
                                 new SqlCommand("kill " + reader["spid"], connection2).ExecuteNonQuery();
                             }
                             catch
                             {
                             }
                             continue;
                         }
                         finally
                         {
                             connection2.Close();
                         }
                     }
                 }
             }
             finally
             {
                 reader.Close();
             }
         }
         finally
         {
             connection.Close();
         }
     }
 }
コード例 #8
0
        public void Restore(TestDatabase database){
            string serverName = database.Server;
            if (string.IsNullOrEmpty(serverName)){
                serverName = DefaultInstance;
            }

            Drop(database);
            using (var connection = new SqlConnection(string.Format(DefaultConnString, serverName, MasterDB))){
                connection.Open();
                if (string.IsNullOrEmpty(database.Backupfilename)){
                    using (
                        var command = new SqlCommand(string.Format(@"CREATE DATABASE [{0}]", database.DBName),
                            connection)){
                        command.ExecuteNonQuery();
                    }
                }
                else{
                    using (
                        var command =
                            new SqlCommand(
                                string.Format(
                                    @"RESTORE DATABASE [{0}] FROM DISK = '{1}' WITH REPLACE, MOVE N'{0}' TO N'{2}\{0}.mdf', MOVE N'{0}_log' TO N'{2}\{0}_log.LDF'",
                                    database.DBName, database.Backupfilename,
                                    Environment.GetEnvironmentVariable("USERPROFILE")), connection)){
                        command.ExecuteNonQuery();
                    }
                }
                connection.Close();
                bool succes = false;
                int counter = 0;
                connection.ConnectionString = string.Format(DefaultConnString, serverName, database.DBName);
                do{
                    try{
                        connection.Open();
                        succes = true;
                    }
                    catch (Exception){
                    }
                    if (succes){
                        connection.Close();
                    }
                    else{
                        Thread.Sleep(200);
                    }
                    counter++;
                } while (!succes && counter < 50);
                if (!succes){
                    connection.Open();
                }
            }
        }
コード例 #9
0
 public NetStandard_NotIncrementBulkInsert()
 {
     _context = new TestDatabase();
     ClearTable();
     _collection = new List <NotIncrementIdEntity>();
     for (var i = 0; i < 10; i++)
     {
         _collection.Add(new NotIncrementIdEntity
         {
             Id   = Helper.RandomString(10),
             Name = Helper.RandomString(10)
         });
     }
 }
コード例 #10
0
        public void BeIgnored()
        {
            using (TestDatabase test = CreateDatabase(CreateTable_FooTable, InsertIntoFooScript))
                using (IDatabase database = CreateDatabase(test))
                {
                    var ids = database.Query <Foo>()
                              .IgnoreQueryFilters()
                              .Where(p => p.Id > 1)
                              .ToList()
                              .Select(p => p.Id);

                    ids.Should().BeEquivalentTo(2, 3, 4);
                }
        }
コード例 #11
0
        public async Task Setup()
        {
            context = await TestDatabase.GetDatabaseContext();

            MockSolutionsRepository = new MockSolutionsRepository(context);

            sut = new SolutionsService(
                MockSolutionsRepository.SolutionsRepositorySuccessfulRequest.Object);

            sutFailure = new SolutionsService(
                MockSolutionsRepository.SolutionsRepositoryFailedRequest.Object);

            baseRequest = TestObjects.GetBaseRequest();
        }
コード例 #12
0
        private void NotChangeDataWhenBulkUpdateWithNoCommitCore(
            TestDatabase korm,
            Action <IDbConnection, IDbTransaction, string> action,
            Action <IDbSet <Invoice>, Action <IDbConnection, IDbTransaction, string> > dbSetAction)
        {
            using (var transaction = korm.BeginTransaction())
            {
                var dbSet = korm.Query <Invoice>().AsDbSet();

                dbSetAction.Invoke(dbSet, action);
            }

            DatabaseShouldContainInvoices(korm.ConnectionString, CreateOriginalTestData());
        }
コード例 #13
0
        IOrchestrationService CreateServiceWithTestDb(TestDatabase testDb)
        {
            var options = new SqlOrchestrationServiceSettings(testDb.ConnectionString)
            {
                CreateDatabaseIfNotExists = true,
                LoggerFactory             = LoggerFactory.Create(builder =>
                {
                    builder.SetMinimumLevel(LogLevel.Trace);
                    builder.AddProvider(this.logProvider);
                }),
            };

            return(new SqlOrchestrationService(options));
        }
コード例 #14
0
        private void ExplicitTransactionRollbackData(TestDatabase korm)
        {
            using (var transaction = korm.BeginTransaction())
            {
                var dbSet = korm.Query <Invoice>().AsDbSet();

                dbSet.Add(CreateTestData());
                dbSet.CommitChanges();

                transaction.Rollback();

                DatabaseShouldBeEmpty(korm);
            }
        }
コード例 #15
0
        private void ExplicitTransactionCommitData(TestDatabase korm)
        {
            using (var transaction = korm.BeginTransaction())
            {
                var dbSet = korm.Query <Invoice>().AsDbSet();

                dbSet.Add(CreateTestData());
                dbSet.CommitChanges();

                transaction.Commit();

                DatabaseShouldContainInvoices(korm.ConnectionString, CreateTestData());
            }
        }
コード例 #16
0
            public async Task AddCanonicalSkill_GivenNameThatAlreadyExists_UpdatesExistingSkill()
            {
                var existingSkill = InsertSkill("C#", isCanonical: false);

                using (var subject = _fixture.Create <SkillManager>())
                {
                    await subject.AddCanonicalSkillAsync("C#");

                    dynamic newCanonicalSkill = TestDatabase.QuerySingle("SELECT Id, Name, IsCanonical FROM Skills WHERE Id = @0", existingSkill.Id);
                    Assert.AreEqual(existingSkill.Id, newCanonicalSkill.Id);
                    Assert.AreEqual("C#", newCanonicalSkill.Name);
                    Assert.AreEqual(true, newCanonicalSkill.IsCanonical);
                }
            }
コード例 #17
0
 public void ResetDatabase()
 {
     //DropDatabase();
     //TestDatabase.EnsureDatabase();
     if (DatabaseExists())
     {
         TestDatabase.ResetDatabase();
     }
     else
     {
         TestDatabase.EnsureDatabase();
         TestDatabase.ResetDatabase();
     }
 }
コード例 #18
0
        public async Task InvalidateRefreshTokenDoesNotBelongToUser()
        {
            var tokenValue    = new byte[] { 0x01, 0x02, 0x03, 0x04 };
            var tokenValueStr = Convert.ToBase64String(tokenValue);

            var momentMock = MomentTestHelper.CreateMomentMock();

            using var testDb           = new TestDatabase(this.outputHelper);
            using var identityInstance = IdentityTestHelper.CreateInstance(testDb, this.outputHelper);
            using var testDbContext    = await testDb.CreateContextAsync().ConfigureAwait(true);

            var manager = new AuthManager(
                identityInstance.UserManager,
                testDbContext,
                momentMock.Object);

            var user = await identityInstance.CreateUserAsync("someone").ConfigureAwait(true);

            var user2 = await identityInstance.CreateUserAsync("someone1").ConfigureAwait(true);

            var claimsPrincipal = IdentityTestHelper.CreateClaimsPrincipalForUserId(user.Id);

            var tokenEntity = new UserRefreshToken
            {
                TokenValue          = tokenValue,
                IpAddress           = "1.2.3",
                UserAgent           = "chrome",
                IsInvalidated       = false,
                SubjectUserId       = user2.Id,
                GeneratedAtUtc      = momentMock.Object.UtcNow,
                ExpiresAtUtc        = momentMock.Object.UtcNow.AddDays(1),
                ClientApplicationId = identityInstance.ClientId,
            };

            testDbContext.UserRefreshTokens.Add(tokenEntity);
            await testDbContext.SaveChangesAsync().ConfigureAwait(true);

            var result = await manager.InvalidateRefreshTokenAsync(
                claimsPrincipal,
                tokenValueStr).ConfigureAwait(true);

            result.Should().BeFalse(because: "the token should not have been found and invalidated");

            tokenEntity = await testDbContext.UserRefreshTokens
                          .FindAsync(tokenValue)
                          .ConfigureAwait(true);

            tokenEntity.IsInvalidated.Should().BeFalse(
                because: "the token was not invalidated");
        }
コード例 #19
0
ファイル: TimestampFixture.cs プロジェクト: aTiKhan/nmemory
        public void TimestampChangedOnInsert()
        {
            TestDatabase db = new TestDatabase();

            TimestampEntity entity = new TimestampEntity()
            {
                Id = 1
            };
            Timestamp timestamp = entity.Timestamp;

            db.TimestampEntities.Insert(entity);

            Assert.AreNotEqual(timestamp, db.TimestampEntities.Single(t => t.Id == 1).Timestamp);
        }
コード例 #20
0
            public async Task RemoveSkillFromConsultant_GivenCanonicalSkillTiedToNoOtherConsultants_DoesNoRemoveTheSkill()
            {
                int consultantId = InsertUser(SampleData.Consultant());
                var skill        = InsertSkill("C#", true);

                InsertConsultantSkill(consultantId, skill.Id);
                var subject = _fixture.Create <SkillManager>();

                await subject.RemoveSkillFromConsultantAsync(consultantId, skill.Id);

                int skillCount = (int)TestDatabase.QueryValue("SELECT COUNT(*) FROM Skills WHERE Id = @0", skill.Id);

                Assert.AreEqual(1, skillCount);
            }
コード例 #21
0
        public void QueryableRewriter_ContainsNonGenericMethod()
        {
            TestDatabase db         = new TestDatabase();
            Expression   expression = CreateExpression(
                () => db.Groups.Select(g => string.Concat("Name: ", g.Name)));

            Expression expectedExpression = expression;

            IExpressionRewriter rewriter = new QueryableRewriter();

            expression = rewriter.Rewrite(expression);

            Assert.AreEqual(expectedExpression.ToString(), expression.ToString());
        }
コード例 #22
0
        public async Task SendMessageAsync_ShouldBeFalse_IfNotConnected()
        {
            //Arrange
            var message = "Message1";
            var user    = await TestDatabase.Instance().ChatUsers.FirstAsync(u => u.Name == "Usuario3");

            await _chatClient.LoginAsync(user.Name, user.Password);

            //Act
            var result = await _chatClient.SendMessageAsync(message);

            //Assert
            result.Should().BeFalse();
        }
        private static async Task CleanupTestDataAsync(TestDatabase db)
        {
            using (var session = db.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    await session.DeleteAsync("from PersistedGrant pg");

                    await session.DeleteAsync("from DeviceFlowCodes c");

                    await tx.CommitAsync();
                }
            }
        }
コード例 #24
0
        public void WillPauseAndSetErrorStateWhenMainTableFails()
        {
            var settings = new TestSettings();
            var db       = new TestDatabase(settings, new PopulatedTable(), new PopulatedEventTable());

            db.Setup();
            try
            {
                var connector = CreateConnector();

                connector.ResetConnector("WillPauseAndSetErrorStateWhenIncrementalFails");
                var configuration = GetTestConfiguration(
                    "WillPauseAndSetErrorStateWhenIncrementalFails",
                    settings.TestSqlDatabaseConnection.ToString(),
                    PopulatedTable.TableName,
                    new List <TableDetail>(),
                    new List <EventTable>()
                {
                    new EventTable()
                    {
                        EventSequenceColumnName = "Id",
                        MainTableIdColumnName   = "Name",
                        EventTypeColumnName     = PopulatedEventTable.EventTypeColumnName,
                        DeleteEventTypeValue    = "delete",
                        TableName = PopulatedEventTable.TableName
                    }
                });
                configuration.BatchSize = 1;
                Action execute = () => connector.ExecuteFetch(configuration);
                execute.Invoke(); //init should work fine
                var state = new ConnectorStateBase(_stateService.LoadState(configuration.JobName));
                state.State.Should().Be(JobState.IncrementalCrawling);

                //We change the name of the table to something that does not exist
                configuration.MainTable.TableName = "I_dont exist";
                execute.Should().Throw <SqlException>("The main table name does not exist");
                state = new ConnectorStateBase(_stateService.LoadState(configuration.JobName));
                state.State.Should().Be(JobState.Error, "Should be in error state since the Main table doesen't exist");

                //Invoking it a third time will make it revert to the last working state (IncrementalCrawling) just to
                //yet again fail to read the main table and go back to Error
                execute.Should().Throw <SqlException>("The main table name still does not exist");
                state = new ConnectorStateBase(_stateService.LoadState(configuration.JobName));
                state.State.Should().Be(JobState.Error);
            }
            finally
            {
                db.Destroy();
            }
        }
コード例 #25
0
        public async Task Should_Retrieve_Null_If_DeviceCode_Does_Not_Exist(TestDatabase testDb)
        {
            var loggerMock = new Mock <ILogger <DeviceFlowStore> >();

            using (var session = testDb.SessionFactory.OpenSession())
            {
                var store = new DeviceFlowStore(session, new PersistentGrantSerializer(), loggerMock.Object);
                var code  = await store.FindByDeviceCodeAsync($"device_{Guid.NewGuid()}");

                code.Should().BeNull();
            }

            await CleanupTestDataAsync(testDb);
        }
コード例 #26
0
        public void Delete_Object()
        {
            using (var db = new TestDatabase(DbInfo.Name))
            {
                db.BeginTransaction();
                var customer = db.SingleById <Customer>("DEMO");
                int deleted  = db.Delete(customer);
                db.CompleteTransaction();

                Assert.That(deleted, Is.EqualTo(1));
            }

            AssertIsDeleted("DEMO");
        }
コード例 #27
0
        public ActionResult Registration([Bind(Exclude = "verify_email, activation_code")] User user)
        {
            bool   status  = false;
            string message = "";

            // Model validation
            if (ModelState.IsValid)
            {
                #region Email already exists
                var doesExist = DoesEmailExist(user.email_ID);
                if (doesExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exists");
                    return(View(user));
                }
                #endregion

                #region  Generate code
                user.activation_code = Guid.NewGuid();
                #endregion

                #region Password Hashing
                user.user_pass    = Encrypt.Hash(user.user_pass);
                user.confirm_pass = Encrypt.Hash(user.confirm_pass);
                #endregion

                user.verify_email = false;

                #region Save new user data to DB
                using (TestDatabase db = new TestDatabase())
                {
                    db.Users.Add(user);
                    db.SaveChanges();

                    // Send verification email
                    SendVerifyEmailLink(user.email_ID, user.activation_code.ToString());
                    message = "Registration complete. A verification email has been sent to " + user.email_ID;
                    status  = true;
                }
                #endregion
            }
            else
            {
                message = "Invalid request";
            }
            ViewBag.Message = message;
            ViewBag.Status  = status;
            return(View(user));
        }
コード例 #28
0
        public void WillIncludeBothAddsAndDeletesUsingEventTable()
        {
            var settings = new TestSettings();

            var eventTable = new MixedPopulatedEventTable();
            var db         = new TestDatabase(settings, new MixedPopulatedTable(), eventTable);

            db.Setup();
            try
            {
                var connector = CreateConnector();
                connector.ResetConnector("WillIncludeBothAddsAndDeletesUsingEventTable");
                var configuration = GetTestConfiguration(
                    "WillIncludeBothAddsAndDeletesUsingEventTable",
                    settings.TestSqlDatabaseConnection.ToString(),
                    MixedPopulatedTable.TableName,
                    new List <TableDetail>(),
                    new List <EventTable>()
                {
                    new EventTable()
                    {
                        EventSequenceColumnName = "Id",
                        MainTableIdColumnName   = "Name",
                        EventTypeColumnName     = MixedPopulatedEventTable.EventTypeColumnName,
                        DeleteEventTypeValue    = "delete",
                        TableName = MixedPopulatedEventTable.TableName
                    }
                });
                var sourceChanges = connector.ExecuteFetch(configuration);
                sourceChanges.Adds.Count.Should().Be(6);
                sourceChanges.Deletes.Count.Should().Be(0);

                sourceChanges = connector.ExecuteFetch(configuration);
                sourceChanges.Adds.Count.Should().Be(0);

                eventTable.AddEvent("first", "add");
                eventTable.AddEvent("second", "delete");
                eventTable.AddEvent("third", "add");
                eventTable.AddEvent("fourth", "delete");
                db.UpdateDbObject(eventTable);
                sourceChanges = connector.ExecuteFetch(configuration);
                sourceChanges.Adds.Count.Should().Be(2, "Should've found two adds since we added two to the event table");
                sourceChanges.Deletes.Count.Should().Be(2, "Should've found two deletes since two was added to the event table");
            }
            finally
            {
                db.Destroy();
            }
        }
コード例 #29
0
        public async Task Setup()
        {
            context = await TestDatabase.GetDatabaseContext();

            mockUsersService       = new MockUsersService(context);
            mockAppsService        = new MockAppsService(context);
            mockWebHostEnvironment = new Mock <IWebHostEnvironment>();

            baseRequest = new BaseRequest();

            updateUserRequest = new UpdateUserRequest()
            {
                UserName    = "******",
                FirstName   = "FirstName",
                LastName    = "LastName",
                NickName    = "MyNickname",
                Email       = "*****@*****.**",
                License     = TestObjects.GetLicense(),
                RequestorId = 1,
                Paginator   = new Paginator()
            };

            updatePasswordRequest = new UpdatePasswordRequest()
            {
                UserId      = 1,
                NewPassword = "******"
            };

            updateUserRoleRequest = new UpdateUserRoleRequest()
            {
                RoleIds = new List <int>()
                {
                    3
                },
                License     = TestObjects.GetLicense(),
                RequestorId = 1,
                Paginator   = new Paginator()
            };

            sutSuccess = new UsersController(
                mockUsersService.UsersServiceSuccessfulRequest.Object,
                mockAppsService.AppsServiceSuccessfulRequest.Object,
                mockWebHostEnvironment.Object);

            sutFailure = new UsersController(
                mockUsersService.UsersServiceFailedRequest.Object,
                mockAppsService.AppsServiceSuccessfulRequest.Object,
                mockWebHostEnvironment.Object);
        }
コード例 #30
0
        public void CreateColumn()
        {
            var database  = new TestDatabase();
            var context   = new MigrationContext(database, Logger);
            var migration = new AddPropertyTypeGroupColumns(context);

            var dtos = new[]
            {
                new PropertyTypeGroupDto()
                {
                    Id = 0, Text = "Content"
                },
                new PropertyTypeGroupDto()
                {
                    Id = 1, Text = "Content"
                },
                new PropertyTypeGroupDto()
                {
                    Id = 2, Text = "Settings"
                },
                new PropertyTypeGroupDto()
                {
                    Id = 3, Text = "Content "
                },                                                        // The trailing space is intentional
                new PropertyTypeGroupDto()
                {
                    Id = 4, Text = "SEO/OpenGraph"
                },
                new PropertyTypeGroupDto()
                {
                    Id = 5, Text = "Site defaults"
                }
            };

            var populatedDtos = migration.PopulateAliases(dtos)
                                .OrderBy(x => x.Id) // The populated DTOs can be returned in a different order
                                .ToArray();

            // All DTOs should be returned and Id and Text should be unaltered
            Assert.That(dtos.Select(x => (x.Id, x.Text)), Is.EquivalentTo(populatedDtos.Select(x => (x.Id, x.Text))));

            // Check populated aliases
            Assert.That(populatedDtos[0].Alias, Is.EqualTo("content"));
            Assert.That(populatedDtos[1].Alias, Is.EqualTo("content"));
            Assert.That(populatedDtos[2].Alias, Is.EqualTo("settings"));
            Assert.That(populatedDtos[3].Alias, Is.EqualTo("content2"));
            Assert.That(populatedDtos[4].Alias, Is.EqualTo("sEOOpenGraph"));
            Assert.That(populatedDtos[5].Alias, Is.EqualTo("siteDefaults"));
        }
コード例 #31
0
 public void Restore(TestDatabase database) {
     var connectionString = ParseConnectionString(database);
     using (var conn = database.DbConnection(connectionString, AssemblyName,TypeName)) {
         conn.Open();
         try {
             DropDB(conn, database);
             using (IDbCommand c = conn.CreateCommand()) {
                 string dbFileName = database.DBSourceLocation.Replace(@"\", @"\\");
                 if (string.IsNullOrEmpty(database.Backupfilename)) {
                     c.CommandText = string.Format("Create Database '{0}'", dbFileName);
                     c.ExecuteNonQuery();
                 } else {
                     if (
                         GetExtension(database.Backupfilename)
                             .Equals(".db", StringComparison.OrdinalIgnoreCase) ||
                         File.Exists(database.Backupfilename + ".db")) {
                         string baseSourceFileName = database.Backupfilename;
                         string baseDestFileName = database.DBSourceLocation;
                         if (GetExtension(baseSourceFileName)
                                 .Equals(".db", StringComparison.OrdinalIgnoreCase)) {
                             baseSourceFileName = Path.ChangeExtension(baseSourceFileName, null);
                         }
                         if (GetExtension(baseDestFileName)
                                 .Equals(".db", StringComparison.OrdinalIgnoreCase)) {
                             baseDestFileName = Path.ChangeExtension(baseDestFileName, null);
                         }
                         File.Copy(baseSourceFileName + ".db", baseDestFileName + ".db", true);
                         if (File.Exists(baseSourceFileName + ".log")) {
                             File.Copy(baseSourceFileName + ".log", baseDestFileName + ".log", true);
                         }
                     } else {
                         string backupFileName = database.Backupfilename.Replace(@"\", @"\\");
                         if (GetExtension(database.Backupfilename)
                                 .Equals(".1", StringComparison.OrdinalIgnoreCase)) {
                             backupFileName = Path.ChangeExtension(backupFileName, null);
                         }
                         c.CommandText = string.Format("RESTORE DATABASE '{0}' FROM '{1}' HISTORY OFF",
                                                       dbFileName, backupFileName);
                         c.ExecuteNonQuery();
                     }
                 }
                 c.CommandText = string.Format("START DATABASE '{0}' AS [{1}]", dbFileName, database.DBName);
                 c.ExecuteNonQuery();
             }
         } finally {
             conn.Close();
         }
     }
 }
コード例 #32
0
        private void ExplicitTransactionCommitAfterBulkInsert(TestDatabase database)
        {
            using (var korm = new Database(database.ConnectionString))
                using (var transaction = korm.BeginTransaction())
                {
                    var dbSet = korm.Query <Invoice>().AsDbSet();

                    dbSet.Add(CreateTestData());
                    dbSet.BulkInsert();

                    transaction.Commit();
                }

            DatabaseShouldContainInvoices(database.ConnectionString, CreateTestData());
        }
コード例 #33
0
        public void TransactionScope()
        {
            TestDatabase database = new TestDatabase();

            using (TransactionScope tran = new TransactionScope())
            {
                database.Members.Insert(new Member {
                    Id = "A"
                });
                tran.Complete();
            }

            Assert.AreEqual(database.Members.Count, 1);
            Assert.IsTrue(database.Members.Any(m => m.Id == "A"));
        }
コード例 #34
0
            public async Task RemoveCanonicalSkill_GivenCanonicalSkillInUse_SetsIsCanonicalToFalse()
            {
                int userId         = InsertUser(SampleData.Consultant());
                var canonicalSkill = InsertSkill("C#", true);

                InsertConsultantSkill(userId, canonicalSkill.Id);

                using (var subject = _fixture.Create <SkillManager>())
                {
                    await subject.RemoveCanonicalSkillAsync(canonicalSkill.Id);

                    bool isCanonical = TestDatabase.QueryValue("SELECT IsCanonical FROM Skills WHERE Id = @0", canonicalSkill.Id);
                    Assert.IsFalse(isCanonical);
                }
            }
コード例 #35
0
        private void ExplicitTransactionCommit(TestDatabase database)
        {
            using (var korm = new Database(database.ConnectionString, SqlServerDataHelper.ClientId))
                using (var transaction = korm.BeginTransaction())
                {
                    var dbSet = korm.Query <Invoice>().AsDbSet();

                    dbSet.Add(CreateTestData());
                    dbSet.CommitChanges();

                    transaction.Commit();

                    DatabaseShouldContainInvoices(database.ConnectionString, CreateTestData());
                }
        }
コード例 #36
0
        public async Task Should_Not_Retrieve_Non_Existing_Client(TestDatabase testDb)
        {
            Client requestedClient;
            var    loggerMock = new Mock <ILogger <ClientStore> >();

            using (var session = testDb.OpenSession())
            {
                var store = new ClientStore(session, loggerMock.Object);
                requestedClient = await store.FindClientByIdAsync("not_existing_client");
            }

            requestedClient.Should().BeNull();

            await CleanupTestDataAsync(testDb);
        }
コード例 #37
0
        public async Task Setup()
        {
            context = await TestDatabase.GetDatabaseContext();

            mockAppsService = new MockAppsService(context);

            baseRequest = new BaseRequest();

            appRequest = TestObjects.GetAppRequest();

            sutSuccess            = new AppsController(mockAppsService.AppsServiceSuccessfulRequest.Object);
            sutFailure            = new AppsController(mockAppsService.AppsServiceFailedRequest.Object);
            sutInvalid            = new AppsController(mockAppsService.AppsServiceInvalidRequest.Object);
            sutPromoteUserFailure = new AppsController(mockAppsService.AppsServicePromoteUserFailsRequest.Object);
        }
コード例 #38
0
                public PacificTimeZone(TestDatabase database)
                {
                    _database = database;
                    var offset      = TimeSpan.FromHours(8);
                    var dateTimeNow = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
                    var now         = new DateTimeOffset(dateTimeNow, offset);

                    _input = new TestEntity
                    {
                        Id             = Guid.NewGuid().ToString(),
                        DateTimeOffset = now
                    };

                    _database.TestEntities.UpsertAsync(_input).GetAwaiter().GetResult();
                }
コード例 #39
0
        private static HttpContextAccessor CreateHttpContextAccessor(TestDatabase testDb)
        {
            var ctx  = new DefaultHttpContext();
            var svcs = new ServiceCollection();

            svcs.AddScoped(provider => testDb.OpenStatelessSession());
            ctx.RequestServices = svcs.BuildServiceProvider();

            var ctxAccessor = new HttpContextAccessor()
            {
                HttpContext = ctx
            };

            return(ctxAccessor);
        }
コード例 #40
0
 public void Drop(TestDatabase database) {
     KillConnections(database);
     string serverName = database.Server;
     if (string.IsNullOrEmpty(serverName)) {
         serverName = DefaultInstance;
     }
     using (var connection = new SqlConnection(string.Format(DefaultConnString, serverName, MasterDB))) {
         connection.Open();
         connection.Open();
         using (SqlCommand command = new SqlCommand(string.Format("IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'{0}') DROP DATABASE [{0}]", database.DBName), connection))
         {
             command.ExecuteNonQuery();
         }
         connection.Close();
     }
 }
コード例 #41
0
        public void Drop(TestDatabase database){

            using (var conn = database.DbConnection(GetConnectionString(database),AssemblyName, TypeName)) {
                conn.Open();
                try {
                    using (var dbCommand = conn.CreateCommand()) {
                        dbCommand.CommandText = "DROP DATABASE IF EXISTS " + database.DBName;
                        dbCommand.ExecuteNonQuery();
                    }
                }
                finally {
                    conn.Close();
                }
            }

        }
 public void Setup()
 {
     _connection = new SqlConnection(_connectionString.FormattedConnectionString);
     _connection.Open();
     _database = TestDatabase.Init(_connection,30);
 }
コード例 #43
0
 public TestScoreRepositoryTest(TestDatabase<DomainContext> testDatabase)
 {
     _testDatabase = testDatabase;
 }
コード例 #44
0
ファイル: TableTests.cs プロジェクト: mikeobrien/Gribble
        public void Setup()
        {
            const int records = 10;
            const string columnSchena = "[id] [int] IDENTITY(1,1) NOT NULL, [name] [nvarchar] (500) NULL, " +
                "[hide] [bit] NULL, [timestamp] [datetime] NULL, [upc] [uniqueidentifier] DEFAULT NEWID(), " +
                "[code] [int] DEFAULT 5";
            const string dataColumns = "name, hide, [timestamp]";
            const string data = "'oh hai', 0, GETDATE()";

            _database = new TestDatabase();
            _database.AddTable(columnSchena, records, dataColumns, data);
            _database.AddTable(columnSchena, records, dataColumns, data);
            _database.AddTable("[id] [int] IDENTITY(1,1) NOT NULL, [name] [nvarchar] (500) NULL, " +
                "[hide] [bit] NULL, [upc] [uniqueidentifier] DEFAULT NEWID(), [code] [int] DEFAULT 5",
                5, "name, hide", "'oh hai yo', 1");
            _database.AddTable("[id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar] (500) NULL, " +
                "[hide] [bit] NULL, [upc] [uniqueidentifier] DEFAULT NEWID(), [code] [int] DEFAULT 5",
                5, "name, hide", "'oh hai yo', 1");

            _database.SetUp();

            _identityTable1 = Table<IdentityEntity>.Create(_database.Connection, _database.FirstTable.Name);
            _identityTable2 = Table<IdentityEntity>.Create(_database.Connection, _database.ThirdTable.Name);
            _identityTable3 = Table<IdentityEntity>.Create(_database.Connection, _database.FourthTable.Name);

            _database.CreateTables();
        }
コード例 #45
0
 void DropDB(IDbConnection conn, TestDatabase database) {
     using (IDbCommand c = conn.CreateCommand()) {
         c.CommandText = string.Format("STOP DATABASE [{0}] UNCONDITIONALLY", database.DBName);
         try {
             c.ExecuteNonQuery();
         } catch (Exception) {
         }
         if (!string.IsNullOrEmpty(database.DBSourceLocation)) {
             c.CommandText = string.Format("DROP DATABASE '{0}'", database.DBSourceLocation.Replace(@"\", @"\\"));
             try {
                 c.ExecuteNonQuery();
             } catch (Exception) {
             }
         }
     }
 }
コード例 #46
0
 IDbConnection DbConnection(TestDatabase database) {
     var dbConnection = ReflectConnectionHelper.GetConnection("iAnywhere.Data.SQLAnywhere",
                                                              "iAnywhere.Data.SQLAnywhere.SAConnection",
                                                              UtilityConnString(database));
     return dbConnection;
 }
コード例 #47
0
 public ClassGroupRepositoryTest(TestDatabase<DomainContext> testDatabase)
 {
     _testDatabase = testDatabase;
 }
コード例 #48
0
ファイル: TestTable.cs プロジェクト: mikeobrien/Gribble
 public TestTable(TestDatabase database, string tableColumnSchema)
 {
     _database = database;
     _tableColumnSchema = tableColumnSchema;
 }
コード例 #49
0
 public CourseRepositoryTest(TestDatabase<DomainContext> testDatabase)
 {
     _testDatabase = testDatabase;
 }
コード例 #50
0
 public void Restore(TestDatabase database) {
     File.Copy(database.Backupfilename, database.DBSourceLocation, true);
 }
コード例 #51
0
 protected virtual string GetConnectionString(TestDatabase database) {
     if ((database.Login != null) && !string.IsNullOrEmpty(database.Login.UserID)) {
         return string.Format("Server={0};Uid={1};password={2}",database.Server,database.Login.UserID,database.Login.Password );
     }
     return string.Format("Server={0};IntegratedSecurity=yes;Uid=auth_windows",database.Server );
 }
コード例 #52
0
 public void Drop(TestDatabase database) {
     try {
         File.Delete(database.DBSourceLocation);
     } catch (Exception) {
     }
 }
コード例 #53
0
 public SkillRepositoryTest(TestDatabase<DomainContext> testDatabase)
 {
     _testDatabase = testDatabase;
 }
コード例 #54
0
 public void Restore(TestDatabase database){
     throw new NotImplementedException();
 }