public async Task <UserApplication[]> GetForUserAsync(int accountId)
        {
            if (accountId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(accountId));
            }
            using (var cmd = (DbCommand)_uow.CreateCommand())
            {
                cmd.CommandText = @"SELECT a.Id ApplicationId, a.Name ApplicationName, ApplicationMembers.Roles, a.NumberOfFtes NumberOfDevelopers
                                        FROM Applications a
                                        JOIN ApplicationMembers ON (ApplicationMembers.ApplicationId = a.Id) 
                                        WHERE ApplicationMembers.AccountId = @userId
                                        ORDER BY Name";
                cmd.AddParameter("userId", accountId);
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    var apps = new List <UserApplication>();
                    while (await reader.ReadAsync())
                    {
                        var numberOfDevelopers = reader.GetValue(3);
                        var a = new UserApplication
                        {
                            IsAdmin            = reader.GetString(2).Contains("Admin"),
                            ApplicationName    = reader.GetString(1),
                            ApplicationId      = reader.GetInt32(0),
                            NumberOfDevelopers = numberOfDevelopers is DBNull ? null : (decimal?)numberOfDevelopers
                        };
                        apps.Add(a);
                    }

                    return(apps.ToArray());
                }
            }
        }
        public virtual async Task <int> GetAverageReportCountAsync(int applicationId)
        {
            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = @"SELECT 
          [Day]  = DATENAME(WEEKDAY, createdatutc),
          Totals = COUNT(*)
        FROM errorreports
            WHERE applicationid=@appId
        GROUP BY 
          DATENAME(WEEKDAY, createdatutc)";
                cmd.AddParameter("appId", applicationId);
                var numbers = new List <int>();
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        numbers.Add((int)reader[0]);
                    }
                }
                numbers.Sort();

                RemovePeaks(numbers);
                return((int)numbers.Average());
            }
        }
 public async Task UpdateAsync(Incident incident)
 {
     using (var cmd = (DbCommand)_uow.CreateCommand())
     {
         cmd.CommandText =
             @"UPDATE Incidents SET 
                 ApplicationId = @ApplicationId,
                 UpdatedAtUtc = @UpdatedAtUtc,
                 Description = @Description,
                 Solution = @Solution,
                 IsSolutionShared = @IsSolutionShared,
                 AssignedToId = @AssignedTo,
                 AssignedAtUtc = @AssignedAtUtc,
                 State = @state,
                 IgnoringReportsSinceUtc = @IgnoringReportsSinceUtc,
                 IgnoringRequestedBy = @IgnoringRequestedBy
                 WHERE Id = @id";
         cmd.AddParameter("Id", incident.Id);
         cmd.AddParameter("ApplicationId", incident.ApplicationId);
         cmd.AddParameter("UpdatedAtUtc", incident.UpdatedAtUtc);
         cmd.AddParameter("Description", incident.Description);
         cmd.AddParameter("State", (int)incident.State);
         cmd.AddParameter("AssignedTo", incident.AssignedToId);
         cmd.AddParameter("AssignedAtUtc", incident.AssignedAtUtc);
         cmd.AddParameter("IgnoringReportsSinceUtc", incident.IgnoringReportsSinceUtc.ToDbNullable());
         cmd.AddParameter("IgnoringRequestedBy", incident.IgnoringRequestedBy);
         cmd.AddParameter("Solution",
                          incident.Solution == null ? null : EntitySerializer.Serialize(incident.Solution));
         cmd.AddParameter("IsSolutionShared", incident.IsSolutionShared);
         await cmd.ExecuteNonQueryAsync();
     }
 }
        public virtual async Task <int> GetAverageReportCountAsync(int applicationId)
        {
            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = @"SELECT 
                                        [Day]  = DATENAME(WEEKDAY, ReceivedAtUtc),
                                        Totals = cast (COUNT(IncidentReports.Id) as int)
                                    FROM IncidentReports
                                    JOIN Incidents ON (Incidents.Id = IncidentReports.IncidentId)
                                    WHERE applicationid = @appid
                                    GROUP BY DATENAME(WEEKDAY, ReceivedAtUtc)";
                cmd.AddParameter("appId", applicationId);
                var numbers = new List <int>();
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        numbers.Add((int)reader[1]);
                    }
                }
                numbers.Sort();

                RemovePeaks(numbers);
                return((int)numbers.Average());
            }
        }
Esempio n. 5
0
        private async Task GetReportStatistics(GetIncidentResult result)
        {
            using (var cmd = _unitOfWork.CreateCommand())
            {
                cmd.CommandText = @"select cast(createdatutc as date) as Date, count(*) as Count
from errorreports
where incidentid=@incidentId
AND CreatedAtUtc > @date
group by cast(createdatutc as date)";
                var startDate = DateTime.Today.AddDays(-29);
                cmd.AddParameter("date", startDate);
                cmd.AddParameter("incidentId", result.Id);
                var specifiedDays        = (await cmd.ToListAsync <ReportDay>());
                var curDate              = startDate;
                var values               = new ReportDay[30];
                var valuesIndexer        = 0;
                var specifiedDaysIndexer = 0;
                while (curDate <= DateTime.Today)
                {
                    if (specifiedDays.Count > specifiedDaysIndexer && specifiedDays[specifiedDaysIndexer].Date == curDate)
                    {
                        values[valuesIndexer++] = specifiedDays[specifiedDaysIndexer++];
                    }
                    else
                    {
                        values[valuesIndexer++] = new ReportDay()
                        {
                            Date = curDate
                        }
                    };
                    curDate = curDate.AddDays(1);
                }
                result.DayStatistics = values;
            }
        }
 public IEnumerable <Trigger> GetForApplication(int applicationId)
 {
     using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
     {
         cmd.CommandText =
             "SELECT * FROM Triggers WHERE ApplicationId = @applicationId";
         cmd.AddParameter("applicationId", applicationId);
         return(cmd.ToList(new TriggerMapper()).ToList());
     }
 }
        public async Task CreateAsync(ErrorOrigin entity, int applicationId, int incidentId, int reportId)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (applicationId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(applicationId));
            }
            if (incidentId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(incidentId));
            }
            if (reportId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(reportId));
            }

            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = "SELECT Id FROM ErrorOrigins WHERE IpAddress = @ip";
                cmd.AddParameter("ip", entity.IpAddress);
                var id = await cmd.ExecuteScalarAsync();

                if (id is int)
                {
                    await CreateReportInfoAsync((int)id, applicationId, incidentId, reportId);

                    return;
                }
            }

            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO ErrorOrigins (IpAddress, CountryCode, CountryName, RegionCode, RegionName, City, ZipCode, Latitude, Longitude, CreatedAtUtc) "
                                  +
                                  "VALUES (@IpAddress, @CountryCode, @CountryName, @RegionCode, @RegionName, @City, @ZipCode, @Latitude, @Longitude, @CreatedAtUtc);select cast(SCOPE_IDENTITY() as int);";
                cmd.AddParameter("IpAddress", entity.IpAddress);
                cmd.AddParameter("CountryCode", entity.CountryCode);
                cmd.AddParameter("CountryName", entity.CountryName);
                cmd.AddParameter("RegionCode", entity.RegionCode);
                cmd.AddParameter("RegionName", entity.RegionName);
                cmd.AddParameter("City", entity.City);
                cmd.AddParameter("ZipCode", entity.ZipCode);
                //cmd.AddParameter("Point", SqlGeography.Point(command.Latitude, command.Longitude, 4326));
                cmd.AddParameter("Latitude", entity.Latitude);
                cmd.AddParameter("Longitude", entity.Longitude);
                cmd.AddParameter("CreatedAtUtc", DateTime.UtcNow);
                var id = (int)await cmd.ExecuteScalarAsync();
                await CreateReportInfoAsync(id, applicationId, incidentId, reportId);
            }
        }
Esempio n. 8
0
 public async Task CreateAsync(InvalidErrorReport entity)
 {
     using (var cmd = (DbCommand)_uow.CreateCommand())
     {
         cmd.CommandText =
             @"INSERT INTO InvalidErrorReports (Id, AddedAtUtc, ApplicationId, Body, Exception) VALUES(@Id, @AddedAtUtc, @OrganizationId, @ApplicationId, @Body, @Exception)";
         cmd.AddParameter("Id", entity.Id);
         cmd.AddParameter("AddedAtUtc", entity.AddedAtUtc);
         cmd.AddParameter("ApplicationId", entity.ApplicationId);
         cmd.AddParameter("Body", entity.Report);
         cmd.AddParameter("Exception", entity.Exception);
         await cmd.ExecuteNonQueryAsync();
     }
 }
Esempio n. 9
0
        public bool ExistsByClientId(string clientReportId)
        {
            if (clientReportId == null)
            {
                throw new ArgumentNullException("clientReportId");
            }

            using (var cmd = _unitOfWork.CreateCommand())
            {
                cmd.CommandText = "select id from ErrorReports WHERE ErrorId = @Id";
                cmd.AddParameter("id", clientReportId);
                return(cmd.ExecuteScalar() != null);
            }
        }
Esempio n. 10
0
        /// <inheritdoc />
        public void Execute()
        {
            // find incidents with too many reports.
            var incidentsToTruncate = new List <int>();

            using (var cmd = _unitOfWork.CreateCommand())
            {
                cmd.CommandText =
                    @"SELECT TOP 10 Id FROM Incidents WHERE ReportCount > @max ORDER BY ReportCount DESC";
                cmd.AddParameter("max", MaxReportsPerIncident);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        incidentsToTruncate.Add((int)reader[0]);
                    }
                }
            }

            foreach (var incidentId in incidentsToTruncate)
            {
                using (var cmd = _unitOfWork.CreateCommand())
                {
                    var sql = @"DELETE FROM ErrorReports WHERE IncidentId = @id AND Id <= (SELECT Id 
FROM ErrorReports
WHERE IncidentId = @id
ORDER BY Id DESC
OFFSET {0} ROWS
FETCH NEXT 1 ROW ONLY)";
                    cmd.CommandText = string.Format(sql, MaxReportsPerIncident);
                    cmd.AddParameter("id", incidentId);
                    cmd.CommandTimeout = 90;
                    var rows = cmd.ExecuteNonQuery();
                    if (rows > 0)
                    {
                        _logger.Debug("Deleted the oldest " + rows + " reports for incident " + incidentId);
                    }
                }

                using (var cmd = _unitOfWork.CreateCommand())
                {
                    cmd.CommandText =
                        @"UPDATE Incidents SET ReportCount = (SELECT count(Id) FROM ErrorReports WHERE IncidentId = @id) WHERE Id = @id";
                    cmd.AddParameter("id", incidentId);
                    cmd.ExecuteNonQuery();
                }
            }
        }
Esempio n. 11
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);
                }
            }
        }
        public SimilaritiesReport FindForIncident(int incidentId)
        {
            using (var cmd = _uow.CreateCommand())
            {
                cmd.CommandText =
                    @"select Id, Name, Properties from IncidentContextCollections 
                            where IncidentId = @incidentId";
                cmd.AddParameter("incidentId", incidentId);

                var collections = new List <SimilarityCollection>();

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var json       = (string)reader["Properties"];
                        var properties = CoderrDtoSerializer.Deserialize <ContextCollectionPropertyDbEntity[]>(json);
                        var col        = new SimilarityCollection(incidentId, reader.GetString(1));
                        col.GetType().GetProperty("Id").SetValue(col, reader.GetInt32(0));
                        foreach (var entity in properties)
                        {
                            var prop = new Similarity(entity.Name);
                            prop.LoadValues(
                                entity.Values.Select(x => new SimilarityValue(x.Value, x.Percentage, x.Count)).ToArray());
                            col.Properties.Add(prop);
                        }
                        collections.Add(col);
                    }
                }

                return(collections.Count == 0 ? null : new SimilaritiesReport(incidentId, collections));
            }
        }
Esempio n. 13
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());
            }
        }
        /// <summary>
        ///     Method used to execute the query
        /// </summary>
        /// <param name="query">Query to execute.</param>
        /// <returns>
        ///     Task which will contain the result once completed.
        /// </returns>
        public async Task <GetOriginsForIncidentResult> HandleAsync(IMessageContext context, GetOriginsForIncident query)
        {
            using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
            {
                cmd.CommandText = @"SELECT Longitude, Latitude, count(*) 
                                    FROM ErrorOrigins eo
                                    JOIN ErrorReportOrigins ON (eo.Id = ErrorReportOrigins.ErrorOriginId)
                                    WHERE IncidentId = @id AND eo.IsLookedUp = 1
                                    GROUP BY IncidentId, Longitude, Latitude";
                cmd.AddParameter("id", query.IncidentId);
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    var items = new List <GetOriginsForIncidentResultItem>();
                    while (await reader.ReadAsync())
                    {
                        var item = new GetOriginsForIncidentResultItem
                        {
                            Longitude            = (double)reader.GetDecimal(0),
                            Latitude             = (double)reader.GetDecimal(1),
                            NumberOfErrorReports = reader.GetInt32(2)
                        };
                        items.Add(item);
                    }

                    return(new GetOriginsForIncidentResult {
                        Items = items.ToArray()
                    });

                    ;
                }
            }
        }
Esempio n. 15
0
        public async Task <GetEnvironmentsResult> HandleAsync(IMessageContext context, GetEnvironments query)
        {
            var result = new GetEnvironmentsResult();

            string sql;

            if (query.ApplicationId == null)
            {
                sql = @"select Id, Name from Environments ORDER BY Name";
            }
            else
            {
                sql = @"WITH EnvironmentIds
                            AS
                            (
	                            select distinct EnvironmentId 
	                            FROM IncidentEnvironments
	                            JOIN Incidents ON (IncidentId = Incidents.Id)
	                            WHERE ApplicationId = @applicationId
                            )
                            SELECT Id, Name
                            FROM Environments 
                            JOIN EnvironmentIds ON (EnvironmentId=Environments.Id)";
            }

            using (var cmd = _unitOfWork.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.AddParameter("applicationId", query.ApplicationId);
                var items = await cmd.ToListAsync <GetEnvironmentsResultItem>();

                result.Items = items.ToArray();
                return(result);
            }
        }
Esempio n. 16
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);
                }
            }
        }
Esempio n. 17
0
        public async Task <GetReportListResult> ExecuteAsync(GetReportList query)
        {
            using (var cmd = _unitOfWork.CreateCommand())
            {
                int totalCount = 0;
                cmd.AddParameter("incidentId", query.IncidentId);
                if (query.PageNumber > 0)
                {
                    cmd.CommandText = "SELECT cast(count(Id) as int) FROM ErrorReports WHERE IncidentId = @incidentId";
                    totalCount      = (int)cmd.ExecuteScalar();

                    cmd.CommandText =
                        "SELECT Id, Title, CreatedAtUtc, RemoteAddress, Exception FROM ErrorReports WHERE IncidentId = @incidentId ORDER BY Id DESC";

                    cmd.Paging(query.PageNumber, query.PageSize);
                }
                else
                {
                    cmd.CommandText =
                        "SELECT Id, Title, CreatedAtUtc, RemoteAddress, Exception FROM ErrorReports WHERE IncidentId = @incidentId ORDER BY Id DESC";
                }
                var items = await cmd.ToListAsync <GetReportListResultItem>();

                return(new GetReportListResult(items.ToArray())
                {
                    PageNumber = query.PageNumber,
                    PageSize = query.PageSize,
                    TotalCount = totalCount
                });
            }
        }
        /// <inheritdoc />
        public void Execute()
        {
            // find incidents with too many reports.
            var incidentsToTruncate = new List <Tuple <int, int> >();

            using (var cmd = _unitOfWork.CreateCommand())
            {
                cmd.CommandText =
                    @"SELECT TOP(5) IncidentId, count(Id)
                        FROM ErrorReports
                        GROUP BY IncidentId
                        HAVING Count(IncidentId) > @max
                        ORDER BY count(Id) DESC";
                cmd.AddParameter("max", MaxReportsPerIncident);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        incidentsToTruncate.Add(new Tuple <int, int>((int)reader[0], (int)reader[1]));
                    }
                }
            }

            foreach (var incidentIdAndCount in incidentsToTruncate)
            {
                //do not delete more then 500 at a time.
                var rowsToDelete = Math.Min(500, incidentIdAndCount.Item2 - MaxReportsPerIncident);
                using (var cmd = _unitOfWork.CreateCommand())
                {
                    var sql = $@"With RowsToDelete AS
                                (
                                    SELECT TOP {rowsToDelete} Id
                                    FROM ErrorReports 
                                    WHERE IncidentId = {incidentIdAndCount.Item1}
                                    ORDER BY ID ASC
                                )
                                DELETE FROM RowsToDelete";
                    cmd.CommandText    = sql;
                    cmd.CommandTimeout = 90;
                    var rows = cmd.ExecuteNonQuery();
                    if (rows > 0)
                    {
                        _logger.Debug("Deleted the oldest " + rows + " reports for incident " + incidentIdAndCount);
                    }
                }
            }
        }
Esempio n. 19
0
 /// <inheritdoc />
 public async Task <Account> FindByActivationKeyAsync(string activationKey)
 {
     using (var cmd = _uow.CreateCommand())
     {
         cmd.CommandText = "SELECT * FROM Accounts WHERE ActivationKey=@key";
         cmd.AddParameter("key", activationKey);
         return(await cmd.FirstOrDefaultAsync(new AccountMapper()));
     }
 }
 private async Task <IList <InboundCollection> > GetInboundCollections()
 {
     using (var cmd = _unitOfWork.CreateCommand())
     {
         cmd.CommandText = "SELECT TOP(50) Id, ReportId, Body FROM ErrorReportCollectionInbound";
         return(await cmd.ToListAsync <InboundCollection>());
     }
 }
Esempio n. 21
0
        private IReadOnlyList <ErrorReportEntity> GetReportsUsingSql()
        {
            using (var cmd = _unitOfWork.CreateCommand())
            {
                cmd.CommandText = @"SELECT QueueReports.*
                                    FROM QueueReports
                                    ORDER BY QueueReports.Id";
                cmd.Limit(10);

                try
                {
                    var reports     = new List <ErrorReportEntity>();
                    var idsToRemove = new List <int>();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var json = "";
                            try
                            {
                                json = (string)reader["body"];
                                var report    = _reportDtoConverter.LoadReportFromJson(json);
                                var newReport = _reportDtoConverter.ConvertReport(report, (int)reader["ApplicationId"]);
                                newReport.RemoteAddress = (string)reader["RemoteAddress"];
                                reports.Add(newReport);
                                idsToRemove.Add(reader.GetInt32(0));
                            }
                            catch (Exception ex)
                            {
                                _logger.Error("Failed to deserialize " + json, ex);
                            }
                        }
                    }
                    if (idsToRemove.Any())
                    {
                        _unitOfWork.ExecuteNonQuery("DELETE FROM QueueReports WHERE Id IN (" +
                                                    string.Join(",", idsToRemove) + ")");
                    }
                    return(reports);
                }
                catch (Exception ex)
                {
                    throw cmd.CreateDataException(ex);
                }
            }
        }
 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));
     }
 }
 public async Task ExecuteAsync(DeleteTrigger command)
 {
     using (var cmd = (DbCommand)_uow.CreateCommand())
     {
         cmd.CommandText = "DELETE FROM Triggers WHERE Id = @id";
         cmd.AddParameter("id", command.Id);
         await cmd.ExecuteNonQueryAsync();
     }
 }
        public async Task <Application[]> GetForUserAsync(int accountId)
        {
            if (accountId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(accountId));
            }
            using (var cmd = (DbCommand)_uow.CreateCommand())
            {
                cmd.CommandText = @"SELECT * 
                                        FROM Applications 
                                        JOIN ApplicationMembers ON (ApplicationMembers.ApplicationId = Applications.Id) 
                                        WHERE ApplicationMembers.AccountId = @userId";
                cmd.AddParameter("userId", accountId);
                var result = await cmd.ToListAsync <Application>();

                return(result.ToArray());
            }
        }
 public async Task <TriggerDTO[]> HandleAsync(IMessageContext context, GetTriggersForApplication query)
 {
     using (var cmd = (DbCommand)_unitOfWork.CreateCommand())
     {
         cmd.CommandText = "SELECT * FROM Triggers WHERE [ApplicationId]=@appId";
         cmd.AddParameter("appId", query.ApplicationId);
         return((await cmd.ToListAsync <TriggerDTO>()).ToArray());
     }
 }
Esempio n. 26
0
        public IEnumerable <IncidentSummaryDTO> FindLatestForOrganization(int count)
        {
            using (var cmd = _uow.CreateCommand())
            {
                cmd.CommandText =
                    "SELECT TOP " + count + " * FROM Incidents WHERE IsSolved=0 ORDER BY UpdatedAtUtc DESC";


                return(cmd.ToList <IncidentSummaryDTO>());
            }
        }
Esempio n. 27
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();
            }
        }
Esempio n. 28
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();
            }
        }
Esempio n. 30
0
 public async Task CreateAsync(User user)
 {
     using (var cmd = (DbCommand)_uow.CreateCommand())
     {
         cmd.CommandText = "INSERT INTO Users (AccountId, UserName, EmailAddress) VALUES(@id, @userName, @email)";
         cmd.AddParameter("id", user.AccountId);
         cmd.AddParameter("userName", user.UserName);
         cmd.AddParameter("email", user.EmailAddress);
         await cmd.ExecuteNonQueryAsync();
     }
 }