Example #1
0
        /// <summary>
        ///     Generate a complete list before returning.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to map</typeparam>
        /// <param name="unitOfWork">Connection to invoke <c>ExecuteReader()</c> on (through a created <c>DbCommand</c>).</param>
        /// <param name="mapping">Mapping used to translate from db table rows to .NET object</param>
        /// <param name="query">Query</param>
        /// <param name="parameters">Anonymous object (<c>new { id = dto.ProjectId, @minDate = dto.MinDate }</c>), a dictionary or a value array</param>
        /// <returns>A list.</returns>
        /// <remarks>
        ///     <para>
        ///         For more information about the "query" and "parameters" arguments, see <see cref="CommandExtensions.ApplyQuerySql{TEntity}"/>.
        ///     </para>
        ///     <para>
        ///         The returned enumerator will not map each row until it's requested. To be able to do that the
        ///         connection/command/datareader is
        ///         kept open until the enumerator is disposed. Hence it's important that you make sure that the enumerator is
        ///         disposed when you are
        ///         done with it.
        ///     </para>
        ///     <para>Uses <see cref="EntityMappingProvider" /> to find the correct <c><![CDATA[IEntityMapper<TEntity>]]></c>.</para>
        /// </remarks>
        /// <example>
        /// <code>
        /// // All these examples are valid:
        /// <![CDATA[
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE Age = 37");
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE FirstName = @name", new { name = user.FirstName });
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE FirstName = @1 AND Age < @2", 'A%', 35);
        /// ]]>
        /// </code>
        /// </example>
        public static IList <TEntity> ToList <TEntity>(this IAdoNetUnitOfWork unitOfWork, IEntityMapper <TEntity> mapping, string query, params object[] parameters)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }
            if (mapping == null)
            {
                throw new ArgumentNullException("mapping");
            }

            var cmd = unitOfWork.CreateDbCommand();

            try
            {
                cmd.ApplyQuerySql <TEntity>(mapping, query, parameters);

                var items = new List <TEntity>();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var entity = mapping.Create(reader);
                        mapping.Map(reader, entity);
                        items.Add((TEntity)entity);
                    }
                }
                return(items);
            }
            catch (Exception e)
            {
                throw cmd.CreateDataException(e);
            }
        }
 public ReportController(IMessageQueueProvider queueProvider, IAdoNetUnitOfWork unitOfWork,
                         ConfigurationStore configStore)
 {
     _unitOfWork   = unitOfWork;
     _configStore  = configStore;
     _messageQueue = queueProvider.Open("Reports");
 }
Example #3
0
        /// <summary>
        /// Insert a new item.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity (must have a mapping registered in the <see cref="EntityMappingProvider"/>)</typeparam>
        /// <param name="unitOfWork">Uow to extend</param>
        /// <param name="entity">The entity to create.</param>
        public static object Insert <TEntity>(this IAdoNetUnitOfWork unitOfWork, TEntity entity)
        {
            var mapper = EntityMappingProvider.GetMapper <TEntity>();

            using (var cmd = unitOfWork.CreateCommand())
            {
                try
                {
                    mapper.CommandBuilder.InsertCommand(cmd, entity);
                    var keys = mapper.GetKeys(entity);
                    if (keys.Length == 1)
                    {
                        var id = cmd.ExecuteScalar();
                        if (id != null && id != DBNull.Value)
                        {
                            mapper.Properties[keys[0].Key].SetColumnValue(entity, id);
                        }
                        return(id);
                    }
                    return(cmd.ExecuteScalar());
                }
                catch (Exception ex)
                {
                    throw cmd.CreateDataException(ex);
                }
            }
        }
Example #4
0
        /// <summary>
        ///     Insert a new row into the database.
        /// </summary>
        /// <typeparam name="TEntity">
        ///     Type of entity to use, must have an mapper registered in <see cref="EntityMappingProvider" />
        ///     .
        /// </typeparam>
        /// <param name="unitOfWork">Unit of work to execute command in.</param>
        /// <param name="entity">entity to insert into the database.</param>
        /// <returns>Task to wait on for completion</returns>
        /// <remarks>
        ///     <para>
        ///         Will assign the PK value to the
        ///     </para>
        /// </remarks>
        /// <example>
        ///     <code>
        /// var user = new User(10, "Jonas");
        /// using (var uow = UnitOfWorkFactory.Create())
        /// {
        ///     await uow.InsertAsync(user);
        /// }
        /// </code>
        /// </example>
        public static async Task <object> InsertAsync <TEntity>(this IAdoNetUnitOfWork unitOfWork, TEntity entity)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }
            if (EqualityComparer <TEntity> .Default.Equals(default(TEntity), entity))
            {
                throw new ArgumentNullException("entity");
            }

            var mapper = EntityMappingProvider.GetMapper <TEntity>();

            using (var cmd = (DbCommand)unitOfWork.CreateCommand())
            {
                mapper.CommandBuilder.InsertCommand(cmd, entity);
                //var keys = mapper.GetKeys(entity);
                //if (keys.Length == 1 && true)
                //{
                //    var id = await cmd.ExecuteScalarAsync();
                //    mapper.Properties[keys[0].Key].SetColumnValue(entity, id);
                //}
                return(await cmd.ExecuteScalarAsync());
            }
        }
 public SubmitFeedbackHandler(IAdoNetUnitOfWork unitOfWork, IReportsRepository reportsRepository,
                              IEventBus eventBus)
 {
     _unitOfWork        = unitOfWork;
     _reportsRepository = reportsRepository;
     _eventBus          = eventBus;
 }
 public CollectStatsJob(IAdoNetUnitOfWork unitOfWork, IConfiguration <UsageStatsSettings> config,
                        IConfiguration <CoderrConfigSection> reportConfiguration)
 {
     _unitOfWork          = unitOfWork;
     _config              = config;
     _reportConfiguration = reportConfiguration;
 }
Example #7
0
        /// <summary>
        ///     Insert a new row into the database.
        /// </summary>
        /// <typeparam name="TEntity">
        ///     Type of entity to use, must have an mapper registered in <see cref="EntityMappingProvider" />
        ///     .
        /// </typeparam>
        /// <param name="unitOfWork">Unit of work to execute command in.</param>
        /// <param name="entity">entity to insert into the database.</param>
        /// <returns>Task to wait on for completion</returns>
        /// <remarks>
        ///     <para>
        ///         Will assign the PK value to the
        ///     </para>
        /// </remarks>
        /// <example>
        ///     <code>
        /// var user = new User(10, "Jonas");
        /// using (var uow = UnitOfWorkFactory.Create())
        /// {
        ///     await uow.InsertAsync(user);
        /// }
        /// </code>
        /// </example>
        public static async Task <object> InsertAsync <TEntity>(this IAdoNetUnitOfWork unitOfWork, TEntity entity)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }
            if (EqualityComparer <TEntity> .Default.Equals(default(TEntity), entity))
            {
                throw new ArgumentNullException("entity");
            }

            var mapper = EntityMappingProvider.GetCrudMapper <TEntity>();

            using (var cmd = (DbCommand)unitOfWork.CreateCommand())
            {
                try
                {
                    mapper.CommandBuilder.InsertCommand(cmd, entity);
                    var value = await cmd.AssignAutoIncrementIfConfigured(entity, mapper);

                    return(value ?? await cmd.ExecuteScalarAsync());
                }
                catch (Exception e)
                {
                    throw cmd.CreateDataException(e);
                }
            }
        }
 public SubmitFeedbackHandler(IAdoNetUnitOfWork unitOfWork, IReportsRepository reportsRepository,
                              IApplicationRepository applicationRepository)
 {
     _unitOfWork            = unitOfWork;
     _reportsRepository     = reportsRepository;
     _applicationRepository = applicationRepository;
 }
        public RemoveOldCollectionDataJob(IAdoNetUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
            var db = (UnitOfWorkWithTransaction)unitOfWork;

            _importer = new Importer(db.Transaction);
        }
Example #10
0
        protected void CreateUserAndApplication(IAdoNetUnitOfWork uow, out int accountId, out int applicationId)
        {
            var accountRepos = new AccountRepository(uow);
            var account      = new Account(TestUser.Username, TestUser.Password)
            {
                Email = TestUser.Email
            };

            account.Activate();
            accountRepos.Create(account);
            var userRepos = new UserRepository(uow);
            var user      = new User(account.Id, TestUser.Username)
            {
                EmailAddress = TestUser.Email
            };

            userRepos.CreateAsync(user).GetAwaiter().GetResult();

            var appRepos = new ApplicationRepository(uow);
            var app      = new Application(account.Id, "MyTestApp")
            {
                ApplicationType = TypeOfApplication.DesktopApplication
            };

            appRepos.CreateAsync(app).GetAwaiter().GetResult();
            var member = new ApplicationTeamMember(app.Id, account.Id, "Admin");

            appRepos.CreateAsync(member).GetAwaiter().GetResult();

            accountId     = user.AccountId;
            applicationId = app.Id;
        }
        public ProcessInboundContextCollectionsHandler(IAdoNetUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            var db = (AnalysisUnitOfWork)unitOfWork;

            _importer = new Importer((SqlTransaction)db.Transaction);
        }
Example #12
0
        /// <summary>
        ///     Creates a new instance of <see cref="SaveReportHandler" />.
        /// </summary>
        /// <param name="queue">Queue to store inbound reports in</param>
        /// <exception cref="ArgumentNullException">queueProvider;connectionFactory</exception>
        public SaveReportHandler(IMessageQueue queue, IAdoNetUnitOfWork unitOfWork, ConfigurationStore configStore)
        {
            _unitOfWork = unitOfWork;
            _queue      = queue ?? throw new ArgumentNullException(nameof(queue));
            var config = configStore.Load <ReportConfig>();

            _maxSizeForJsonErrorReport = config.MaxReportJsonSize;
        }
 public ReportReceiverController(IMessageQueueProvider queueProvider, IAdoNetUnitOfWork unitOfWork,
                                 ConfigurationStore configStore, IWhitelistService whitelistService)
 {
     _unitOfWork       = unitOfWork;
     _configStore      = configStore;
     _whitelistService = whitelistService;
     _messageQueue     = queueProvider.Open("ErrorReports");
 }
 public AccountController(IAccountService accountService, IMessageBus messageBus, IAdoNetUnitOfWork uow, IQueryBus queryBus, ConfigurationStore configStore)
 {
     _accountService = accountService;
     _messageBus     = messageBus;
     _uow            = uow;
     _queryBus       = queryBus;
     _configStore    = configStore;
 }
 public ReportReceiverController(IMessageQueueProvider queueProvider, IAdoNetUnitOfWork unitOfWork,
                                 IConfiguration <ReportConfig> reportConfig, IWhitelistService whitelistService)
 {
     _unitOfWork       = unitOfWork;
     _reportConfig     = reportConfig.Value;
     _whitelistService = whitelistService;
     _messageQueue     = queueProvider.Open("ErrorReports");
 }
 public DeleteApiKeyHandler(IAdoNetUnitOfWork unitOfWork)
 {
     if (unitOfWork == null)
     {
         throw new ArgumentNullException(nameof(unitOfWork));
     }
     _unitOfWork = unitOfWork;
 }
 public ApplicationRepository(IAdoNetUnitOfWork uow)
 {
     if (uow == null)
     {
         throw new ArgumentNullException("uow");
     }
     _uow = uow;
 }
Example #18
0
 /// <summary>
 /// Creates a new instance of <see cref="ApplicationDeletedHandler"/>.
 /// </summary>
 public ApplicationDeletedHandler(IAdoNetUnitOfWork uow)
 {
     if (uow == null)
     {
         throw new ArgumentNullException("uow");
     }
     _uow = uow;
 }
 public GetIncidentStatisticsHandler(IAdoNetUnitOfWork unitOfWork)
 {
     if (unitOfWork == null)
     {
         throw new ArgumentNullException("unitOfWork");
     }
     _unitOfWork = unitOfWork;
 }
 /// <summary>
 ///     Creates a new instance of <see cref="DeleteOldReports" />.
 /// </summary>
 /// <param name="unitOfWork">Used for SQL queries</param>
 public DeleteOldReports(IAdoNetUnitOfWork unitOfWork)
 {
     if (unitOfWork == null)
     {
         throw new ArgumentNullException("unitOfWork");
     }
     _unitOfWork = unitOfWork;
 }
Example #21
0
 /// <summary>
 ///     Creates a new instance of <see cref="DeleteEmptyIncidents" />.
 /// </summary>
 /// <param name="unitOfWork">Used for SQL queries</param>
 public DeleteEmptyIncidents(IAdoNetUnitOfWork unitOfWork)
 {
     if (unitOfWork == null)
     {
         throw new ArgumentNullException("unitOfWork");
     }
     _unitOfWork = unitOfWork;
 }
 public static bool TableExists(this IAdoNetUnitOfWork uow, string tableName)
 {
     using (var cmd = uow.CreateCommand())
     {
         cmd.CommandText = @"SELECT name FROM sqlite_master WHERE type='table' AND name=@tableName";
         cmd.AddParameter("tableName", tableName);
         return(tableName.Equals(cmd.ExecuteScalar() as string, StringComparison.OrdinalIgnoreCase));
     }
 }
Example #23
0
        /// <summary>
        ///     Creates a new instance of <see cref="ApiKeyRepository" />.
        /// </summary>
        /// <param name="uow">Active unit of work</param>
        public ApiKeyRepository(IAdoNetUnitOfWork uow)
        {
            if (uow == null)
            {
                throw new ArgumentNullException(nameof(uow));
            }

            _uow = uow;
        }
Example #24
0
 /// <summary>
 ///     Creates a new instance of <see cref="DeleteEmptyIncidents" />.
 /// </summary>
 /// <param name="unitOfWork">Used for SQL queries</param>
 public DeleteEmptyIncidents(IAdoNetUnitOfWork unitOfWork, IConfiguration <ReportConfig> reportConfiguration)
 {
     if (unitOfWork == null)
     {
         throw new ArgumentNullException("unitOfWork");
     }
     _unitOfWork = unitOfWork;
     this._reportConfiguration = reportConfiguration;
 }
Example #25
0
        /// <summary>
        /// Creates a new instance of <see cref="GetApiKeyHandler"/>.
        /// </summary>
        /// <param name="uow">valid uow</param>
        public GetApiKeyHandler(IAdoNetUnitOfWork uow)
        {
            if (uow == null)
            {
                throw new ArgumentNullException(nameof(uow));
            }

            _uow = uow;
        }
 /// <summary>
 ///     Creates a new instance of <see cref="DeleteReportsBelowReportLimit" />.
 /// </summary>
 /// <param name="unitOfWork">Used for SQL queries</param>
 public DeleteReportsBelowReportLimit(IAdoNetUnitOfWork unitOfWork, ConfigurationStore configStore)
 {
     if (unitOfWork == null)
     {
         throw new ArgumentNullException("unitOfWork");
     }
     _unitOfWork  = unitOfWork;
     _configStore = configStore;
 }
Example #27
0
        /// <summary>
        ///     Return an enumerable which uses lazy loading of each row (you must close the connection once done).
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to map</typeparam>
        /// <param name="unitOfWork">Connection to invoke <c>ExecuteReader()</c> on (through a created <c>DbCommand</c>).</param>
        /// <param name="query">Query or short query (<c><![CDATA["projectId = @id AND dateCreated < @minDate"]]></c>)</param>
        /// <param name="parameters">Anonymous object (<c>new { id = dto.ProjectId, @minDate = dto.MinDate }</c>), a dictionary or a value array</param>
        /// <returns>Lazy loaded enumerator</returns>
        /// <remarks>
        ///     <para>
        ///         For more information about the "query" and "parameters" arguments, see <see cref="CommandExtensions.ApplyQuerySql{TEntity}"/>.
        ///     </para>
        ///     <para>
        ///         The returned enumerator will not map each row until it's requested. To be able to do that the
        ///         connection/command/datareader is
        ///         kept open until the enumerator is disposed. Hence it's important that you make sure that the enumerator is
        ///         disposed when you are
        ///         done with it.
        ///     </para>
        ///     <para>Uses <see cref="EntityMappingProvider" /> to find the correct <c><![CDATA[IEntityMapper<TEntity>]]></c>.</para>
        /// </remarks>
        /// <example>
        /// <code>
        /// // All these examples are valid:
        /// <![CDATA[
        /// var users = unitOfWork.ToEnumerable<User>("Age < 10");
        /// var users = unitOfWork.ToEnumerable<User>("SELECT * FROM Users WHERE Age = 37");
        /// var users = unitOfWork.ToEnumerable<User>("FirstName = @name", new { name = user.FirstName });
        /// var users = unitOfWork.ToEnumerable<User>("FirstName = @1 AND Age < @2", 'A%', 35);
        /// var users = unitOfWork.ToEnumerable<User>("SELECT * FROM Users WHERE Age = @age LIMIT 1, 10", new { age = submittedAge });
        /// var users = unitOfWork.ToEnumerable<User>("SELECT * FROM Users WHERE Age = @1 LIMIT 1, 10", user.FirstName);
        /// ]]>
        /// </code>
        /// </example>
        public static IEnumerable <TEntity> ToEnumerable <TEntity>(this IAdoNetUnitOfWork unitOfWork, string query, params object[] parameters)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }

            return(ToEnumerable <TEntity>(unitOfWork, false, query, parameters));
        }
Example #28
0
        /// <summary>
        /// Insert a new item.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity (must have a mapping registred in the <see cref="EntityMappingProvider"/>)</typeparam>
        /// <param name="unitOfWork">Uow to extend</param>
        /// <param name="entity">The entity to create.</param>
        public static void Insert <TEntity>(this IAdoNetUnitOfWork unitOfWork, TEntity entity)
        {
            var mapper = EntityMappingProvider.GetMapper <TEntity>();

            using (var cmd = unitOfWork.CreateCommand())
            {
                mapper.CommandBuilder.InsertCommand(cmd, entity);
                cmd.ExecuteNonQuery();
            }
        }
Example #29
0
        /// <summary>
        /// Truncate table (remove all rows without filling the transaction log)
        /// </summary>
        /// <typeparam name="TEntity">Type of entity (must have a mapping registred in the <see cref="EntityMappingProvider"/>)</typeparam>
        /// <param name="unitOfWork">Uow to extend</param>
        public static void Truncate <TEntity>(this IAdoNetUnitOfWork unitOfWork)
        {
            var mapper = EntityMappingProvider.GetMapper <TEntity>();

            using (var cmd = unitOfWork.CreateCommand())
            {
                mapper.CommandBuilder.TruncateCommand(cmd);
                cmd.ExecuteNonQuery();
            }
        }
        /// <summary>
        /// DELETE a row from the table.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to use, must have an mapper registered in <see cref="EntityMappingProvider"/>.</typeparam>
        /// <param name="unitOfWork">Unit of work to execute command in.</param>
        /// <param name="entity">Uses the primary key column(s), as defined in the mapping, to remove the entry.</param>
        /// <returns>Task to wait on for completion.</returns>
        /// <example>
        /// <code>
        /// <![CDATA[
        /// public async Task DeleteUser(int userId)
        /// {
        ///     return await _unitOfWork.DeleteAsync(new User { Id = userId });
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public static async Task DeleteAsync <TEntity>(this IAdoNetUnitOfWork unitOfWork, TEntity entity)
        {
            var mapper = EntityMappingProvider.GetMapper <TEntity>();

            using (var cmd = (DbCommand)unitOfWork.CreateCommand())
            {
                mapper.CommandBuilder.DeleteCommand(cmd, entity);
                await cmd.ExecuteNonQueryAsync();
            }
        }