示例#1
0
        public void CheickDbObjectCommand_Generic_Should_Throw_ArgumentNull_Exception()
        {
            // Arrange
            this.fluentDbCommand = new FluentDbCommandBase();
            DbObjectCommand <string> nullCommand  = null;
            DbObjectCommand <string> emptyCommand = new DbObjectCommand <string>();

            emptyCommand.ObjectParameter = null;
            emptyCommand.Operation       = DbOperation.Delete;
            emptyCommand.ScriptSql       = string.Empty;

            DbObjectCommand <string> emptyCommand_2 = new DbObjectCommand <string>();

            emptyCommand_2.ObjectParameter = "fake param";
            emptyCommand_2.Operation       = DbOperation.ExecuteSql;
            emptyCommand_2.ScriptSql       = string.Empty;

            // Assert
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(nullCommand));
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(emptyCommand));
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(emptyCommand_2));
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(new List <DbObjectCommand <string> >()
            {
                emptyCommand
            }));
        }
示例#2
0
        /// <inheritdoc />
        public async Task <TReturn> ExecuteAsync <TReturn, T>(DbObjectCommand <T> command, Func <TReturn> customValueProviderToExecute, Action?dispatcherPostExecution = null, bool throwException = false)
            where T : class, new()
        {
            await this.ExecuteAsync(command, dispatcherPostExecution, throwException);

            return(customValueProviderToExecute());
        }
示例#3
0
        /// <inheritdoc />
        public async Task <DbCommandResult> ExecuteAsync(DbObjectCommand command, Action?dispatcherPostExecution = null, bool throwException = false)
        {
            this.EnsureDbConnection();
            this.EnsureDbConnectionIsOpened();

            return(await this.SafeExecute(() => this.ExecuteDbObjectCommand(command, dispatcherPostExecution, throwException), throwException));
        }
示例#4
0
        public async Task InsertDataByObjectCommand()
        {
            this.dbFactory = new FluentDbFactory(dbConnection);
            Stopwatch stopwatch = new Stopwatch();

            // Insert by using an DbObjectCommand
            var newEmp = new Employee()
            {
                FirstName = "FirstName111",
                LastName  = "LastName111",
                Salary    = 120000
            };

            var insertEmpCommand = new DbObjectCommand()
            {
                Parameters = new List <object>()
                {
                    newEmp
                },
                ScriptSql = "INSERT INTO[dbo].[Employee](FirstName, LastName, Salary) Values(@FirstName, @LastName, @Salary)"
            };

            Console.WriteLine("await dbEngine.CreateDbCommand().ExecuteAsync with a DbObjectCommand");
            stopwatch.Start();
            var result = await dbFactory.CreateDbCommand().ExecuteAsync(insertEmpCommand);

            stopwatch.Stop();
            Console.WriteLine($"Result : {result.IsSuccess} | Time Elapsed : {stopwatch.Elapsed}");

            stopwatch.Reset();
            Console.WriteLine("---------------------------------------------------------------------------");

            // Insert with generic DbObjectCommand and return a custom value
            Func <string> returnFunction = () => "Everything is ok";
            var           project        = new Project()
            {
                AssigneeId  = 1,
                Description = "Project | Fluent Db Sample",
                Budget      = 250000,
                Name        = "Show FluentDb library"
            };
            var insertPrjCommand = new DbObjectCommand <Project>()
            {
                ObjectParameter = project,
                Operation       = DbOperation.Insert,
            };

            Console.WriteLine("await dbEngine.CreateDbCommand().ExecuteAsync with a Generic DbObjectCommand and return a custom value");
            stopwatch.Start();
            string returnValue = await dbFactory.CreateDbCommand().ExecuteAsync <string, Project>(
                insertPrjCommand,
                customValueProviderToExecute: returnFunction);

            stopwatch.Stop();
            Console.WriteLine($"Result returned : {returnValue} | Time Elapsed : {stopwatch.Elapsed}");

            stopwatch.Reset();
            Console.WriteLine("---------------------------------------------------------------------------");
        }
示例#5
0
        /// <inheritdoc />
        public IFluentDbCommand AddDeleteCommand <T>(T data)
            where T : class, new()
        {
            DbObjectCommand <T> command = new DbObjectCommand <T>();

            command.ObjectParameter = data;
            command.Operation       = DbOperation.Delete;

            Func <Task <DbCommandResult> > execution = () => this.ExecuteAsync(command);

            this.ActionsToExecute.Enqueue(execution);
            this.MultipleCommandExecution = true;
            return(this);
        }
示例#6
0
        /// <inheritdoc />
        public IFluentDbCommand AddCustomCommand(string sql)
        {
            if (string.IsNullOrWhiteSpace(sql))
            {
                throw new ArgumentNullException(nameof(sql));
            }

            DbObjectCommand command = new DbObjectCommand();

            command.ScriptSql  = sql;
            command.Parameters = null;

            Func <Task <DbCommandResult> > execution = () => this.ExecuteAsync(command);

            this.ActionsToExecute.Enqueue(execution);

            this.MultipleCommandExecution = true;
            return(this);
        }
示例#7
0
        // DbObjectCommand execute
        private async Task <DbCommandResult> ExecuteDbObjectCommand <T>(DbObjectCommand <T> command, Action?dispatcherPostExecution = null, bool throwException = false)
            where T : class, new()
        {
            DbCommandResult result = new DbCommandResult();

            try
            {
                this.CheickDbObjectCommand(command);
                bool operation = command.Operation switch
                {
                    DbOperation.Delete => await this.dbConnection.DeleteAsync <T>(command.ObjectParameter !, transaction : this.Transaction),
                    DbOperation.Insert => await this.dbConnection.InsertAsync <T>(command.ObjectParameter !, transaction : this.Transaction) > 0,
                    DbOperation.Update => await this.dbConnection.UpdateAsync <T>(command.ObjectParameter !, transaction : this.Transaction),
                    DbOperation.ExecuteSql => await this.ExecuteScriptAsync <T>(command.ScriptSql !, command.ObjectParameter !),
                    _ => false
                };

                result.Result    = operation ? 1 : 0;
                result.IsSuccess = operation;

                dispatcherPostExecution?.Invoke();
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Result    = -1;
                result.IsSuccess = false;

                dispatcherPostExecution?.Invoke();

                this.ThrowExceptionIfNecessary(throwException, ex);
            }

            if (!result.IsSuccess && result.Exception == null)
            {
                result.Exception = new FluentDbExecutionException("Data was not found");
            }

            return(result);
        }
示例#8
0
        public void CheickDbObjectCommand_Should_Throw_ArgumentNull_Exception()
        {
            // Arrange
            this.fluentDbCommand = new FluentDbCommandBase();
            DbObjectCommand nullCommand  = null;
            DbObjectCommand emptyCommand = new DbObjectCommand();

            emptyCommand.Parameters = Enumerable.Empty <object>();
            emptyCommand.ScriptSql  = "SELECT 1";

            DbObjectCommand emptyCommand_2 = new DbObjectCommand();

            emptyCommand.Parameters = new object[] { 10 };
            emptyCommand.ScriptSql  = string.Empty;

            // Assert
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(nullCommand));
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(emptyCommand_2));
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(emptyCommand));
            Assert.Throws <ArgumentNullException>(() => this.fluentDbCommand.CheickDbObjectCommand(new List <DbObjectCommand>()
            {
                emptyCommand
            }));
        }
示例#9
0
        // DbObjectCommand execute
        private async Task <DbCommandResult> ExecuteDbObjectCommand(DbObjectCommand command, Action?dispatcherPostExecution = null, bool throwException = false)
        {
            DbCommandResult result = new DbCommandResult();

            try
            {
                this.CheickDbObjectCommand(command);

                if (command.Parameters != null && command.Parameters.Any())
                {
                    result.Result = await this.dbConnection.ExecuteAsync(
                        command.ScriptSql,
                        command.Parameters,
                        transaction : this.Transaction);
                }
                else
                {
                    result.Result = await this.dbConnection.ExecuteAsync(command.ScriptSql, transaction : this.Transaction);
                }

                result.IsSuccess = result.Result > 0;
                dispatcherPostExecution?.Invoke();
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Result    = -1;
                result.IsSuccess = false;

                dispatcherPostExecution?.Invoke();

                this.ThrowExceptionIfNecessary(throwException, ex);
            }

            return(result);
        }
示例#10
0
        public async Task ExecuteWithDispatcher(ILogger logger)
        {
            this.dbFactory = new FluentDbFactory(dbConnection);
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("Execute dispatcher inside the command");

            var project = new Project()
            {
                AssigneeId  = 1,
                Description = "Project 3 | Fluent Db Sample",
                Budget      = 260000,
                Name        = "Show FluentDb library 3"
            };
            var insertPrjCommand = new DbObjectCommand <Project>()
            {
                ObjectParameter = project,
                Operation       = DbOperation.Insert,
            };

            stopwatch.Start();
            var result = await this.dbFactory.CreateDbCommand().ExecuteAsync <Project>(
                command: insertPrjCommand,
                dispatcherPostExecution: () => logger?.LogInformation("dispatcher execute"),
                throwException: false);

            Console.WriteLine($"Result : {result.IsSuccess} | Time Elapsed : {stopwatch.Elapsed}");

            stopwatch.Reset();
            Console.WriteLine("---------------------------------------------------------------------------");

            Console.WriteLine("Execute dispatcher inside many command execution");

            Project prj = await this.dbConnection.QueryFirstAsync <Project>("select * from dbo.Project where Name = 'Show FluentDb library 3'");

            // Update data
            prj.Budget = 340000;

            // Apply update and insert new data

            // employe data
            var newEmp = new Employee()
            {
                FirstName = "FirstName133",
                LastName  = "LastName133",
                Salary    = 200000
            };

            Console.WriteLine("Execute many insert in one step");
            stopwatch.Start();
            var result2 = await this.dbFactory.CreateDbCommand().WithTransaction()
                          .AddInsertCommand <Employee>(newEmp)
                          .AddUpdateCommand <Project>(prj)
                          .AddCustomCommand("delete from dbo.Employee where FirstName = 'FirstName111'")
                          .ExecuteAsync(
                dispatcherPostExecution: () => logger?.LogInformation("Dispatcher executed"),
                throwException: true);

            stopwatch.Stop();
            Console.WriteLine($"Result : {result.IsSuccess} | Time Elapsed : {stopwatch.Elapsed}");

            stopwatch.Reset();
            Console.WriteLine("---------------------------------------------------------------------------");
        }