コード例 #1
0
    public async Task WillMergeDuplicatedStacks()
    {
        var utcNow        = SystemClock.UtcNow;
        var originalStack = StackData.GenerateStack();

        originalStack.Id = ObjectId.GenerateNewId().ToString();
        originalStack.TotalOccurrences = 100;
        var duplicateStack = originalStack.DeepClone();

        duplicateStack.Id               = ObjectId.GenerateNewId().ToString();
        duplicateStack.Status           = StackStatus.Fixed;
        duplicateStack.TotalOccurrences = 10;
        duplicateStack.LastOccurrence   = originalStack.LastOccurrence.AddMinutes(1);
        duplicateStack.SnoozeUntilUtc   = originalStack.SnoozeUntilUtc = null;
        duplicateStack.DateFixed        = duplicateStack.LastOccurrence.AddMinutes(1);
        duplicateStack.Tags.Add("stack2");
        duplicateStack.References.Add("stack2");
        duplicateStack.OccurrencesAreCritical = true;

        originalStack = await _stackRepository.AddAsync(originalStack, o => o.ImmediateConsistency());

        duplicateStack = await _stackRepository.AddAsync(duplicateStack, o => o.ImmediateConsistency());

        await _eventRepository.AddAsync(EventData.GenerateEvents(count: 100, stackId: originalStack.Id), o => o.ImmediateConsistency());

        await _eventRepository.AddAsync(EventData.GenerateEvents(count: 10, stackId: duplicateStack.Id), o => o.ImmediateConsistency());

        var results = await _stackRepository.FindAsync(q => q.ElasticFilter(Query <Stack> .Term(s => s.DuplicateSignature, originalStack.DuplicateSignature)));

        Assert.Equal(2, results.Total);

        var migration = GetService <FixDuplicateStacks>();
        var context   = new MigrationContext(GetService <ILock>(), _logger, CancellationToken.None);
        await migration.RunAsync(context);

        await RefreshDataAsync();

        results = await _stackRepository.FindAsync(q => q.ElasticFilter(Query <Stack> .Term(s => s.DuplicateSignature, originalStack.DuplicateSignature)));

        Assert.Single(results.Documents);

        var updatedOriginalStack = await _stackRepository.GetByIdAsync(originalStack.Id, o => o.IncludeSoftDeletes());

        Assert.False(updatedOriginalStack.IsDeleted);
        var updatedDuplicateStack = await _stackRepository.GetByIdAsync(duplicateStack.Id, o => o.IncludeSoftDeletes());

        Assert.True(updatedDuplicateStack.IsDeleted);

        Assert.Equal(originalStack.CreatedUtc, updatedOriginalStack.CreatedUtc);
        Assert.Equal(110, updatedOriginalStack.TotalOccurrences);
        Assert.Equal(StackStatus.Fixed, updatedOriginalStack.Status);
        Assert.Equal(duplicateStack.LastOccurrence, updatedOriginalStack.LastOccurrence);
        Assert.Null(updatedOriginalStack.SnoozeUntilUtc);
        Assert.Equal(duplicateStack.DateFixed, updatedOriginalStack.DateFixed);
        Assert.Equal(originalStack.Tags.Count + 1, updatedOriginalStack.Tags.Count);
        Assert.Contains("stack2", updatedOriginalStack.Tags);
        Assert.Equal(originalStack.References.Count + 1, updatedOriginalStack.References.Count);
        Assert.Contains("stack2", updatedOriginalStack.References);
        Assert.True(updatedOriginalStack.OccurrencesAreCritical);
    }
コード例 #2
0
        public async Task GetAsync()
        {
            Log.SetLogLevel <EventRepository>(LogLevel.Trace);
            var ev = await _repository.AddAsync(new PersistentEvent { CreatedUtc = SystemClock.UtcNow, Date = new DateTimeOffset(SystemClock.UtcNow.Date, TimeSpan.Zero) });

            Assert.Equal(ev, await _repository.GetByIdAsync(ev.Id));
        }
コード例 #3
0
        public async Task CreateAsync(Guid id, string name, string description, DateTime startDate, DateTime endDate)
        {
            var @event = await _eventRepository.CheckOrFailAsync(name);

            @event = new Event(id, name, description, startDate, endDate);
            await _eventRepository.AddAsync(@event);
        }
コード例 #4
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator        = new CreateEventCommandValidator();
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new Exceptions.ValidationException(validationResult);
            }

            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            var email = new Email()
            {
                To      = "*****@*****.**",
                Body    = $"A new event was created: {request}",
                Subject = "A new event was created"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Mailing about event {@event.EventId} failed due to an error with the mail service: {ex.Message}");
            }

            return(@event.EventId);
        }
コード例 #5
0
        public async Task <EventDto> AddAsync(EventDto dto)
        {
            var result = (await eventRepository.AddAsync(dto.ToEntity())).ToDto();
            await eventRepository.SaveChangesAsync();

            return(result);
        }
コード例 #6
0
    public async Task <ActionResult <DtoEvent> > Add([FromBody] DtoEvent dtoEvent)
    {
        log.LogInformation("Adding the new dtoEvent {dtoEvent}", dtoEvent);
        if (!ModelState.IsValid)
        {
            return(BadRequest(getModelStateErrorMessage()));
        }
        if (dtoEvent.ID != 0)
        {
            return(BadRequest("Cannot add event with a valid id"));
        }

        try
        {
            var @event = mapper.Map <Event>(dtoEvent);
            log.LogInformation("Mapped {dtoEvent} to {event}", dtoEvent, @event);
            var newEvent = await eventRepository.AddAsync(@event);

            log.LogInformation("Got back {newEvent} from event repository", newEvent);
            return(mapper.Map <DtoEvent>(newEvent));
        }
        catch (Exception ex)
        {
            log.LogError("Got an exception adding event {ex}", ex);
            throw;
        }
    }
コード例 #7
0
        public static async Task CreateSearchDataAsync(ExceptionlessElasticConfiguration configuration, IEventRepository eventRepository, EventParserPluginManager parserPluginManager, bool updateDates = false)
        {
            string path = Path.Combine("..", "..", "..", "Search", "Data");

            foreach (string file in Directory.GetFiles(path, "event*.json", SearchOption.AllDirectories))
            {
                if (file.EndsWith("summary.json"))
                {
                    continue;
                }

                var events = parserPluginManager.ParseEvents(await File.ReadAllTextAsync(file), 2, "exceptionless/2.0.0.0");
                Assert.NotNull(events);
                Assert.True(events.Count > 0);
                foreach (var ev in events)
                {
                    if (updateDates)
                    {
                        ev.Date       = SystemClock.OffsetNow;
                        ev.CreatedUtc = SystemClock.UtcNow;
                    }

                    ev.CopyDataToIndex(Array.Empty <string>());
                }

                await eventRepository.AddAsync(events, o => o.ImmediateConsistency());
            }

            configuration.Events.QueryParser.Configuration.MappingResolver.RefreshMapping();
        }
コード例 #8
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator        = new CreateEventCommandValidator(eventRepository);
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new ValidationException(validationResult);
            }

            var @event = mapper.Map <Event>(request);

            @event = await eventRepository.AddAsync(@event);

            var email = new Email
            {
                To      = "*****@*****.**",
                Subject = $"A new event was created: {request}",
                Body    = $"A new event was created: {request}"
            };

            try
            {
                await emailService.SendEmail(email);
            }
            catch (Exception)
            {
                throw;
            }

            return(@event.EventId);
        }
コード例 #9
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator        = new CreateEventCommandValidator(_eventRepository);
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new ValidationException(validationResult);
            }

            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            var email = new Email()
            {
                To      = "*****@*****.**", Body = $"A new event was created: {request}",
                Subject = "A new event was created"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(@event.EventId);
        }
コード例 #10
0
        public async Task <EventModel> CreateEventAsync(EventModel eventModel)
        {
            if (eventModel is null)
            {
                throw new ArgumentNullException(nameof(eventModel));
            }

            var eventEntity = new Data.Entities.Event
            {
                Title       = eventModel.Title,
                Description = eventModel.Description,
                StartDate   = eventModel.StartDate,
                EndDate     = eventModel.EndDate,
                AllDay      = eventModel.AllDay,
                Place       = eventModel.Place,
                Users       = eventModel.Users.Select(e => new User
                {
                    Id = e.Id,
                }).ToList()
            };

            eventEntity = await _eventRepository.AddAsync(eventEntity);

            return(new EventModel
            {
                Id = eventEntity.Id,
                Title = eventEntity.Title,
                Description = eventEntity.Description,
                StartDate = eventModel.StartDate,
                EndDate = eventModel.EndDate,
                AllDay = eventModel.AllDay,
                Place = eventModel.Place
            });
        }
コード例 #11
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator        = new CreateEventCommandValidator(_eventRepository);
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new Exceptions.ValidationException(validationResult);
            }
            //CreateCommand'den Event'a mapleme yapılıyor. Veritabaı kaydı için entitiye çevriliyor.
            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            var email = new Email()
            {
                To      = "*****@*****.**",
                Body    = $"A new event was created:{request}",
                Subject = "A new event"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (Exception ex)
            {
                //will be logged
            }

            return(@event.EventId);
        }
コード例 #12
0
        public async Task <ICommandResult> Handle(CreateEventCommand command)
        {
            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult(false, "Invalid operation!", command.Notifications));
            }

            var sensorMock = _sensorService.GetSensorFromString(command.Tag);

            var sensor = await _sensorRepository.GetSensorByNameAndRegionAndCountry(sensorMock);

            var status = string.IsNullOrEmpty(command.Value.ToString()) ? EventStatus.Error : EventStatus.Processed;

            var @event = new Event
                         (
                sensor.Id,
                command.Value,
                command.Timestamp,
                status
                         );

            await _eventRepository.AddAsync(@event);

            await _eventWs.sendEventsToAll();

            return(new GenericCommandResult(true, "Event created!", new { @event.Id }));
        }
コード例 #13
0
            public async Task <EventResponse> Handle(CreateEventCommand request, CancellationToken cancellationToken)
            {
                var entity = mapper.Map <Domain.Entities.Event>(request);
                await eventRepository.AddAsync(entity);

                return(mapper.Map <EventResponse>(entity));
            }
コード例 #14
0
        public async Task <ActionResult <EventData> > AddAsync([FromBody] EventData ev)
        {
            //try
            //{
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //throw new InvalidOperationException("No vaild");
            var result = await eventRepo.AddAsync(ev);

            //return result; //200
            //return Created("", result); //201
            //return Created($"/api/events/{result.Id}", result);
            return(CreatedAtAction(nameof(GetById), new { id = result.Id }, result));
            //}
            //catch (Exception ex)
            //{
            //    var error = new
            //    {
            //        Message = ex.Message
            //    };
            //    return StatusCode(StatusCodes.Status500InternalServerError, error);
            //}
        }
コード例 #15
0
        private async Task CreateEventsAsync()
        {
            string path = Path.Combine("..", "..", "..", "Search", "Data");
            var    parserPluginManager = GetService <EventParserPluginManager>();

            foreach (string file in Directory.GetFiles(path, "event*.json", SearchOption.AllDirectories))
            {
                if (file.EndsWith("summary.json"))
                {
                    continue;
                }

                var events = parserPluginManager.ParseEvents(File.ReadAllText(file), 2, "exceptionless/2.0.0.0");
                Assert.NotNull(events);
                Assert.True(events.Count > 0);
                foreach (var ev in events)
                {
                    ev.CopyDataToIndex(Array.Empty <string>());
                }

                await _repository.AddAsync(events, o => o.ImmediateConsistency());
            }

            GetService <ExceptionlessElasticConfiguration>().Events.Event.QueryParser.Configuration.RefreshMapping();
        }
コード例 #16
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator        = new CreateEventCommandValidator(_eventRepository);
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new Exceptions.ValidationException(validationResult);
            }

            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            //Sending email notification to admin address
            var email = new Email()
            {
                To = "*****@*****.**", Body = $"A new event was created: {request}", Subject = "A new event was created"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (Exception ex)
            {
                //this shouldn't stop the API from doing else so this can be logged
                _logger.LogError($"Mailing about event {@event.EventId} failed due to an error with the mail service: {ex.Message}");
            }

            return(@event.EventId);
        }
コード例 #17
0
        private async Task <PersistentEvent> CreateSessionStartEventAsync(EventContext startContext, DateTime?lastActivityUtc, bool?isSessionEnd)
        {
            var startEvent         = startContext.Event.ToSessionStartEvent(lastActivityUtc, isSessionEnd, startContext.Organization.HasPremiumFeatures, startContext.IncludePrivateInformation);
            var startEventContexts = new List <EventContext> {
                new EventContext(startEvent, startContext.Organization, startContext.Project)
            };

            if (_assignToStack.Enabled)
            {
                await _assignToStack.ProcessBatchAsync(startEventContexts).AnyContext();
            }
            if (_updateStats.Enabled)
            {
                await _updateStats.ProcessBatchAsync(startEventContexts).AnyContext();
            }
            await _eventRepository.AddAsync(startEvent).AnyContext();

            if (_locationPlugin.Enabled)
            {
                await _locationPlugin.EventBatchProcessedAsync(startEventContexts).AnyContext();
            }

            await SetSessionStartEventIdAsync(startContext.Project.Id, startContext.Event.GetSessionId(), startEvent.Id).AnyContext();

            return(startEvent);
        }
コード例 #18
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator       = new CreateEventCommandValidator(_eventRepository);
            var validatorResult = await validator.ValidateAsync(request);

            if (validatorResult.Errors.Count > 0)
            {
                throw new Exceptions.ValidationException(validatorResult);
            }

            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            var email = new Email()
            {
                To = "*****@*****.**", Body = $"Event created: {request}", Subject = "Event"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (Exception)
            {
            }
            return(@event.EventId);
        }
コード例 #19
0
        public async Task <Guid> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var validator = new CreateEventCommandValidator(_eventRepository);

            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Any())
            {
                throw new ValidationException(validationResult);
            }

            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            var email = new Email
            {
                To = "*****@*****.**", Subject = "Event Notification", Body = $"{request} was created"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (Exception)
            {
                // app shouldn't stop
            }


            return(@event.EventId);
        }
コード例 #20
0
ファイル: EventIndexTests.cs プロジェクト: zzms/Exceptionless
        private async Task CreateEventsAsync()
        {
            _configuration.DeleteIndexes(_client);
            _configuration.ConfigureIndexes(_client);

            var parserPluginManager = IoC.GetInstance <EventParserPluginManager>();

            foreach (var file in Directory.GetFiles(@"..\..\Search\Data\", "event*.json", SearchOption.AllDirectories))
            {
                if (file.EndsWith("summary.json"))
                {
                    continue;
                }

                var events = parserPluginManager.ParseEvents(File.ReadAllText(file), 2, "exceptionless/2.0.0.0");
                Assert.NotNull(events);
                Assert.True(events.Count > 0);
                foreach (var ev in events)
                {
                    ev.CopyDataToIndex();
                }

                await _repository.AddAsync(events);
            }

            await _client.RefreshAsync();
        }
コード例 #21
0
        public async Task <Guid> Handle(
            CreateEventCommand request,
            CancellationToken cancellationToken)
        {
            var validator        = new CreateEventCommandValidator(_eventRepository);
            var validationResult = await validator.ValidateAsync(request);

            if (validationResult.Errors.Count > 0)
            {
                throw new Exceptions.ValidationException(validationResult);
            }

            var @event = _mapper.Map <Event>(request);

            @event = await _eventRepository.AddAsync(@event);

            var email = new Email()
            {
                To      = "*****@*****.**",
                Body    = $"A new event was created: {request}",
                Subject = "A new event was created"
            };

            try
            {
                await _emailService.SendEmail(email);
            }
            catch (System.Exception)
            {
                //This should't stop the API from doing else so this
                //can be logged
            }

            return(@event.EventId);
        }
コード例 #22
0
        public async Task CreateAsync(Guid id, string name, string description, DateTime startDate, DateTime endDate)
        {
            Logger.Info("Create event");
            var @event = await _eventRepository.IsExistsAsync(name);

            @event = new Event(id, name, description, startDate, endDate);
            await _eventRepository.AddAsync(@event);
        }
コード例 #23
0
        public async Task GetAsync()
        {
            await RemoveDataAsync();

            var ev = await _repository.AddAsync(new RandomEventGenerator().GeneratePersistent());

            var result = await _repository.GetByIdAsync(ev.Id);

            Assert.NotNull(result);
        }
コード例 #24
0
        private async Task <EventContext> CreateSessionStartEventAsync(EventContext context, DateTime?lastActivityUtc, bool?isSessionEnd)
        {
            var startEvent = context.Event.ToSessionStartEvent(lastActivityUtc, isSessionEnd, context.Organization.HasPremiumFeatures);

            var startEventContexts = new List <EventContext> {
                new EventContext(startEvent)
                {
                    Project = context.Project, Organization = context.Organization
                }
            };

            await _assignToStack.ProcessBatchAsync(startEventContexts).AnyContext();

            await _updateStats.ProcessBatchAsync(startEventContexts).AnyContext();

            await _eventRepository.AddAsync(startEvent).AnyContext();

            return(startEventContexts.Single());
        }
コード例 #25
0
 private async Task CreateEventAsync(User user, string text, GamificationEnums.EventType type, CancellationToken cancellationToken)
 {
     var eventEntity = new Event()
     {
         Description = text,
         User        = user,
         Type        = type
     };
     await _eventRepository.AddAsync(eventEntity, cancellationToken);
 }
コード例 #26
0
        public async Task <ActionResult <EventData> > AddAsync([FromBody] EventData ev)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await eventRepo.AddAsync(ev);

            //return Created($"/api/events/{result.Id}", result); // Adds a location header in the response
            return(CreatedAtAction(nameof(GetById), new { id = result.Id }, result));
        }
コード例 #27
0
        public async Task CreateAsync(Guid id, string name, string description, DateTime startDate, DateTime endDate)
        {
            var @event = await _eventRepository.GetAsync(name);

            if (@event != null)
            {
                throw new Exception($"Event named: '{name}' already exists");
            }
            @event = new Event(id, name, description, startDate, endDate);
            await _eventRepository.AddAsync(@event);
        }
コード例 #28
0
        public async Task CanCleanupSoftDeletedOrganization()
        {
            var organization = OrganizationData.GenerateSampleOrganization(_billingManager, _plans);

            organization.IsDeleted = true;
            await _organizationRepository.AddAsync(organization, o => o.ImmediateConsistency());

            var project = await _projectRepository.AddAsync(ProjectData.GenerateSampleProject(), o => o.ImmediateConsistency());

            var stack = await _stackRepository.AddAsync(StackData.GenerateSampleStack(), o => o.ImmediateConsistency());

            var persistentEvent = await _eventRepository.AddAsync(EventData.GenerateEvent(organization.Id, project.Id, stack.Id), o => o.ImmediateConsistency());

            await _job.RunAsync();

            Assert.Null(await _organizationRepository.GetByIdAsync(organization.Id, o => o.IncludeSoftDeletes()));
            Assert.Null(await _projectRepository.GetByIdAsync(project.Id, o => o.IncludeSoftDeletes()));
            Assert.Null(await _stackRepository.GetByIdAsync(stack.Id, o => o.IncludeSoftDeletes()));
            Assert.Null(await _eventRepository.GetByIdAsync(persistentEvent.Id, o => o.IncludeSoftDeletes()));
        }
コード例 #29
0
ファイル: EventService.cs プロジェクト: PatiDevv/Evento
        public async Task CreateAsync(Guid id, string name, string description, DateTime startDate, DateTime endDate)
        {
            Logger.Trace($"Został utworzony nowy event o nazwie {name}, rozpoczyna sie ${startDate} konczy sie {endDate}");
            var @event = await _eventRepository.GetAsync(name);

            if (@event != null)
            {
                throw new Exception($"Event named: '{name}' already exists.");
            }
            @event = new Event(id, name, description, startDate, endDate);
            await _eventRepository.AddAsync(@event);
        }
コード例 #30
0
ファイル: EventService.cs プロジェクト: KKowalewski24/Evento
        public async Task CreateAsync(Guid eventId, string name, string description,
                                      DateTime startDate, DateTime endDate)
        {
            if (await _eventRepository.GetByNameAsync(name) != null)
            {
                throw new EventAlreadyExistsException();
            }

            await _eventRepository.AddAsync(
                new Event(eventId, name, description, startDate, endDate)
                );
        }