Example #1
0
        protected void CompleteRename(object sender, string text)
        {
            var control = sender as FrameworkElement;

            if (control != null && control.DataContext is HierarchicalViewModelBase)
            {
                var selected = control.DataContext as HierarchicalViewModelBase;


                DatabaseCommand command = null;
                if (selected is FavoriteViewModel <T> )
                {
                    var vm = selected as FavoriteViewModel <T>;
                    if (vm.IsGroup)
                    {
                        vm.GroupName = text;
                        command      = new RenameFavoriteGroupCommand(vm.Model);
                    }
                    else
                    {
                        command = Provider.RenameFavorite(vm, text);
                    }
                }
                else if (selected is V)
                {
                    command = Provider.RenameViewModel(selected as V, text);
                }

                if (command != null)
                {
                    RegisterPendingChange(command);
                }
            }
        }
        public void ExecuteScalarWithAnonymousParameters_Test()
        {
            using (var cmd = new DatabaseCommand(_connection))
            {
                cmd.Log         = Console.WriteLine;
                cmd.CommandText = @" SELECT ENAME 
                                       FROM EMP 
                                      WHERE EMPNO = @EmpNo 
                                        AND HIREDATE = @HireDate 
                                        AND JOB = @Job 
                                        AND 1 = @NotDeleted";

                cmd.AddParameter("@EMPNO", 1234);                            // Parameter in Upper Case
                cmd.AddParameter("HireDate", new DateTime(1980, 1, 1));      // Parameter without @
                cmd.AddParameter("@Job", "FAKE");                            // Parameter in normal mode
                cmd.AddParameter("@NotDeleted", true);                       // Parameter not replaced

                // Replace previous values wiht these new propery values
                cmd.AddParameter(new
                {
                    EmpNo    = 7369,
                    HireDate = new DateTime(1980, 12, 17),
                    Job      = "CLERK"
                });

                object data = cmd.ExecuteScalar();

                Assert.AreEqual("SMITH", data);
            }
        }
        public void Should_Contain_The_Connection_String()
        {
            // Arrange
            const string sql = @"
CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            string connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString].ConnectionString;

            var dbConnection = Sequelocity.CreateDbConnection( connectionString, "System.Data.SQLite" );

            new DatabaseCommand( dbConnection )
                .SetCommandText( sql )
                .ExecuteNonQuery( true );

            var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };

            var databaseCommand = new DatabaseCommand( dbConnection )
                .GenerateInsertForSQLite( customer )
                .GenerateInsertForSQLite( customer2 );

            // Act
            var debugCommandText = databaseCommand.DbCommand.GetDebugCommandText();

            // Visual Assertion
            Trace.WriteLine( debugCommandText );
            
            // Assert
            Assert.That( debugCommandText.Contains( connectionString ) );
        }
Example #4
0
        static void Main(string[] args)
        {
            try
            {
                Config.Settings = Config.LoadFromExecutablePath();
                VerifyConnectionString();

                DatabaseCommand command = DatabaseCommand.Parse(args);
                Log.i(tag, command.Description());
                System.Console.WriteLine("Using: " + Config.Settings.ConnectionString);
                Stopwatch sw = new Stopwatch();
                sw.Start();
                command.Execute();
                var totalSeconds = sw.Elapsed.TotalSeconds;
                if (totalSeconds > 5)
                {
                    Log.w(tag, "Wasted " + TimeSpanString.ToString(sw.Elapsed) + " on: " + command.Description());
                }
            }
            catch (Exception caught)
            {
                System.Console.WriteLine(caught.Message);
                Log.e(tag, caught);
                Environment.Exit(1);
            }
            finally
            {
                Log.Flush();
            }
        }
Example #5
0
 public int Insert(DataAspect aspect, IEnumerable <AspectMemberValue> values, out object identityValue)
 {
     using (IDbConnection conn = _dialect.CreateConnection(_ConnectionString))
     {
         conn.Open();
         try
         {
             bool            hasIdentity;
             DatabaseCommand cmd = _dialect.CreateInsert(aspect, values, out hasIdentity);
             if (hasIdentity)
             {
                 identityValue = cmd.ExecuteScalar(conn);
                 return(1);
             }
             else
             {
                 identityValue = null;
                 return(cmd.ExecuteNonQuery(conn));
             }
         }
         finally
         {
             conn.Close();
         }
     }
 }
 public void RegisterPendingChange(DatabaseCommand command)
 {
     WithChangeContainer(window => {
         window.RegisterPendingChange(command, this);
     });
     RaiseChangeRegistered(command);
 }
        private void DeleteTypeDataFromOwner(TypeDataOwnerInfo ownerInfo)
        {
            DatabaseCommand command = null;

            switch (_type)
            {
            case "trait":
                command = new DeleteTraitFromOwnerCommand(ownerInfo.ObjectID.Value);
                break;

            case "note":
                command = new DeleteNoteFromOwnerCommand(ownerInfo.ObjectID.Value);
                break;

            default:
                throw new NotImplementedException("Deleting type data for type: " + _type + " is currently unsupported!");
            }

            if (command != null)
            {
                var model = lvwValues.ItemsSource as ObservableCollection <TypeDataOwnerInfo>;
                if (model != null)
                {
                    model.Remove(ownerInfo);
                    RegisterPendingChange(command);
                }
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            var settings = ConfigurationManager.ConnectionStrings["TestDB"];
            var cmd = new DatabaseCommand(settings.ProviderName, settings.ConnectionString, "[dbo].[GetContacts]");
            var allContacts = cmd.GetRecords(MapContact);

            Console.WriteLine("Listing all contacts...");
            foreach (var contact in allContacts)
            {
                OutputContact(contact);
            }

            while (true)
            {
                Console.WriteLine();
                Console.Write("Enter a contact ID (ctrl-c to exit): ");
                var id = Console.ReadLine();

                // try and load the contact...
                cmd.Parameters = new { id };
                var result = cmd.GetRecord(MapContact);
                if (result == null)
                    Console.WriteLine($"Contact with ID of {id} not found in the database!");
                else
                    OutputContact(cmd.GetRecord(MapContact));
                Thread.Sleep(1000);
            }
        }
Example #9
0
 public int ExecuteNonQuery(DatabaseCommand command)
 {
     using (var com = CreateCommand(command))
     {
         return(com.ExecuteNonQuery());
     }
 }
        public void Should_Return_The_Last_Inserted_Ids()
        {
            // Arrange
            const string sql = @"
CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString );

            new DatabaseCommand( dbConnection )
                .SetCommandText( sql )
                .ExecuteNonQuery( true );

            var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
            var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
            var list = new List<Customer> { customer1, customer2, customer3 };
            
            // Act
            var customerIds = new DatabaseCommand( dbConnection )
                .GenerateInsertsForSQLite( list )
                .ExecuteToList<long>();

            // Assert
            Assert.That( customerIds.Count == 3 );
            Assert.That( customerIds[0] == 1 );
            Assert.That( customerIds[1] == 2 );
            Assert.That( customerIds[2] == 3 );
        }
Example #11
0
 protected void RegisterUniquePendingChange(DatabaseCommand command)
 {
     var changeContainer = FindChangeContainer();
     if (changeContainer != null) {
         changeContainer.RegisterUniquePendingChange(command, this);
     }
 }
Example #12
0
 public object ExecuteScalar(DatabaseCommand command)
 {
     using (var com = CreateCommand(command))
     {
         return(com.ExecuteScalar());
     }
 }
Example #13
0
        public void UpdateTagAfterExecution_Test()
        {
            using (var cmd = new DatabaseCommand(_connection))
            {
                cmd.Log = Console.WriteLine;

                // Tag 1
                cmd.TagWith("Tag1");
                cmd.CommandText = "SELECT * FROM EMP";

                cmd.ActionBeforeExecution = (query) =>
                {
                    Assert.AreEqual($"Tag1", query.Tags.First());
                    Assert.AreEqual($"SELECT * FROM EMP", query.CommandText);
                    Assert.AreEqual($"-- Tag1{NEW_LINE}SELECT * FROM EMP", query.Formatted.CommandAsText);
                };

                cmd.ExecuteNonQuery();

                // Tag 2
                cmd.TagWith("Tag2");
                cmd.CommandText = "SELECT * FROM EMP";

                cmd.ActionBeforeExecution = (query) =>
                {
                    Assert.AreEqual($"Tag1", query.Tags.First());
                    Assert.AreEqual($"SELECT * FROM EMP", query.CommandText);
                    Assert.AreEqual($"-- Tag1{NEW_LINE}-- Tag2{NEW_LINE}SELECT * FROM EMP", query.Formatted.CommandAsText);
                };

                cmd.ExecuteNonQuery();
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            var settings    = ConfigurationManager.ConnectionStrings["TestDB"];
            var cmd         = new DatabaseCommand(settings.ProviderName, settings.ConnectionString, "[dbo].[GetContacts]");
            var allContacts = cmd.GetRecords(MapContact);

            Console.WriteLine("Listing all contacts...");
            foreach (var contact in allContacts)
            {
                OutputContact(contact);
            }

            while (true)
            {
                Console.WriteLine();
                Console.Write("Enter a contact ID (ctrl-c to exit): ");
                var id = Console.ReadLine();

                // try and load the contact...
                cmd.Parameters = new { id };
                var result = cmd.GetRecord(MapContact);
                if (result == null)
                {
                    Console.WriteLine($"Contact with ID of {id} not found in the database!");
                }
                else
                {
                    OutputContact(cmd.GetRecord(MapContact));
                }
                Thread.Sleep(1000);
            }
        }
Example #15
0
            public StudioSecurityList(StudioEntityRegistry registry)
                : base(registry.Storage)
            {
                _registry = registry;

                var database = (Database)registry.Storage;

                var readAllByUnderlyingSecurityId = Query
                                                    .Select(Schema)
                                                    .From(Schema)
                                                    .Where()
                                                    .Equals(Schema.Fields["UnderlyingSecurityId"])
                                                    .And()
                                                    .OpenBracket()
                                                    .IsParamNull(Schema.Fields["ExpiryDate"])
                                                    .Or()
                                                    .Equals(Schema.Fields["ExpiryDate"])
                                                    .CloseBracket();

                _readAllByUnderlyingSecurityId = database.GetCommand(readAllByUnderlyingSecurityId, Schema, new FieldList(new[] { Schema.Fields["UnderlyingSecurityId"], Schema.Fields["ExpiryDate"] }), new FieldList());

                var readSecurityIds = Query
                                      .Execute("SELECT group_concat(Id, ',') FROM Security");

                _readSecurityIds = database.GetCommand(readSecurityIds, null, new FieldList(), new FieldList());
            }
        private static string AddPGLocksFilterParametersAndGetFilterExpression(DatabaseCommand command, PostgresAdvisoryLockKey key)
        {
            // From https://www.postgresql.org/docs/12/view-pg-locks.html
            // Advisory locks can be acquired on keys consisting of either a single bigint value or two integer values.
            // A bigint key is displayed with its high-order half in the classid column, its low-order half in the objid column,
            // and objsubid equal to 1. The original bigint value can be reassembled with the expression (classid::bigint << 32) | objid::bigint.
            // Integer keys are displayed with the first key in the classid column, the second key in the objid column, and objsubid equal to 2.

            string classIdParameter, objIdParameter, objSubId;

            if (key.HasSingleKey)
            {
                // since Postgres seems to lack unchecked int conversions, it is simpler to just generate extra
                // parameters to carry the split key info in this case
                var(keyUpper32, keyLower32)           = key.Keys;
                command.AddParameter(classIdParameter = "keyUpper32", keyUpper32, DbType.Int32);
                command.AddParameter(objIdParameter   = "keyLower32", keyLower32, DbType.Int32);
                objSubId = "1";
            }
            else
            {
                classIdParameter = "key1";
                objIdParameter   = "key2";
                objSubId         = "2";
            }

            return($"(l.classid = @{classIdParameter} AND l.objid = @{objIdParameter} AND l.objsubid = {objSubId})");
        }
 public void Process(DatabaseCommand command, IDatabase database)
 {
     FixDates(command);
     FixTimes(command);
     FixDateTimes(command);
     FixDateTimeParameters(command);
 }
Example #18
0
        public void ExecuteTableWithAnonymousConverter_Test()
        {
            using (var cmd = new DatabaseCommand(_connection))
            {
                cmd.Log         = Console.WriteLine;
                cmd.CommandText = " SELECT EMPNO, ENAME, SAL, HIREDATE, COMM, MGR  FROM EMP";
                var employees = cmd.ExecuteTable((row) =>
                {
                    return(new
                    {
                        Id = row.Field <int>("EMPNO"),
                        Name = row.Field <string>("ENAME"),
                        Salary = row.Field <Decimal>("SAL"),
                        HireDate = row.Field <DateTime>("HIREDATE"),
                        Comm = row.Field <int?>("COMM"),
                        Manager = row.Field <int?>("MGR"),
                    });
                });

                var smith = employees.First();

                Assert.AreEqual(14, employees.Count());
                Assert.AreEqual(EMP.Smith.EmpNo, smith.Id);
                Assert.AreEqual(EMP.Smith.Salary, smith.Salary);
                Assert.AreEqual(EMP.Smith.HireDate, smith.HireDate);
                Assert.AreEqual(EMP.Smith.Comm, smith.Comm);
                Assert.AreEqual(EMP.Smith.Manager, smith.Manager);
            }
        }
Example #19
0
        public static async Task AfterTestRun()
        {
            if (bool.Parse(ConfigurationManager.AppSettings["RestoreDatabaseAfterTests"]))
            {
                DatabaseCommand.Execute("SecurityEssentials.Acceptance.Tests.Resources.DatabaseTeardown.sql");
                DatabaseCommand.Execute("SecurityEssentials.Acceptance.Tests.Resources.LookupRestore.sql");
                DatabaseCommand.Execute("SecurityEssentials.Acceptance.Tests.Resources.DatabaseRestore.sql");
            }
            // Cleanup screenshot files after 1 day
            var storage = ConfigurationManager.AppSettings["TestScreenCaptureStorage"];

            if (Convert.ToBoolean(ConfigurationManager.AppSettings["TakeScreenShotOnFailure"]))
            {
                Console.WriteLine("Cleaning up screen captures older than 7 days");
                if (storage.Contains("Endpoint"))
                {
                    if (CloudStorageAccount.TryParse(storage, out var storageAccount))
                    {
                        CloudBlobClient cloudBlobClient    = storageAccount.CreateCloudBlobClient();
                        var             cloudBlobContainer = cloudBlobClient.GetContainerReference("selenium");
                        await cloudBlobContainer.CreateIfNotExistsAsync();

                        if (await cloudBlobContainer.ExistsAsync())
                        {
                            BlobContinuationToken continuationToken = null;
                            do
                            {
                                var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, continuationToken, null, null);

                                continuationToken = results.ContinuationToken;
                                foreach (IListBlobItem blobItem in results.Results)
                                {
                                    if (blobItem is CloudBlockBlob blob)
                                    {
                                        if (blob.Properties.LastModified < DateTime.UtcNow.AddDays(-7))
                                        {
                                            await blob.DeleteIfExistsAsync();
                                        }
                                    }
                                }
                            } while (continuationToken != null);
                        }
                    }
                }
                else
                {
                    if (Directory.Exists(storage))
                    {
                        var screenshots = Directory.GetFiles(storage, "*.png")
                                          .Select(a => new FileInfo(a))
                                          .Where(b => b.CreationTimeUtc < DateTime.UtcNow.AddDays(-7))
                                          .ToList();
                        foreach (var screenshot in screenshots)
                        {
                            screenshot.Delete();
                        }
                    }
                }
            }
        }
        private void RaiseChangeRegistered(DatabaseCommand change)
        {
            var list = new List <DatabaseCommand>();

            list.Add(change);
            RaiseChangeRegistered(list);
        }
Example #21
0
        public void Should_Be_Able_To_Specify_The_Table_Name()
        {
            // Arrange
            const string sql          = @"
CREATE TABLE IF NOT EXISTS Person
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            var          dbConnection = Sequelocity.CreateDbConnection(ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString);

            new DatabaseCommand(dbConnection)
            .SetCommandText(sql)
            .ExecuteNonQuery(true);

            var customer = new Customer {
                FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse("06/18/1938")
            };

            // Act
            var customerId = new DatabaseCommand(dbConnection)
                             .GenerateInsertForSQLite(customer, "[Person]") // Specifying a table name of Person
                             .ExecuteScalar(true)
                             .ToInt();

            // Assert
            Assert.That(customerId == 1);
        }
Example #22
0
        public void ExecuteRow_DataRowMapTo_Test()
        {
            using (var cmd = new DatabaseCommand(_connection))
            {
                cmd.Log         = Console.WriteLine;
                cmd.CommandText = @"SELECT EMP.EMPNO,
                                            EMP.ENAME,                                         
                                            DEPT.DNAME
                                        FROM EMP 
                                        INNER JOIN DEPT ON DEPT.DEPTNO = EMP.DEPTNO
                                        WHERE EMPNO = 7369";



                var smith = cmd.ExecuteRow(row =>
                {
                    MyEmployee emp = row.MapTo <MyEmployee>();
                    emp.Department = row.MapTo <MyDepartment>();
                    return(emp);
                });

                Assert.AreEqual(7369, smith.EmpNo);
                Assert.AreEqual("SMITH", smith.EName);
                Assert.AreEqual(null, smith.Salary);
                Assert.AreEqual(null, smith.SAL);

                Assert.AreEqual(0, smith.Department.DeptNo);
                Assert.AreEqual("RESEARCH", smith.Department.DName);
            }
        }
        public void Should_Return_The_Last_Inserted_Id()
        {
            // Arrange
            const string sql = @"
CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString );

            new DatabaseCommand( dbConnection )
                .SetCommandText( sql )
                .ExecuteNonQuery( true );

            var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };

            // Act
            var customerId = new DatabaseCommand( dbConnection )
                .GenerateInsertForSQLite( customer )
                .ExecuteScalar( true )
                .ToInt();

            // Assert
            Assert.That( customerId == 1 );
        }
Example #24
0
        public void Parameters_ShouldReturn_EmptyList()
        {
            var command = new DatabaseCommand();

            Assert.IsNotNull(command.Parameters);
            Assert.AreEqual(0, command.Parameters.Count);
        }
        public void ExecuteScalarWithPrepare_Test()
        {
            var sample = new Dictionary <int, string>()
            {
                { 7369, "SMITH" },
                { 7499, "ALLEN" }
            };

            using (var cmd = new DatabaseCommand(_connection))
            {
                cmd.Log         = Console.WriteLine;
                cmd.CommandText = @"SELECT ENAME
                                      FROM EMP
                                     WHERE EMPNO = @EmpNo ";

                cmd.AddParameter("@EMPNO", 0, System.Data.DbType.Int32);
                cmd.Prepare();

                foreach (var item in sample)
                {
                    cmd.Parameters["@EMPNO"].Value = item.Key;
                    var ename = cmd.ExecuteScalar <string>();

                    Assert.AreEqual(item.Value, ename);
                }
            }
        }
Example #26
0
        private void AddCommonParameters(DatabaseCommand command, string semaphoreName, TimeoutValue?timeout = null, string?markerTableName = null, string?ticketLockName = null)
        {
            command.AddParameter(SemaphoreNameParameter, semaphoreName);
            command.AddParameter(MaxCountParameter, this.MaxCount);
            if (timeout.TryGetValue(out var timeoutValue))
            {
                command.AddParameter(TimeoutMillisParameter, timeoutValue.InMilliseconds);
            }

            command.AddParameter(ResultCodeParameter, type: DbType.Int32, direction: ParameterDirection.Output);

            var ticket = command.AddParameter(TicketLockNameParameter, ticketLockName, type: DbType.String);

            if (ticketLockName == null)
            {
                ticket.Direction = ParameterDirection.Output;
            }
            const int MaxOutputStringLength = 8000; // plenty long enough

            ticket.Size = MaxOutputStringLength;

            var markerTable = command.AddParameter(MarkerTableNameParameter, markerTableName, type: DbType.String);

            if (markerTableName == null)
            {
                markerTable.Direction = ParameterDirection.Output;
            }
            markerTable.Size = MaxOutputStringLength;
        }
Example #27
0
        protected T[] ProcessCommand <T>(DatabaseCommand command) where T : DatabaseEntity, new()
        {
            T[] results;
            using (SqlConnection connection = new SqlConnection(ConnectionString))
                using (SqlCommand sqlCommand = connection.CreateCommand())
                {
                    sqlCommand.CommandText = command.FullCommandText;

                    foreach (DatabaseParameter parameter in command.Parameters)
                    {
                        sqlCommand.Parameters.AddWithValue(parameter.Key, parameter.Value);
                    }

                    connection.Open();
                    using (SqlDataReader reader = sqlCommand.ExecuteReader())
                    {
                        results = ReadEntities <T>(reader);
                    }

                    connection.Close();
                }


            return(results.ToArray());
        }
    public void CommandParameters_Returns_Null_When_Delegate_Is_Null()
    {
        // Act
        var actual = new DatabaseCommand <DatabaseCommandTests>("commandtext", DatabaseCommandType.Text, this, null);

        // Assert
        actual.CommandParameters.Should().BeNull();
    }
Example #29
0
 public static int GetEmployeesCount(DbTransaction currentTransaction)
 {
     using (var cmd = new DatabaseCommand(currentTransaction))
     {
         cmd.CommandText.AppendLine(" SELECT COUNT(*) FROM EMP ");
         return(cmd.ExecuteScalar <int>());
     }
 }
Example #30
0
            public ExchangeBoardListEx(IStorage storage)
                : base(storage)
            {
                var readBoardCodes = Query
                                     .Execute("SELECT group_concat(Code, ',') FROM ExchangeBoard");

                _readBoardCodes = ((Database)storage).GetCommand(readBoardCodes, null, new FieldList(), new FieldList());
            }
Example #31
0
 public override ViewModelBase AddNewItem(out DatabaseCommand addAction)
 {
     var model = new TaxonRefLink();
     model.RefLinkID = -1;
     model.RefID = ReferenceID;
     model.RefLink = "<New Taxon Link>";
     model.UseInReports = true;
     addAction = new InsertTaxonRefLinkCommand(model);
     return new TaxonRefLinkViewModel(model);
 }
        public ViewModelBase AddNewItem(out DatabaseCommand addAction)
        {
            var model = new Associate();
            model.AssociateID = -1;
            model.FromIntraCatID = Owner.ObjectID.Value;
            model.FromCategory = Category.ToString();
            model.Direction = "FromTo";

            var viewModel = new AssociateViewModel(model);
            addAction = new InsertAssociateCommand(model, Owner);
            return viewModel;
        }
		public void Should_Return_The_Last_Inserted_Ids()
		{
			// Arrange
			const string sql = @"
IF ( EXISTS (	SELECT	* 
				FROM	INFORMATION_SCHEMA.TABLES 
				WHERE	TABLE_SCHEMA = 'dbo' 
						AND	TABLE_NAME = 'Customer' ) )
BEGIN

	DROP TABLE Customer

END

IF ( NOT EXISTS (	SELECT	* 
					FROM	INFORMATION_SCHEMA.TABLES 
					WHERE	TABLE_SCHEMA = 'dbo' 
							AND	TABLE_NAME = 'Customer') )
BEGIN

	CREATE TABLE Customer
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( sql )
				.ExecuteNonQuery( true );

			var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<Customer> { customer1, customer2, customer3 };
			
			// Act
			var customerIds = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list )
				.ExecuteToList<long>();

			// Assert
			Assert.That( customerIds.Count == 3 );
			Assert.That( customerIds[0] == 1 );
			Assert.That( customerIds[1] == 2 );
			Assert.That( customerIds[2] == 3 );
		}
        public void Should_Handle_Generating_Inserts_For_A_Strongly_Typed_Object()
        {
            // Arrange
            const string createSchemaSql = @"
CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString );

            new DatabaseCommand( dbConnection )
                .SetCommandText( createSchemaSql )
                .ExecuteNonQuery( true );

            var newCustomer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };

            // Act
            var customerId = new DatabaseCommand( dbConnection )
                .GenerateInsertForSQLite( newCustomer )
                .ExecuteScalar( true )
                .ToInt();

            const string selectCustomerQuery = @"
SELECT  CustomerId,
        FirstName,
        LastName,
        DateOfBirth
FROM    Customer;
";

            var customer = new DatabaseCommand( dbConnection )
                .SetCommandText( selectCustomerQuery )
                .ExecuteToObject<Customer>();

            // Assert
            Assert.That( customerId == 1 );
            Assert.That( customer.CustomerId == 1 );
            Assert.That( customer.FirstName == newCustomer.FirstName );
            Assert.That( customer.LastName == newCustomer.LastName );
            Assert.That( customer.DateOfBirth == newCustomer.DateOfBirth );
        }
        public void Should_Contain_The_Connection_String()
        {
            // Arrange
            const string sql = @"
DROP TABLE IF EXISTS Customer;

CREATE TEMPORARY TABLE Customer
(
    CustomerId      serial not null,
    FirstName       VARCHAR(120)   NOT NULL,
    LastName        VARCHAR(120)   NOT NULL,
    DateOfBirth     timestamp        NOT NULL,
    PRIMARY KEY ( CustomerId )
);
";
            string connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringsNames.PostgreSQLConnectionString].ConnectionString;

            var dbConnection = Sequelocity.CreateDbConnection(connectionString, "Npgsql");
            connectionString = dbConnection.ConnectionString;

            new DatabaseCommand(dbConnection)
                .SetCommandText(sql)
                .ExecuteNonQuery(true);

            var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse("06/18/1938") };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse("05/27/1939") };

            var databaseCommand = new DatabaseCommand(dbConnection)
                .GenerateInsertForPostgreSQL(customer)
                .GenerateInsertForPostgreSQL(customer2);

            // Act
            var debugCommandText = databaseCommand.DbCommand.GetDebugCommandText();

            dbConnection.Close();

            // Visual Assertion
            Trace.WriteLine(debugCommandText);

            // Assert
            Assert.That(debugCommandText.Contains(connectionString.Substring(0, 10))); // Using a substring as the framework will remove the password so we can't anticipate the entire connection string will be shown
            //Note: the connection string changes slightly to default all keys to uppercase and some names to different names (i.e. USERNAME to USER ID). Connection string provided may need to be altered to accomodate.
        }
        public void Should_Contain_The_Connection_String()
        {
            // Arrange
            const string sql = @"
DROP TEMPORARY TABLE IF EXISTS Customer;

CREATE TEMPORARY TABLE Customer
(
    CustomerId      INT             NOT NULL    AUTO_INCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL,
    PRIMARY KEY ( CustomerId )
);
";
            string connectionString = ConfigurationManager.ConnectionStrings[ ConnectionStringsNames.MySqlConnectionString ].ConnectionString;

            var dbConnection = Sequelocity.CreateDbConnection( connectionString, "MySql.Data.MySqlClient" );

            new DatabaseCommand( dbConnection )
                .SetCommandText( sql )
                .ExecuteNonQuery( true );

            var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };

            var databaseCommand = new DatabaseCommand( dbConnection )
                .GenerateInsertForMySql( customer )
                .GenerateInsertForMySql( customer2 );

            // Act
            var debugCommandText = databaseCommand.DbCommand.GetDebugCommandText();

            // Visual Assertion
            Trace.WriteLine( debugCommandText );
            
            // Assert
            Assert.That( debugCommandText.Contains( connectionString.Substring( 0, 10 ) ) ); // Using a substring as the framework will remove the password so we can't anticipate the entire connection string will be shown
        }
        public void Should_Return_The_Last_Inserted_Ids()
        {
            // Arrange
            const string createSchemaSql = @"
DROP TABLE IF EXISTS Customer;

CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      serial not null,
    FirstName       VARCHAR(120)   NOT NULL,
    LastName        VARCHAR(120)   NOT NULL,
    DateOfBirth     timestamp        NOT NULL,
    PRIMARY KEY ( CustomerId )
);
";

            var dbConnection = Sequelocity.CreateDbConnection(ConnectionStringsNames.PostgreSQLConnectionString);

            new DatabaseCommand(dbConnection)
                .SetCommandText(createSchemaSql)
                .ExecuteNonQuery(true);

            var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse("06/18/1938") };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse("05/27/1939") };
            var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse("08/18/1962") };
            var list = new List<Customer> { customer1, customer2, customer3 };

            // Act
            var customerIds = new DatabaseCommand(dbConnection)
                .GenerateInsertsForPostgreSQL(list)
                .ExecuteToList<long>();

            // Assert
            Assert.That(customerIds.Count == 3);
            Assert.That(customerIds[0] == 1);
            Assert.That(customerIds[1] == 2);
            Assert.That(customerIds[2] == 3);
        }
        public void Should_Contain_Parameter_Replaced_CommandText()
        {
            // Arrange
            const string sql = @"
CREATE TABLE #Customer
(
    CustomerId      INT         NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);
";
            string connectionString = ConfigurationManager.ConnectionStrings[ ConnectionStringsNames.SqlServerConnectionString ].ConnectionString;

            var dbConnection = Sequelocity.CreateDbConnection( connectionString, "System.Data.SqlClient" );

            new DatabaseCommand( dbConnection )
                .SetCommandText( sql )
                .ExecuteNonQuery( true );

            var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };

            var databaseCommand = new DatabaseCommand( dbConnection )
                .GenerateInsertForSqlServer( customer )
                .GenerateInsertForSqlServer( customer2 );

            // Act

            var debugCommandText = databaseCommand.DbCommand.GetDebugCommandText();

            // Visual Assertion
            Trace.WriteLine( debugCommandText );

            // Assert
            Assert.That( debugCommandText.Contains( customer.FirstName ) );
            Assert.That( debugCommandText.Contains( customer.LastName ) );
        }
        public void Should_Handle_Generating_Inserts_For_A_Strongly_Typed_Object()
        {
            // Arrange
            const string createSchemaSql = @"
CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString );

            new DatabaseCommand( dbConnection )
                .SetCommandText( createSchemaSql )
                .ExecuteNonQuery( true );

            var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
            var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
            var list = new List<Customer> { customer1, customer2, customer3 };

            // Act
            var customerIds = new DatabaseCommand( dbConnection )
                .GenerateInsertsForSQLite( list )
                .ExecuteToList<long>( true );

            const string selectCustomerQuery = @"
SELECT  CustomerId,
        FirstName,
        LastName,
        DateOfBirth
FROM    Customer
WHERE   CustomerId IN ( @CustomerIds );
";

            var customers = new DatabaseCommand( dbConnection )
                .SetCommandText( selectCustomerQuery )
                .AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
                .ExecuteToList<Customer>()
                .OrderBy( x => x.CustomerId )
                .ToList();

            // Assert
            Assert.That( customers.Count == 3 );

            Assert.That( customers[0].CustomerId == 1 );
            Assert.That( customers[0].FirstName == customer1.FirstName );
            Assert.That( customers[0].LastName == customer1.LastName );
            Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );

            Assert.That( customers[1].CustomerId == 2 );
            Assert.That( customers[1].FirstName == customer2.FirstName );
            Assert.That( customers[1].LastName == customer2.LastName );
            Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );

            Assert.That( customers[2].CustomerId == 3 );
            Assert.That( customers[2].FirstName == customer3.FirstName );
            Assert.That( customers[2].LastName == customer3.LastName );
            Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
        }
		public void Should_Be_Able_To_Specify_The_Table_Name()
		{
			// Arrange
			const string sql = @"
IF ( EXISTS (	SELECT	* 
				FROM	INFORMATION_SCHEMA.TABLES 
				WHERE	TABLE_SCHEMA = 'dbo' 
						AND	TABLE_NAME = 'Person' ) )
BEGIN

	DROP TABLE Person

END

IF ( NOT EXISTS (	SELECT	* 
					FROM	INFORMATION_SCHEMA.TABLES 
					WHERE	TABLE_SCHEMA = 'dbo' 
							AND	TABLE_NAME = 'Person') )
BEGIN

	CREATE TABLE Person
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( sql )
				.ExecuteNonQuery( true );

			var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<Customer> { customer1, customer2, customer3 };

			// Act
			var numberOfAffectedRecords = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list, "[Person]" ) // Specifying a table name of Person
				.ExecuteNonQuery( true );

			// Assert
			Assert.That( numberOfAffectedRecords == list.Count );
		}
        public void Should_Be_Able_To_Specify_The_Table_Name()
        {
            // Arrange
            const string sql = @"
CREATE TABLE IF NOT EXISTS Person
(
    CustomerId      INTEGER         NOT NULL    PRIMARY KEY     AUTOINCREMENT,
    FirstName       NVARCHAR(120)   NOT NULL,
    LastName        NVARCHAR(120)   NOT NULL,
    DateOfBirth     DATETIME        NOT NULL
);";
            var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString );

            new DatabaseCommand( dbConnection )
                .SetCommandText( sql )
                .ExecuteNonQuery( true );

            var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
            var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
            var list = new List<Customer> { customer1, customer2, customer3 };

            // Act
            var numberOfAffectedRecords = new DatabaseCommand( dbConnection )
                .GenerateInsertsForSQLite( list, "[Person]" ) // Specifying a table name of Person
                .ExecuteNonQuery( true );

            // Assert
            Assert.That( numberOfAffectedRecords == list.Count );
        }
        public void Should_Contain_Parameter_Replaced_CommandText()
        {
            // Arrange
            const string sql = @"
DROP TABLE IF EXISTS Customer;

CREATE TEMPORARY TABLE Customer
(
    CustomerId      serial not null,
    FirstName       VARCHAR(120)   NOT NULL,
    LastName        VARCHAR(120)   NOT NULL,
    DateOfBirth     timestamp        NOT NULL,
    PRIMARY KEY ( CustomerId )
);
";
            string connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringsNames.PostgreSQLConnectionString].ConnectionString;

            var dbConnection = Sequelocity.CreateDbConnection(connectionString, "Npgsql");

            new DatabaseCommand(dbConnection)
                .SetCommandText(sql)
                .ExecuteNonQuery(true);

            var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse("06/18/1938") };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse("05/27/1939") };

            var databaseCommand = new DatabaseCommand(dbConnection)
                .GenerateInsertForPostgreSQL(customer)
                .GenerateInsertForPostgreSQL(customer2);

            // Act

            var debugCommandText = databaseCommand.DbCommand.GetDebugCommandText();

            dbConnection.Close();

            // Visual Assertion
            Trace.WriteLine(debugCommandText);

            // Assert
            Assert.That(debugCommandText.Contains(customer.FirstName));
            Assert.That(debugCommandText.Contains(customer.LastName));
        }
Example #43
0
 public bool RegisterUniquePendingChange(DatabaseCommand command, object contributer)
 {
     return _impl.RegisterUniquePendingChange(command, contributer);
 }
        public void Should_Handle_Generating_Inserts_For_A_Dynamic_Object()
        {
            // Arrange
            const string createSchemaSql = @"
DROP TABLE IF EXISTS Customer;

CREATE TABLE IF NOT EXISTS Customer
(
    CustomerId      serial,
    FirstName       VARCHAR(120)   NOT NULL,
    LastName        VARCHAR(120)   NOT NULL,
    DateOfBirth     timestamp        NOT NULL,
    PRIMARY KEY ( CustomerId )
);
";

            var dbConnection = Sequelocity.CreateDbConnection(ConnectionStringsNames.PostgreSQLConnectionString);

            new DatabaseCommand(dbConnection)
                .SetCommandText(createSchemaSql)
                .ExecuteNonQuery(true);

            dynamic customer1 = new ExpandoObject();
            customer1.FirstName = "Clark";
            customer1.LastName = "Kent";
            customer1.DateOfBirth = DateTime.Parse("06/18/1938");

            dynamic customer2 = new ExpandoObject();
            customer2.FirstName = "Bruce";
            customer2.LastName = "Wayne";
            customer2.DateOfBirth = DateTime.Parse("05/27/1939");

            dynamic customer3 = new ExpandoObject();
            customer3.FirstName = "Peter";
            customer3.LastName = "Parker";
            customer3.DateOfBirth = DateTime.Parse("08/18/1962");

            var list = new List<dynamic> { customer1, customer2, customer3 };

            // Act
            var customerIds = new DatabaseCommand(dbConnection)
                .GenerateInsertsForPostgreSQL(list, "public.Customer")
                .ExecuteToList<long>(true);

            const string selectCustomerQuery = @"
SELECT  CustomerId,
		FirstName,
		LastName,
		DateOfBirth
FROM    Customer
WHERE   CustomerId IN ( @CustomerIds );
";

            var customers = new DatabaseCommand(dbConnection)
                .SetCommandText(selectCustomerQuery)
                .AddParameters("@CustomerIds", customerIds, DbType.Int64)
                .ExecuteToList<Customer>()
                .OrderBy(x => x.CustomerId)
                .ToList();

            // Assert
            Assert.That(customers.Count == 3);

            Assert.That(customers[0].CustomerId == 1);
            Assert.That(customers[0].FirstName == customer1.FirstName);
            Assert.That(customers[0].LastName == customer1.LastName);
            Assert.That(customers[0].DateOfBirth == customer1.DateOfBirth);

            Assert.That(customers[1].CustomerId == 2);
            Assert.That(customers[1].FirstName == customer2.FirstName);
            Assert.That(customers[1].LastName == customer2.LastName);
            Assert.That(customers[1].DateOfBirth == customer2.DateOfBirth);

            Assert.That(customers[2].CustomerId == 3);
            Assert.That(customers[2].FirstName == customer3.FirstName);
            Assert.That(customers[2].LastName == customer3.LastName);
            Assert.That(customers[2].DateOfBirth == customer3.DateOfBirth);
        }
Example #45
0
		public bool ReadFromDB(int taskID)
		{
			DataTable table;
			DatabaseCommand cmd = new DatabaseCommand(db);

			cmd.AppendFormat("Select * from TaskBackupSync where taskid = {0}", taskID);
			table = cmd.ExecuteSelectToTable(DatabaseCommandOptions.ThrowException | DatabaseCommandOptions.LogError);
			if (table == null || table.Rows.Count == 0)
				return false;

			TaskID = Convert.ToInt32(table.Rows[0]["taskID"]);
			StartJobID = DatabaseFieldConvert.ToInt32(table.Rows[0]["StartJobID"]);
			Type = (JobType)DatabaseFieldConvert.ToInt32(table.Rows[0]["JobType"]);
			StatTaskStart = DatabaseFieldConvert.ToDateTime(table.Rows[0]["StartTS"]);
			StatTaskEnd = DatabaseFieldConvert.ToDateTime(table.Rows[0]["EndTS"]);
			AgentMachineName = table.Rows[0]["AgentMachineName"] as string;
			SourcePath = table.Rows[0]["SourcePath"] as string;
			DestinationPath = table.Rows[0]["DestinationPath"] as string;
			StatFileCount = Convert.ToInt64(table.Rows[0]["FileCount"]);
			StatFileCreateCount = Convert.ToInt64(table.Rows[0]["FileCreateCount"]);
			StatFileCopyCount = Convert.ToInt64(table.Rows[0]["FileCopyCount"]);
			StatFileCopyOKCount = Convert.ToInt64(table.Rows[0]["FileCopyOKCount"]);
			StatFileCopyErrorCount = Convert.ToInt64(table.Rows[0]["FileCopyErrorCount"]);
			StatFileDeleteCount = Convert.ToInt64(table.Rows[0]["FileDeleteCount"]);
			StatFileDeleteOKCount = Convert.ToInt64(table.Rows[0]["FileDeleteOKCount"]);
			StatFileDeleteErrorCount = Convert.ToInt64(table.Rows[0]["FileDeleteErrorCount"]);
			StatDirCount = Convert.ToInt64(table.Rows[0]["DirCount"]);
			StatDirCreateCount = Convert.ToInt64(table.Rows[0]["DirCreateCount"]);
			StatDirCreateOKCount = Convert.ToInt64(table.Rows[0]["DirCreateOKCount"]);
			StatDirCreateErrorCount = Convert.ToInt64(table.Rows[0]["DirCreateErrorCount"]);
			StatDirDeleteCount = Convert.ToInt64(table.Rows[0]["DirDeleteCount"]);
			StatDirDeleteOKCount = Convert.ToInt64(table.Rows[0]["DirDeleteOKCount"]);
			StatDirDeleteErrorCount = Convert.ToInt64(table.Rows[0]["DirDeleteErrorCount"]);
			StatByteCopyCount = Convert.ToInt64(table.Rows[0]["ByteCopyCount"]);
			StatByteCopyOKCount = Convert.ToInt64(table.Rows[0]["ByteCopyOKCount"]);
			StatErrorCount = Convert.ToInt64(table.Rows[0]["ErrorCount"]);

			return true;
		}
Example #46
0
 public virtual ViewModelBase AddNewItem(out DatabaseCommand addAction)
 {
     throw new NotImplementedException();
 }
		public void Should_Handle_Generating_Inserts_For_A_Dynamic_Object()
		{
			// Arrange
			const string createSchemaSql = @"
IF ( EXISTS (	SELECT	* 
				FROM	INFORMATION_SCHEMA.TABLES 
				WHERE	TABLE_SCHEMA = 'dbo' 
						AND	TABLE_NAME = 'Customer' ) )
BEGIN

	DROP TABLE Customer

END

IF ( NOT EXISTS (	SELECT	* 
					FROM	INFORMATION_SCHEMA.TABLES 
					WHERE	TABLE_SCHEMA = 'dbo' 
							AND	TABLE_NAME = 'Customer') )
BEGIN

	CREATE TABLE Customer
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( createSchemaSql )
				.ExecuteNonQuery( true );

			dynamic customer1 = new ExpandoObject();
			customer1.FirstName = "Clark";
			customer1.LastName = "Kent";
			customer1.DateOfBirth = DateTime.Parse( "06/18/1938" );

			dynamic customer2 = new ExpandoObject();
			customer2.FirstName = "Bruce";
			customer2.LastName = "Wayne";
			customer2.DateOfBirth = DateTime.Parse( "05/27/1939" );

			dynamic customer3 = new ExpandoObject();
			customer3.FirstName = "Peter";
			customer3.LastName = "Parker";
			customer3.DateOfBirth = DateTime.Parse( "08/18/1962" );

			var list = new List<dynamic> { customer1, customer2, customer3 };

			// Act
			var customerIds = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list, "Customer" )
				.ExecuteToList<long>( true );

			const string selectCustomerQuery = @"
SELECT  CustomerId,
		FirstName,
		LastName,
		DateOfBirth
FROM    Customer
WHERE   CustomerId IN ( @CustomerIds );
";

			var customers = new DatabaseCommand( dbConnection )
				.SetCommandText( selectCustomerQuery )
				.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
				.ExecuteToList<Customer>()
				.OrderBy( x => x.CustomerId )
				.ToList();

			// Assert
			Assert.That( customers.Count == 3 );

			Assert.That( customers[0].CustomerId == 1 );
			Assert.That( customers[0].FirstName == customer1.FirstName );
			Assert.That( customers[0].LastName == customer1.LastName );
			Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );

			Assert.That( customers[1].CustomerId == 2 );
			Assert.That( customers[1].FirstName == customer2.FirstName );
			Assert.That( customers[1].LastName == customer2.LastName );
			Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );

			Assert.That( customers[2].CustomerId == 3 );
			Assert.That( customers[2].FirstName == customer3.FirstName );
			Assert.That( customers[2].LastName == customer3.LastName );
			Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
		}
        public void Should_Be_Able_To_Specify_The_Table_Name()
        {
            // Arrange
            const string createSchemaSql = @"
DROP TABLE IF EXISTS Person;

CREATE TABLE IF NOT EXISTS Person
(
    CustomerId      serial,
    FirstName       VARCHAR(120)   NOT NULL,
    LastName        VARCHAR(120)   NOT NULL,
    DateOfBirth     timestamp        NOT NULL,
    PRIMARY KEY ( CustomerId )
);
";

            var dbConnection = Sequelocity.CreateDbConnection(ConnectionStringsNames.PostgreSQLConnectionString);

            new DatabaseCommand(dbConnection)
                .SetCommandText(createSchemaSql)
                .ExecuteNonQuery(true);

            var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse("06/18/1938") };
            var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse("05/27/1939") };
            var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse("08/18/1962") };
            var list = new List<Customer> { customer1, customer2, customer3 };

            // Act
            var numberOfAffectedRecords = new DatabaseCommand(dbConnection)
                .GenerateInsertsForPostgreSQL(list, "Person") // Specifying a table name of Person
                .ExecuteNonQuery(true);

            var recordsInPerson = new DatabaseCommand(dbConnection)
                .SetCommandText(@"select count(*) from Person;")
                .ExecuteScalar<int>();

            // Assert
            Assert.That(recordsInPerson == list.Count);
        }
Example #49
0
 public void RegisterPendingChange(DatabaseCommand command, object contributer)
 {
     _impl.RegisterPendingChange(command, contributer);
 }