Example #1
0
        private static async Task Sample2(IEventStore store)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options, TransactionScopeAsyncFlowOption.Enabled))
            {
                var repo      = new Repository <ShoppingCart>(store);
                var streamId  = SequentialGuid.NewGuid();
                var aggregate = new ShoppingCart(streamId, SequentialGuid.NewGuid());
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 1", quantity: 3);
                var item2Id = SequentialGuid.NewGuid();
                aggregate.AddItem(item2Id, name: "Product 2", quantity: 1);
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 3", quantity: 5);
                aggregate.RemoveItem(item2Id);
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 4", quantity: 1);

                var snap = aggregate.GetSnapshot();

                await repo.SaveChangesAsync(aggregate);

                await store.Advanced.UpdateSnapshotAsync(aggregate.Id, snap.Version, snap.State);

                aggregate = await repo.LoadAsync(streamId);

                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 5", quantity: 5);
                await repo.SaveChangesAsync(aggregate);

                aggregate = await repo.LoadAsync(streamId);

                Console.WriteLine($@"Aggregate expected version 7 = {aggregate.CommittedVersion}");

                scope.Complete();
            }
        }
Example #2
0
        public async Task AddAsync(GrupoIndexDTO grupoDTO)
        {
            Grupo grupo = grupoDTO.BuildModel();
            await _repository.AddAsync(grupo);

            await _repository.SaveChangesAsync();
        }
Example #3
0
        public virtual async Task <IActionResult> Put(int id, T item)
        {
            if (id != item.Id)
            {
                return(BadRequest());
            }
            await repo.UpdateAsync(item);

            try
            {
                await repo.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!repo.FindBy(a => a.Id == id).Any())
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(NoContent());
        }
Example #4
0
        private async Task SeedCustomCakeImg(CakeItDbContext db)
        {
            var repo = new Repository <CustomCakeImg>(db);
            var mock = new Mock <ILogger <CustomCakeService> >();
            ILogger <CustomCakeService> logger = mock.Object;
            var service = new CustomCakeService(null, repo, this.Mapper, logger);

            CustomCakeImgViewModel model1 = new CustomCakeImgViewModel
            {
                Side = "White Cigarettes",
                Top  = "Habana",
                Name = "Habana" + " " + "White Cigarettes",
                Img  = "https://someurl.bg"
            };

            await service.AddCustomCakeImg(model1);

            CustomCakeImgViewModel model2 = new CustomCakeImgViewModel
            {
                Side = "Dark Cigarettes",
                Top  = "Meksiko",
                Name = "Meksiko" + " " + "Dark Cigarettes",
                Img  = "https://otherurl.bg"
            };

            await service.AddCustomCakeImg(model2);

            await repo.SaveChangesAsync();
        }
Example #5
0
        /// <summary>
        /// Implementation of <see cref="ICategoryCommands.UpdateCategoryInfo(Guid, string, string, string, string, bool, DateTime?, DateTime?)"/>
        /// </summary>
        /// <param name="categoryId">The category id</param>
        /// <param name="code">The category code</param>
        /// <param name="name">The category name</param>
        /// <param name="url">The category url</param>
        /// <param name="description">The category description</param>
        /// <param name="isVisible">Whether the category is visible</param>
        /// <param name="visibleFrom">The date and time from when the category is visible</param>
        /// <param name="visibleTo">The date and time till when the category is visible</param>
        /// <returns></returns>
        public virtual async Task UpdateCategoryInfo(Guid categoryId, string code, string name, string url, string description, bool isVisible, DateTime?visibleFrom, DateTime?visibleTo)
        {
            try
            {
                if (categoryId == Guid.Empty)
                {
                    throw new ArgumentException("value cannot be empty", nameof(categoryId));
                }

                var category = await Repository.GetByKeyAsync <Category>(categoryId);

                if (category.Code != code)
                {
                    category.ChangeCode(code);
                }

                if (category.Name != name)
                {
                    category.ChangeName(name);
                }

                if (category.Url != url)
                {
                    category.ChangeUrl(url);
                }

                if (category.Description != description)
                {
                    category.ChangeDescription(description);
                }

                if (category.IsVisible != isVisible)
                {
                    if (isVisible)
                    {
                        if (!visibleFrom.HasValue && !visibleTo.HasValue)
                        {
                            category.SetAsVisible();
                        }
                        else
                        {
                            category.SetAsVisible(visibleFrom, visibleTo);
                        }
                    }
                    else
                    {
                        category.Hide();
                    }
                }

                await Repository.SaveChangesAsync();

                var @event = new CategoryInfoUpdatedEvent(categoryId, code, name, url, description, isVisible, visibleFrom, visibleTo);
                EventBus.RaiseEvent(@event);
            }
            catch
            {
                throw;
            }
        }
Example #6
0
        /// <summary>
        /// Implementation of <see cref="ICategoryCommands.CreateNewCategory(string, string, string, string, bool, DateTime?, DateTime?)"/>
        /// </summary>
        /// <param name="code">The category code</param>
        /// <param name="name">The category name</param>
        /// <param name="url">The category url</param>
        /// <param name="description">The category description</param>
        /// <param name="isVisible">Whether the category is visible</param>
        /// <param name="visibleFrom">The date and time of when the category starts to be visible</param>
        /// <param name="visibleTo">The date and time till when the category is visible</param>
        /// <returns>The category id</returns>
        public virtual async Task <Guid> CreateNewCategory(string code, string name, string url, string description, bool isVisible, DateTime?visibleFrom, DateTime?visibleTo)
        {
            try
            {
                var category = Category.Create(code, name, url);
                if (!string.IsNullOrEmpty(description))
                {
                    category.ChangeDescription(description);
                }

                if (isVisible)
                {
                    if (!visibleFrom.HasValue && !visibleTo.HasValue)
                    {
                        category.SetAsVisible();
                    }
                    else
                    {
                        category.SetAsVisible(visibleFrom, visibleTo);
                    }
                }

                Repository.Add(category);
                await Repository.SaveChangesAsync();

                var @event = new CategoryCreatedEvent(category.Id, name, code);
                EventBus.RaiseEvent(@event);

                return(category.Id);
            }
            catch
            {
                throw;
            }
        }
Example #7
0
        /// <summary>
        /// Implementation of <see cref="ICategoryCommands.RemoveParentForCategory(Guid, Guid)"/>
        /// </summary>
        /// <param name="categoryId">The category id</param>
        /// <param name="parentId">The category parent id</param>
        /// <returns></returns>
        public virtual async Task RemoveParentForCategory(Guid categoryId, Guid parentId)
        {
            try
            {
                if (categoryId == Guid.Empty)
                {
                    throw new ArgumentException("value cannot be empty", nameof(categoryId));
                }

                var category = await Repository.GetByKeyAsync <Category>(categoryId);

                if (parentId != Guid.Empty)
                {
                    var parent = await Repository.GetByKeyAsync <Category>(parentId);

                    category.RemoveParent(parent);
                    await Repository.SaveChangesAsync();

                    var @event = new CategoryChildRemovedEvent(parentId, categoryId);
                    EventBus.RaiseEvent(@event);
                }
            }
            catch
            {
                throw;
            }
        }
Example #8
0
        /// <summary>
        /// Implementation of <see cref="ICategoryCommands.AddCategoryChild(Guid, Guid)"/>
        /// </summary>
        /// <param name="categoryId">The category id</param>
        /// <param name="childId">The child id</param>
        /// <returns></returns>
        public virtual async Task AddCategoryChild(Guid categoryId, Guid childId)
        {
            try
            {
                if (categoryId == Guid.Empty)
                {
                    throw new ArgumentException("value cannot be empty", nameof(categoryId));
                }

                if (childId == Guid.Empty)
                {
                    throw new ArgumentException("value cannot be empty", nameof(childId));
                }

                var category = await Repository.GetByKeyAsync <Category>(categoryId);

                var child = await Repository.GetByKeyAsync <Category>(childId);

                category.AddChild(child);
                await Repository.SaveChangesAsync();

                var @event = new CategoryChildAddedEvent(categoryId, childId);
                EventBus.RaiseEvent(@event);
            }
            catch
            {
                throw;
            }
        }
Example #9
0
        private async Task <int> Vote(int itemId, bool upvote)
        {
            var value = upvote ? 1 : -1;

            var user = await GetRequestUser();

            var solution = await Get(itemId);

            var castVote = await Repository.Votes.GetVoteByItemIdAndUser(itemId, user.UserId);

            var vote = new Sql.Models.Vote();

            vote.ItemId = itemId;
            vote.Value  = value;

            if (castVote == null)
            {
                vote.Voter = user;

                await Repository.Votes.Create(vote);

                await Repository.SaveChangesAsync();
            }
            else if (castVote.Value != vote.Value)
            {
                castVote.Value = vote.Value;
                await Repository.SaveChangesAsync();
            }

            return(await Repository.Votes.GetCountForItemId(solution.SolutionId));
        }
        public async Task <string> EditAsync(int id, Sql.Models.Problem problem)
        {
            if (problem == null)
            {
                throw new ArgumentNullException(nameof(problem));
            }

            if (string.IsNullOrEmpty(problem.Description) || string.IsNullOrWhiteSpace(problem.Name) || !problem.TestCases.Any())
            {
                throw new Exception("All details are required to create a problem");
            }

            var user = await GetRequestUser();

            var existingProblem = await Repository.Problem.Get(id);

            if (existingProblem == null)
            {
                throw new ArgumentNullException(nameof(problem));
            }

            if (user.UserId != existingProblem.Author.UserId)
            {
                throw new Exception("User is not author!");
            }

            existingProblem.TestCases   = problem.TestCases;
            existingProblem.Description = problem.Description;
            existingProblem.Language    = problem.Language;
            existingProblem.Name        = problem.Name;

            await Repository.SaveChangesAsync();

            return(Url.Action("Index", new { problem.ProblemId }));
        }
        public override async Task HandleAsync(ImportBaylorRegistrationsCommand command)
        {
            var sr  = new StringReader(command.ViewModel.Data);
            var csv = new CsvReader(sr);

            csv.Configuration.MissingFieldFound = null;
            if (command.ViewModel.TabDelimeter)
            {
                csv.Configuration.Delimiter = "\t";
            }
            csv.Read();
            csv.ReadHeader();
            while (csv.Read())
            {
                var email = csv.GetField("Username");
                var user  = await _userManager.FindByEmailAsync(email);

                if (user == null)
                {
                    continue;
                }

                var completed = csv.GetField("Registration complete"); //yes or no
                user.IsBaylorRegistrationCompleted = (completed == "yes");
            }

            await Repository.SaveChangesAsync();
        }
        /// <summary>
        /// Implementation of <see cref="IBrandCommands.CreateNewBrand(string, string, string, Image)"/>
        /// </summary>
        /// <param name="name">The brand's name</param>
        /// <param name="url">The brand's unique url</param>
        /// <param name="description">The brand's description</param>
        /// <param name="logo">The brand's logo</param>
        /// <returns>The brand id</returns>
        public virtual async Task <Guid> CreateNewBrand(string name, string url, string description, Image logo)
        {
            try
            {
                var brand = Brand.Create(name, url);
                if (!string.IsNullOrEmpty(description))
                {
                    brand.ChangeDescription(description);
                }

                if (logo != null)
                {
                    brand.SetLogo(logo);
                }

                Repository.Add(brand);
                await Repository.SaveChangesAsync();

                var @event = new BrandCreatedEvent(brand.Id, brand.Name);
                EventBus.RaiseEvent(@event);

                return(brand.Id);
            }
            catch
            {
                throw;
            }
        }
        public async Task CreateAsync(CreateBrandBindingModel model)
        {
            Brand brand = this.Mapper.Map <Brand>(model);
            await Repository.AddAsync(brand);

            await Repository.SaveChangesAsync();
        }
Example #14
0
        public async Task Should_Delete_Entities_Async()
        {
            var options      = DatabaseOptionsWithData <FakeDbContext>(typeof(FakeDbContext));
            var fakeEntities = new FakeEntities();
            var fakeEntity   = fakeEntities[0];

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var entitiesToDelete = await repository.SelectAsync();

                await repository.DeleteAsync(entitiesToDelete);

                var saveCount = await repository.SaveChangesAsync();

                Assert.Equal(entitiesToDelete.Count(), saveCount);
            }

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var result = await repository.SelectAsync();

                var singleResult = result.Single(prop => prop.EntityCode == fakeEntity.EntityCode);

                Assert.Equal(fakeEntities.Count, result.Count());
                Assert.All(result, prop => Assert.True(prop.IsDeleted));
                Assert.All(result, prop => Assert.True(prop.DeletedTime == prop.ModifiedTime));
                Assert.All(result, prop => Assert.True(prop.ModifiedTime > prop.CreatedTime));
                Assert.All(result, prop => Assert.Equal(Principal.Identity.Name, prop.ModifiedBy));
            }
        }
Example #15
0
        public async Task Should_Update_Entities_Async()
        {
            var options      = DatabaseOptionsWithData <FakeDbContext>(typeof(FakeDbContext));
            var fakeEntities = new FakeEntities();

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var entitiesToUpdate = (await repository.SelectAsync()).ToList();
                entitiesToUpdate.ForEach(entity => entity.EntityName = "Modified");

                var result = await repository.UpdateAsync(entitiesToUpdate);

                var saveCount = await repository.SaveChangesAsync();

                Assert.All(entitiesToUpdate, prop => Assert.True(prop.Id > 0));
                Assert.Equal(entitiesToUpdate.Count, saveCount);
            }

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var result = await repository.SelectAsync();

                Assert.Equal(fakeEntities.Count, result.Count());
                Assert.All(result, prop => Assert.Equal("Modified", prop.EntityName));
                Assert.All(result, prop => Assert.Equal(Principal.Identity.Name, prop.ModifiedBy));
                Assert.All(result, prop => Assert.True(prop.ModifiedTime > prop.CreatedTime));
            }
        }
Example #16
0
        public async Task Should_Insert_Entities_Async()
        {
            var options      = DatabaseOptions <FakeDbContext>();
            var fakeEntities = new FakeEntities();

            fakeEntities.ForEach(entity => entity.FakeChildEntities = null);

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var result = await repository.InsertAsync(fakeEntities);

                var saveCount = await repository.SaveChangesAsync();

                Assert.True(result.Count() > 0);
                Assert.All(result, prop => Assert.True(prop.Id > 0));
                Assert.Equal(fakeEntities.Count, saveCount);
            }

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var result = await repository.SelectAsync();

                var entryDateTime = result.First().CreatedTime;

                Assert.Equal(fakeEntities.Count, result.Count());
                Assert.All(result, prop => Assert.True(prop.Id > 0));
                Assert.All(result, prop => Assert.Equal(Principal.Identity.Name, prop.CreatedBy));
                Assert.All(result, prop => Assert.Equal(entryDateTime, prop.CreatedTime, TimeSpan.FromMinutes(1)));
            }
        }
Example #17
0
        public async Task Should_Insert_Entity_Async()
        {
            var options    = DatabaseOptions <FakeDbContext>();
            var fakeEntity = new FakeEntities()[0];

            fakeEntity.FakeChildEntities = null;

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var result = await repository.InsertAsync(fakeEntity);

                var saveCount = await repository.SaveChangesAsync();

                Assert.True(result.Id > 0);
                Assert.Equal(1, saveCount);
            }

            using (IDbContext context = new FakeDbContext(options))
            {
                var repository = new Repository <FakeEntity>(context);

                var result = await repository.SelectAsync(prop => prop.EntityCode == fakeEntity.EntityCode);

                Assert.Single(result);
                Assert.True(result.First().Id > 0);
                Assert.True(result.First().EntityCode == fakeEntity.EntityCode);
                Assert.True(result.First().EntityName == fakeEntity.EntityName);
                Assert.Equal(Principal.Identity.Name, result.First().CreatedBy);
                Assert.True(result.First().CreatedTime > DateTime.MinValue);
            }
        }
        public async Task <ActionResult> PutAsync(int id, [FromBody] Event evt)
        {
            Event evtDB;

            try
            {
                evtDB = await Repository.GetByIdAsync(id);
            }
            catch (Exception ex)
            {
                // internal server error
                return(StatusCode(500, ex));
            }
            if (evtDB == null)
            {
                return(NotFound()); // if resource doesn't exist, i'll return an error
            }
            if (id != evtDB.Id)
            {
                return(BadRequest("cannot change ID"));
            }
            try
            {
                await Repository.UpdateAsync(evt, id);

                await Repository.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                // internal server error
                return(StatusCode(500, ex));
            }
            // return proper 204 No Content response
            return(NoContent()); // success = Ok()
        }
        public override async Task HandleAsync(TCommand command)
        {
            var dbRegistration = await Repository.Set <TeamContestRegistration>()
                                 .SingleOrDefaultAsync(r => r.Id == command.RegistrationId);

            if (dbRegistration == null)
            {
                throw new EntityNotFoundException();
            }

            var validationResult = await ValidateEditTeamContestRegistrationAsync(command.ViewModel);

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

            _mapper.Map(command.ViewModel, dbRegistration);

            if (dbRegistration.Status == ContestRegistrationStatus.Completed && dbRegistration.RegistrationDateTime == null)
            {
                dbRegistration.RegistrationDateTime = DateTimeService.SfuServerNow;
                dbRegistration.RegistredBy          = await _userManager.FindByEmailAsync(_currentUserService.Email);
            }

            await Repository.SaveChangesAsync();
        }
        public async Task <ActionResult> DeleteAsync(int id)
        {
            Event evtDB;

            try
            {
                evtDB = await Repository.GetByIdAsync(id);

                if (evtDB == null)
                {
                    return(NotFound()); // if resource doesn't exist, i'll return an error
                }
                evtDB = null;

                await Repository.DeleteAsync(id);

                await Repository.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                // internal server error
                return(StatusCode(500, ex));
            }
            // return proper 204 No Content response
            return(NoContent()); // success = Ok()
        }
Example #21
0
        /// <summary>
        /// Implementation of <see cref="ICustomerCommands.RestoreCustomer(Guid)"/>
        /// </summary>
        /// <param name="customerId">The customer id</param>
        /// <returns></returns>
        public async Task RestoreCustomer(Guid customerId)
        {
            if (customerId == Guid.Empty)
            {
                throw new ArgumentException("value cannot be empty", nameof(customerId));
            }

            var customer = await Repository.GetByKeyAsync <Customer>(customerId);

            if (customer == null)
            {
                throw new ArgumentOutOfRangeException(nameof(customerId));
            }

            try
            {
                customer.Restore();
                if (customer.HasAccount && customer.Account.IsLocked)
                {
                    await AuthClient.EnableAccount(customer.Account.UserId);

                    customer.UnlockAccount();
                }

                await Repository.SaveChangesAsync();

                var @event = new CustomerRestoredEvent(customerId);
                EventBus.RaiseEvent(@event);
            }
            catch
            {
                throw;
            }
        }
Example #22
0
        public override async Task <FeedViewModel> AddAsync <TCreateRequest>(TCreateRequest createRequest)
        {
            if (!(createRequest is CreateFeedRequest request))
            {
                var message = GetImproperRequestErrorMessage(typeof(TCreateRequest), nameof(IFeedService));
                throw new ArgumentException(message);
            }

            var entity        = createRequest.CreateEntity();
            var createdEntity = await Repository.AddAsync(entity);

            await Repository.SaveChangesAsync();

            var tempEntity = await Repository.GetFeedWithAfflictionsById(createdEntity.Id);

            createdEntity.DogAfflictions = tempEntity.DogAfflictions;
            var viewModel = new FeedViewModel();

            viewModel.Construct(createdEntity);

            await _imageService.AddImagesAsync(request.Photos, viewModel.UniqueId);

            viewModel.PhotosIds = await _imageService.GetImagesIdsByOwnerGuidAsync(
                viewModel.UniqueId,
                CancellationToken.None);

            return(viewModel);
        }
Example #23
0
        /// <summary>
        /// Implementation of <see cref="ICustomerCommands.RemoveCustomerBillingInformation(Guid, Guid)"/>
        /// </summary>
        /// <param name="customerId">The customer id</param>
        /// <param name="billingInfoId">The billing info id</param>
        /// <returns></returns>
        public async Task RemoveCustomerBillingInformation(Guid customerId, Guid billingInfoId)
        {
            if (customerId == Guid.Empty)
            {
                throw new ArgumentException("value cannot be empty", nameof(customerId));
            }

            if (billingInfoId == Guid.Empty)
            {
                throw new ArgumentException("value cannot be empty", nameof(billingInfoId));
            }

            var customer = await Repository.GetByKeyAsync <Customer>(customerId);

            if (customer == null)
            {
                throw new ArgumentOutOfRangeException(nameof(customerId));
            }

            customer.RemoveBillingInfo(billingInfoId);
            await Repository.SaveChangesAsync();

            var @event = new BillingoInformationRemovedEvent(customerId, billingInfoId);

            EventBus.RaiseEvent(@event);
        }
Example #24
0
        /// <summary>
        /// Implementation of <see cref="ICustomerCommands.RemoveCustomerShippingAddress(Guid, Guid)"/>
        /// </summary>
        /// <param name="customerId">The customer id</param>
        /// <param name="addressId">The address id</param>
        /// <returns></returns>
        public async Task RemoveCustomerShippingAddress(Guid customerId, Guid addressId)
        {
            if (customerId == Guid.Empty)
            {
                throw new ArgumentException("value cannot be empty", nameof(customerId));
            }

            if (addressId == Guid.Empty)
            {
                throw new ArgumentException("value cannot be empty", nameof(addressId));
            }

            var customer = await Repository.GetByKeyAsync <Customer>(customerId);

            if (customer == null)
            {
                throw new ArgumentOutOfRangeException(nameof(customerId));
            }

            customer.RemoveShippingAddress(addressId);
            await Repository.SaveChangesAsync();

            var @event = new ShippingAddressRemovedEvent(customerId, addressId);

            EventBus.RaiseEvent(@event);
        }
Example #25
0
        /// <summary>
        /// Implementation of <see cref="ICustomerCommands.RegisterNewPerson(string, string, string, Gender, DateTime)"/>
        /// </summary>
        /// <param name="firstName">The first name</param>
        /// <param name="lastName">The last name</param>
        /// <param name="nationalIdentificationNumber">The national identification number</param>
        /// <param name="gender">The gender</param>
        /// <param name="birthDate">The birth date</param>
        /// <returns></returns>
        public async Task RegisterNewPerson(string firstName, string lastName, string nationalIdentificationNumber, Gender gender, DateTime birthDate)
        {
            if (string.IsNullOrWhiteSpace(firstName))
            {
                throw new ArgumentException("value cannot be empty", nameof(firstName));
            }

            if (string.IsNullOrWhiteSpace(lastName))
            {
                throw new ArgumentException("value cannot be empty", nameof(lastName));
            }

            if (birthDate >= DateTime.Today)
            {
                throw new ArgumentException("Birth date cannot be after today", nameof(birthDate));
            }

            var person = Person.Register(firstName, lastName, gender, birthDate);

            if (!string.IsNullOrWhiteSpace(nationalIdentificationNumber))
            {
                person.SetNationalIdentificationNumber(nationalIdentificationNumber);
            }

            Repository.Add(person);
            await Repository.SaveChangesAsync();

            var @event = new PersonRegisteredEvent(person.Id, firstName, lastName, gender, birthDate);

            EventBus.RaiseEvent(@event);
        }
Example #26
0
        /// <summary>
        /// Implementation of <see cref="ICustomerCommands.RemoveCustomerAccount(Guid)"/>
        /// </summary>
        /// <param name="customerId">The customer id</param>
        /// <returns></returns>
        public async Task RemoveCustomerAccount(Guid customerId)
        {
            if (customerId == Guid.Empty)
            {
                throw new ArgumentException("value cannot be empty", nameof(customerId));
            }

            var customer = await Repository.GetByKeyAsync <Customer>(customerId);

            if (customer == null)
            {
                throw new ArgumentOutOfRangeException(nameof(customerId));
            }

            try
            {
                var    accountId = customer.Account.UserId;
                string userName  = customer.Account.UserName;

                customer.RemoveAccount();
                await AuthClient.DisableAccount(accountId);

                await Repository.SaveChangesAsync();

                var @event = new CustomerAccountRemovedEvent(customerId, userName);
                EventBus.RaiseEvent(@event);
            }
            catch
            {
                throw;
            }
        }
        public async Task <IActionResult> Join([FromBody] GroupMembership membership)
        {
            var group = await Repository.Groups
                        .Include(x => x.Members)
                        .FirstOrDefaultAsync(x => x.Id == membership.GroupId);

            // Can't join non-existant groups.
            if (group == null)
            {
                return(NotFound());
            }
            // Only group owners or the member themselves can manage membership.
            if (group.OwnerId != User.Id && membership.MemberId != User.Id)
            {
                return(Unauthorized());
            }
            // Can't join the same group twice.
            if (group.Members.Any(x => x == membership))
            {
                return(BadRequest());
            }

            await Repository.GroupMemberships.AddAsync(new GroupMembership
            {
                Id       = membership.Id,
                GroupId  = membership.GroupId,
                MemberId = membership.MemberId
            });

            await Repository.SaveChangesAsync();

            return(Ok());
        }
Example #28
0
        /// <summary>
        /// Implementation of <see cref="ICustomerCommands.RegisterNewCompany(string, string, string)"/>
        /// </summary>
        /// <param name="companyName">The company name</param>
        /// <param name="vatNumber">The company vat number</param>
        /// <param name="nationalIdentificationNumber">The company national identification number</param>
        /// <returns></returns>
        public async Task RegisterNewCompany(string companyName, string vatNumber, string nationalIdentificationNumber)
        {
            if (string.IsNullOrWhiteSpace(companyName))
            {
                throw new ArgumentException("value cannot be empty", nameof(companyName));
            }

            if (string.IsNullOrWhiteSpace(vatNumber))
            {
                throw new ArgumentException("value cannot be empty", nameof(vatNumber));
            }

            var company = Company.Register(companyName, vatNumber);

            if (!string.IsNullOrWhiteSpace(nationalIdentificationNumber))
            {
                company.SetNationalIdentificationNumber(nationalIdentificationNumber);
            }

            Repository.Add(company);
            await Repository.SaveChangesAsync();

            var @event = new CompanyRegisteredEvent(company.Id, companyName, vatNumber);

            EventBus.RaiseEvent(@event);
        }
        public async Task <IActionResult> Create([FromBody] Group group)
        {
            // Can't create groups for other users.
            if (group.OwnerId != User.Id)
            {
                return(Unauthorized());
            }

            // Don't create the exact same group twice.
            if (Repository.Groups.Any(x => x.Id == group.Id))
            {
                return(BadRequest());
            }

            await Repository.Groups.AddAsync(new Group
            {
                Id      = group.Id,
                Name    = group.Name,
                OwnerId = group.OwnerId
            });

            await Repository.SaveChangesAsync();

            return(Ok());
        }
        public async Task <IActionResult> UpdateData(string id, [FromBody] string data)
        {
            if (data == null)
            {
                data = "";
            }
            string accid = AuthMan.GetAccountId(this);
            var    ok    = await repo.CanUpdateAsync(accid, id);

            if (ok == false)
            {
                return(Forbid());
            }

            var obj = await repo.GetAsync(accid, id);

            if (obj == null)
            {
                return(Forbid());
            }
            obj.Data = data;
            await repo.SaveChangesAsync();

            return(Ok());
        }
Example #31
0
 public static async Task LogAsync(Credentials user, LogActivityType activity, string message)
 {
     using (var repo = new Repository())
     {
         var log = repo.Create<activity_log>();
         log.action_id = (int) activity;
         log.credentials_id = Authentication.Credentials.CredId;
         log.message = message;
         log.created = await repo.GetNowAsync();
         repo.Add(log);
         await repo.SaveChangesAsync();
     }
 }
Example #32
0
        public static async Task UpdateRank()
        {
            using (var dataContext = new AppServiceDataContext())
            {
                var repository = new Repository(dataContext);

                var team = await repository.Query<Team>().FirstOrDefaultAsync();
                if (team != null)
                {
                    Console.WriteLine("Loaded team: {0}", team.Id);
                    var random = new Random();
                    var increment = random.Next(-5, 5);
                    team.Rank += increment;
                    await repository.SaveChangesAsync();
                    Console.WriteLine("Updated team rank to: {0}", team.Rank);
                }
            }
        }
        public static void InitFormContainerActions(TileContainer con)
        {
            con.Properties.ItemCheckMode = TileItemCheckMode.Single;
            var deleteAction = new DelegateAction(() => true, async () =>
            {
                var checkedTile = con.Items.FirstOrDefault(x => x.Checked.HasValue && x.Checked.Value) as Tile;
                if (checkedTile == null) return;
                if (checkedTile.Tag == null) return;
                int? formId = TagHelper.GetFormDataId(checkedTile.Tag.ToString());
                if (!formId.HasValue)
                    return;
                var view = (WindowsUIView)con.Manager.View;
                var fly = view.ContentContainers.FindFirst(x => x is Flyout && x.Caption == "Сообщение") as Flyout;
                var formType = ((Page)checkedTile.ActivationTarget).Document.ControlName;
                
                switch (formType)
                {
                    case "FormData1":
                    case "ArchiveFormData1":
                    case "FormData2":
                    case "ArchiveFormData2":
                        {
                            try
                            {
                                using (var repo = new Repository())
                                {
                                    var data = await repo.GetEduFormDataById(formId.Value);
                                    var form = await repo.GetForm(data.form_id);
                                    var res = fly != null ? GuiUtility.ShowFlyoutMessage(view, fly, "Подтверждение", string.Format("Удалить форму \"{0}\"?", form), FlyoutCommand.Yes, FlyoutCommand.No) : MessageBox.Show(string.Format("Удалить форму {0}?", form), "Подтверждение", MessageBoxButtons.OKCancel);
                                    if (res == DialogResult.No)
                                        return;
                                    if (await form.IsBlockedAsync())
                                    {
                                        var mes = fly != null
                                            ? GuiUtility.ShowFlyoutMessage(view, fly, "Информация",
                                                "Удаление формы отключено, так как срок сдачи истек.\n" +
                                                "Чтобы иметь возможность удалить эту форму, обратитесь к региональному оператору")
                                            : MessageBox.Show("Удаление формы отключено, так как срок сдачи истек.\n" +
                                                "Чтобы иметь возможность удалить эту форму, обратитесь к региональному оператору", "Информация", MessageBoxButtons.OKCancel);
                                        return;
                                    }

                                    var file = await repo.GetFile(data.file_id);
                                    var forms = file.edu_form_data;

                                    var tag = TagHelper.GetFormDataTag(TagHelper.TagType.Tile, data);
                                    var tiles = con.Items.Find(t => t.Tag.ToString() == tag).ToArray();

                                    repo.RemoveRange(forms);
                                    repo.Remove(file);
                                    await repo.SaveChangesAsync();

                                    if (con.Items.Count == 1)
                                        con.Items.Clear();
                                    else
                                        con.Items.RemoveRange(tiles);
                                }
                            }
                            catch (Exception ex)
                            {
                                var mess = fly != null ?
                                    GuiUtility.ShowFlyoutMessage(view, fly, "Ошибка удаления", ex.Message) :
                                    MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK);
                            }
                            break;
                        }
                    case "FormData3":
                    case "ArchiveFormData3":
                    case "FormData4":
                    case "ArchiveFormData4":
                        {
                            try
                            {
                                using (var repo = new Repository())
                                {
                                    var data = await repo.GetMunitFormDataById(formId.Value);
                                    var form = await repo.GetForm(data.form_id);
                                    var res = fly != null ? GuiUtility.ShowFlyoutMessage(view, fly, "Подтверждение", string.Format("Удалить форму \"{0}\"?", form), FlyoutCommand.Yes, FlyoutCommand.No) : MessageBox.Show(string.Format("Удалить форму {0}?", form), "Подтверждение", MessageBoxButtons.OKCancel);
                                    if (res == DialogResult.No)
                                        return;
                                    if (await form.IsBlockedAsync())
                                    {
                                        var mes = fly != null
                                            ? GuiUtility.ShowFlyoutMessage(view, fly, "Информация",
                                                "Удаление формы отключено, так как срок сдачи истек.\n" +
                                                "Чтобы иметь возможность удалить эту форму, обратитесь к региональному оператору")
                                            : MessageBox.Show("Удаление формы отключено, так как срок сдачи истек.\n" +
                                                "Чтобы иметь возможность удалить эту форму, обратитесь к региональному оператору", "Информация", MessageBoxButtons.OKCancel);
                                        return;
                                    }

                                    var file = data.file;
                                    var forms = file.municipality_form_data;

                                    var tag = TagHelper.GetFormDataTag(TagHelper.TagType.Tile, data);
                                    var tiles = con.Items.Find(t => t.Tag.ToString() == tag).ToArray();

                                    repo.RemoveRange(forms);
                                    repo.Remove(file);
                                    await repo.SaveChangesAsync();

                                    if (con.Items.Count == 1)
                                        con.Items.Clear();
                                    else
                                        con.Items.RemoveRange(tiles);
                                }
                            }
                            catch (Exception ex)
                            {
                                var mess = fly != null ?
                                    GuiUtility.ShowFlyoutMessage(view, fly, "Ошибка удаления", ex.Message) :
                                    MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK);
                            }
                            break;
                        }
                    case "FormData5":
                    case "ArchiveFormData5":
                    case "FormData6":
                    case "ArchiveFormData6":
                        {
                            try
                            {
                                using (var repo = new Repository())
                                {
                                    var data = await repo.GetRegionFormDataById(formId.Value);
                                    var res = fly != null ? GuiUtility.ShowFlyoutMessage(view, fly, "Подтверждение", string.Format("Удалить форму \"{0}\"?", data.form), FlyoutCommand.Yes, FlyoutCommand.No) : MessageBox.Show(string.Format("Удалить форму {0}?", data.form), "Подтверждение", MessageBoxButtons.OKCancel);
                                    if (res == DialogResult.No)
                                        return;
                                    var file = data.file;
                                    var forms = file.region_form_data;

                                    var tag = TagHelper.GetFormDataTag(TagHelper.TagType.Tile, data);
                                    var tiles = con.Items.Find(t => t.Tag.ToString() == tag).ToArray();

                                    repo.RemoveRange(forms);
                                    repo.Remove(file);
                                    await repo.SaveChangesAsync();

                                    if (con.Items.Count == 1)
                                        con.Items.Clear();
                                    else
                                        con.Items.RemoveRange(tiles);
                                }
                            }
                            catch (Exception ex)
                            {
                                var mess = fly != null ?
                                    GuiUtility.ShowFlyoutMessage(view, fly, "Ошибка удаления", ex.Message) :
                                    MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK);
                            }
                            break;
                        }
                }
            })
            {
                Caption = "Удалить форму",
                Type = ActionType.Context,
                Edge = ActionEdge.Right,
                Behavior = ActionBehavior.HideBarOnClick
            };
            var searchAction = new DelegateAction(() => true, () => (con.Manager.View as WindowsUIView).ShowSearchPanel())
            {
                Caption = "Поиск",
                Type = ActionType.Default,
                Edge = ActionEdge.Left,
                Behavior = ActionBehavior.HideBarOnClick
            };
            con.Actions.Clear();
            con.Actions.Add(deleteAction);
            con.Actions.Add(searchAction);
        }
        public async Task<IHttpActionResult> PostExcelFile()
        {
            var stream = await Request.Content.ReadAsStreamAsync();

            IList<Questionary> questionaries;

            using (var package = new ExcelPackage(stream))
            {
                if (package.Workbook.Worksheets.Count == 0)
                {
                    throw new InvalidOperationException("Your Excel file does not contain any work sheets");
                }

                var worksheet = package.Workbook.Worksheets.First();

                questionaries = FromExcelSheet(worksheet);
            }

            if (questionaries.Count == 0)
            {
                throw new InvalidOperationException("Excel file is empty");
            }

            using (var repository = new Repository<Questionary>())
            {
                repository.DeleteAll();
                foreach (var questionary in questionaries)
                {
                    repository.Add(questionary);
                }
                await repository.SaveChangesAsync();
            }

            return Ok();
        }
        public async Task<IHttpActionResult> Post(Questionary questionary)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            using (var repository = new Repository<Questionary>())
            {
                repository.Add(questionary);
                await repository.SaveChangesAsync();
                return Ok();
            }
        }