public async Task <int> SendMessage(Message message, User activeUser)
        {
            IEnumerable <int> recipientIds = new List <int>();

            message.SenderUserId = activeUser.Id;

            using (var trans = TransactionScopeFactory.Create())
            {
                if (!await MessageRepo.UserIsChannelMember(message.ChannelId, activeUser.Id))
                {
                    throw new CritterException($"Could not send that message, recipient does not exist!",
                                               $"Invalid channel provided - channel: {message.ChannelId}, sender: {message.SenderUserId}",
                                               System.Net.HttpStatusCode.BadRequest);
                }
                recipientIds = await MessageRepo.GetAllChannelMemberIds(message.ChannelId);

                message.Id = await MessageRepo.CreateMessage(message, recipientIds.Where(id => id != activeUser.Id), activeUser.Id);

                trans.Complete();
            }

            await Task.WhenAll(
                recipientIds.Select(async userId =>
                                    await(SignalRHubContext?.Clients?.Group(NotificationHub.GetUserGroupIdentifier(userId))
                                          ?.ReceiveNotification(
                                              new NewMessageAlert(new MessageDetails()
            {
                Message = message, SenderUsername = activeUser.Username
            }, message.ChannelId)
                                              ) ?? Task.CompletedTask)
                                    )
                );;

            return(message.Id);
        }
Example #2
0
        public async Task PurchaseShopItem(int itemId, User activeUser)
        {
            using (var trans = TransactionScopeFactory.Create())
            {
                (ShopItem shopItem, InventoryItem item)purchaseItem = (await ShopRepo.RetrieveShopItemByItemId(itemId)).FirstOrDefault();

                if (purchaseItem.shopItem?.Price > 0 && activeUser.Cash >= purchaseItem.shopItem.Price)
                {
                    var userChanges = new List <(int UserId, int CashDelta)> {
                        (activeUser.Id, (-1) * purchaseItem.shopItem.Price.Value)
                    };
                    if (purchaseItem.item.OwnerUserId != null)
                    {
                        userChanges.Add((purchaseItem.item.OwnerUserId.Value, purchaseItem.shopItem.Price.Value));//owner can be null if NPC shop
                    }
                    await UserDomain.ChangeUsersCash(userChanges);

                    await InventoryDomain.TransferItemOwner(activeUser.Id, purchaseItem.item.Id, purchaseItem.item.OwnerUserId);

                    if (!await ShopRepo.RemoveShopItem(itemId))
                    {
                        throw new CritterException("Couldn't purchase item!", $"Failed to remove {itemId} from its shop", System.Net.HttpStatusCode.Conflict);
                    }
                }
                trans.Complete();
            }
        }
        public async Task TransferItemOwner(int?recipientUserId, int itemId, int?ownerId)
        {
            using (var trans = TransactionScopeFactory.Create())
            {
                if (!(await InventoryRepo.UpdateItemOwner(itemId, recipientUserId, ownerId)))
                {
                    throw new CritterException("Could not transfer item ownership!",
                                               $"Something went wrong with item {itemId}, trying to move to user {recipientUserId} from {ownerId}", System.Net.HttpStatusCode.Conflict);
                }

                trans.Complete();
            }
        }
Example #4
0
        public async Task ExecuteAsync(AddImageAssetCommand command, IExecutionContext executionContext)
        {
            var imageAsset = new ImageAsset();

            imageAsset.FileDescription       = command.Title;
            imageAsset.FileName              = SlugFormatter.ToSlug(command.Title);
            imageAsset.DefaultAnchorLocation = command.DefaultAnchorLocation;
            _entityTagHelper.UpdateTags(imageAsset.ImageAssetTags, command.Tags, executionContext);
            _entityAuditHelper.SetCreated(imageAsset, executionContext);

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                // if adding, save this up front
                _dbContext.ImageAssets.Add(imageAsset);

                await _imageAssetFileService.SaveAsync(command.File, imageAsset, nameof(command.File));

                command.OutputImageAssetId = imageAsset.ImageAssetId;
                scope.Complete();
            }

            await _messageAggregator.PublishAsync(new ImageAssetAddedMessage()
            {
                ImageAssetId = imageAsset.ImageAssetId
            });
        }
Example #5
0
        public async Task ExecuteAsync(DeleteImageAssetCommand command, IExecutionContext executionContext)
        {
            var imageAsset = await _dbContext
                             .ImageAssets
                             .FilterById(command.ImageAssetId)
                             .SingleOrDefaultAsync();

            if (imageAsset != null)
            {
                imageAsset.IsDeleted = true;
                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(ImageAssetEntityDefinition.DefinitionCode, imageAsset.ImageAssetId), executionContext);

                    await _dbContext.SaveChangesAsync();

                    scope.Complete();
                }
                _imageAssetCache.Clear(command.ImageAssetId);

                await _messageAggregator.PublishAsync(new ImageAssetDeletedMessage()
                {
                    ImageAssetId = command.ImageAssetId
                });
            }
        }
Example #6
0
        public async Task ExecuteAsync(UpdateImageAssetCommand command, IExecutionContext executionContext)
        {
            bool hasNewFile = command.File != null;

            var imageAsset = await _dbContext
                             .ImageAssets
                             .Include(a => a.ImageAssetTags)
                             .ThenInclude(a => a.Tag)
                             .FilterById(command.ImageAssetId)
                             .SingleOrDefaultAsync();

            imageAsset.FileDescription       = command.Title;
            imageAsset.FileName              = SlugFormatter.ToSlug(command.Title);
            imageAsset.DefaultAnchorLocation = command.DefaultAnchorLocation;
            _entityTagHelper.UpdateTags(imageAsset.ImageAssetTags, command.Tags, executionContext);
            _entityAuditHelper.SetUpdated(imageAsset, executionContext);

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                if (hasNewFile)
                {
                    await _imageAssetFileService.SaveAsync(command.File, imageAsset, nameof(command.File));
                }

                await _dbContext.SaveChangesAsync();

                scope.Complete();
            }

            if (hasNewFile)
            {
                await _imageAssetFileCache.ClearAsync(imageAsset.ImageAssetId);
            }
            _imageAssetCache.Clear(imageAsset.ImageAssetId);
        }
Example #7
0
        public async Task ExecuteAsync(DeleteCustomEntityDraftVersionCommand command, IExecutionContext executionContext)
        {
            var draft = await _dbContext
                        .CustomEntityVersions
                        .Include(v => v.CustomEntity)
                        .SingleOrDefaultAsync(v => v.CustomEntityId == command.CustomEntityId &&
                                              v.WorkFlowStatusId == (int)WorkFlowStatus.Draft);

            if (draft != null)
            {
                _permissionValidationService.EnforceCustomEntityPermission <CustomEntityUpdatePermission>(draft.CustomEntity.CustomEntityDefinitionCode);

                var definitionCode = draft.CustomEntity.CustomEntityDefinitionCode;
                var versionId      = draft.CustomEntityVersionId;

                using (var scope = _transactionScopeFactory.Create())
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(CustomEntityVersionEntityDefinition.DefinitionCode, draft.CustomEntityVersionId));

                    _dbContext.CustomEntityVersions.Remove(draft);
                    await _dbContext.SaveChangesAsync();

                    scope.Complete();
                }
                _customEntityCache.Clear(definitionCode, command.CustomEntityId);

                await _messageAggregator.PublishAsync(new CustomEntityDraftVersionDeletedMessage()
                {
                    CustomEntityId             = command.CustomEntityId,
                    CustomEntityDefinitionCode = definitionCode,
                    CustomEntityVersionId      = versionId
                });
            }
        }
Example #8
0
        public async Task ExecuteAsync(SetupCofoundryCommand command, IExecutionContext executionContext)
        {
            var settings = await _queryExecutor.ExecuteAsync(new GetSettingsQuery <InternalSettings>());

            if (settings.IsSetup)
            {
                throw new InvalidOperationException("Site is already set up.");
            }

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                var userId = await CreateAdminUser(command);

                var impersonatedUserContext = await GetImpersonatedUserContext(executionContext, userId);

                var settingsCommand = await _queryExecutor.ExecuteAsync(new GetUpdateCommandQuery <UpdateGeneralSiteSettingsCommand>());

                settingsCommand.ApplicationName = command.ApplicationName;
                await _commandExecutor.ExecuteAsync(settingsCommand, impersonatedUserContext);

                // Take the opportunity to break the cache in case any additional install scripts have been run since initialization
                _objectCacheFactory.Clear();

                // Setup Complete
                await _commandExecutor.ExecuteAsync(new MarkAsSetUpCommand(), impersonatedUserContext);

                scope.Complete();
            }
        }
Example #9
0
        public async Task ExecuteAsync(AddDocumentAssetCommand command, IExecutionContext executionContext)
        {
            var documentAsset = new DocumentAsset();

            documentAsset.Title       = command.Title;
            documentAsset.Description = command.Description ?? string.Empty;
            documentAsset.FileName    = SlugFormatter.ToSlug(command.Title);
            _entityTagHelper.UpdateTags(documentAsset.DocumentAssetTags, command.Tags, executionContext);
            _entityAuditHelper.SetCreated(documentAsset, executionContext);

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                _dbContext.DocumentAssets.Add(documentAsset);

                await _documentAssetCommandHelper.SaveFile(command.File, documentAsset);

                command.OutputDocumentAssetId = documentAsset.DocumentAssetId;
                scope.Complete();
            }

            await _messageAggregator.PublishAsync(new DocumentAssetAddedMessage()
            {
                DocumentAssetId = documentAsset.DocumentAssetId
            });
        }
        public async Task ExecuteAsync(DeleteCustomEntityCommand command, IExecutionContext executionContext)
        {
            var customEntity = await _dbContext
                               .CustomEntities
                               .SingleOrDefaultAsync(p => p.CustomEntityId == command.CustomEntityId);

            if (customEntity != null)
            {
                _permissionValidationService.EnforceCustomEntityPermission <CustomEntityDeletePermission>(customEntity.CustomEntityDefinitionCode);

                using (var scope = _transactionScopeFactory.Create())
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(customEntity.CustomEntityDefinitionCode, customEntity.CustomEntityId));

                    _dbContext.CustomEntities.Remove(customEntity);
                    await _dbContext.SaveChangesAsync();

                    scope.Complete();
                }
                _customEntityCache.Clear(customEntity.CustomEntityDefinitionCode, command.CustomEntityId);

                await _messageAggregator.PublishAsync(new CustomEntityDeletedMessage()
                {
                    CustomEntityId             = command.CustomEntityId,
                    CustomEntityDefinitionCode = customEntity.CustomEntityDefinitionCode
                });
            }
        }
        public async Task ExecuteAsync(DeleteDocumentAssetCommand command, IExecutionContext executionContext)
        {
            var documentAsset = await _dbContext
                                .DocumentAssets
                                .FilterById(command.DocumentAssetId)
                                .SingleOrDefaultAsync();

            if (documentAsset != null)
            {
                documentAsset.IsDeleted = true;
                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(DocumentAssetEntityDefinition.DefinitionCode, documentAsset.DocumentAssetId));

                    await _dbContext.SaveChangesAsync();

                    scope.Complete();
                }

                await _messageAggregator.PublishAsync(new DocumentAssetAddedMessage()
                {
                    DocumentAssetId = command.DocumentAssetId
                });
            }
        }
Example #12
0
        public async Task ExecuteAsync(PublishPageCommand command, IExecutionContext executionContext)
        {
            var pageVersions = await QueryVersions(command).ToListAsync();

            using (var scope = _transactionScopeFactory.Create())
            {
                // Find the published one and make it appPageroved
                var publishedVersion = pageVersions.SingleOrDefault(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Published);
                if (publishedVersion != null)
                {
                    publishedVersion.WorkFlowStatusId = (int)WorkFlowStatus.Approved;
                    await _dbContext.SaveChangesAsync();
                }

                // Find the draft page and make it published
                SetDraftVersionPublished(command, pageVersions);
                await _dbContext.SaveChangesAsync();

                scope.Complete();
            }

            _pageCache.Clear();

            await _messageAggregator.PublishAsync(new PagePublishedMessage()
            {
                PageId = command.PageId
            });
        }
Example #13
0
        public async Task SaveFile(IUploadedFile uploadedFile, DocumentAsset documentAsset)
        {
            using (var inputSteam = await uploadedFile.OpenReadStreamAsync())
            {
                bool isNew = documentAsset.DocumentAssetId < 1;

                documentAsset.FileExtension   = Path.GetExtension(uploadedFile.FileName).TrimStart('.');
                documentAsset.FileSizeInBytes = Convert.ToInt32(inputSteam.Length);
                documentAsset.ContentType     = uploadedFile.MimeType;

                // Save at this point if it's a new image
                if (isNew)
                {
                    await _dbContext.SaveChangesAsync();
                }

                var fileName = Path.ChangeExtension(documentAsset.DocumentAssetId.ToString(), documentAsset.FileExtension);

                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    // Save the raw file directly
                    await CreateFileAsync(isNew, fileName, inputSteam);

                    if (!isNew)
                    {
                        await _dbContext.SaveChangesAsync();
                    }
                    scope.Complete();
                }
            }
        }
Example #14
0
        public async Task ExecuteAsync(DeletePageCommand command, IExecutionContext executionContext)
        {
            var page = await _dbContext
                       .Pages
                       .SingleOrDefaultAsync(p => p.PageId == command.PageId);

            if (page != null)
            {
                page.IsDeleted = true;
                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(PageEntityDefinition.DefinitionCode, command.PageId), executionContext);

                    await _dbContext.SaveChangesAsync();

                    await _pageStoredProcedures.UpdatePublishStatusQueryLookupAsync(command.PageId);

                    scope.Complete();
                }
                _pageCache.Clear(command.PageId);

                await _messageAggregator.PublishAsync(new PageDeletedMessage()
                {
                    PageId = command.PageId
                });
            }
        }
        public async Task ExecuteAsync(UpdatePageDraftVersionCommand command, IExecutionContext executionContext)
        {
            var draft = await GetDraftVersion(command.PageId).SingleOrDefaultAsync();

            using (var scope = _transactionScopeFactory.Create())
            {
                draft = await CreateDraftIfRequiredAsync(command.PageId, draft);

                UpdateDraft(command, draft);

                await _dbContext.SaveChangesAsync();

                scope.Complete();
            }
            _pageCache.Clear(command.PageId);

            await _messageAggregator.PublishAsync(new PageDraftVersionUpdatedMessage()
            {
                PageId        = command.PageId,
                PageVersionId = draft.PageVersionId
            });

            if (command.Publish)
            {
                await _commandExecutor.ExecuteAsync(new PublishPageCommand(draft.PageId));
            }
        }
Example #16
0
        public async Task <Pet> CreatePet(Pet pet, User user)
        {
            using (var trans = TransactionScopeFactory.Create())
            {
                var color   = (await CfgRepo.RetrieveColorsByIds(pet.ColorId)).FirstOrDefault();
                var species = (await CfgRepo.RetrieveSpeciesByIds(pet.SpeciesId)).FirstOrDefault();

                await validatePet(pet, color, species, user);

                pet.Level            = 0;
                pet.OwnerUserId      = user.Id;
                pet.BaseHealthPoints = species.BaseHealthPoints;
                pet.HealthPoints     = species.BaseHealthPoints; //todo pet stats STR DEX WIS CHAR INT CON luck????
                pet.FoodBasis        = species.FoodBasis;
                pet.FoodLevel        = species.FoodBasis;
                pet.LastFoodUpdate   = DateTime.UtcNow;
                try
                {
                    pet.Id = await PetRepo.CreatePet(pet, pet.OwnerUserId);
                }
                catch (Exception ex)
                {
                    throw new CritterException("Could not create pet, please try again!", "Something went wrong unexpectedly at the DB level", System.Net.HttpStatusCode.InternalServerError, ex, LogLevel.Critical);
                }
                //todo verify configs
                trans.Complete();
            }
            pet = (await RetrievePets(pet.Id)).FirstOrDefault();
            return(pet);
        }
        public async Task ExecuteAsync(DeleteWebDirectoryCommand command, IExecutionContext executionContext)
        {
            var webDirectory = await _dbContext
                               .WebDirectories
                               .Include(w => w.ChildWebDirectories)
                               .SingleOrDefaultAsync(w => w.WebDirectoryId == command.WebDirectoryId);

            if (webDirectory != null)
            {
                if (!webDirectory.ParentWebDirectoryId.HasValue)
                {
                    throw new ValidationException("Cannot delete the root web directory.");
                }

                webDirectory.IsActive = false;

                using (var scope = _transactionScopeFactory.Create())
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(WebDirectoryEntityDefinition.DefinitionCode, webDirectory.WebDirectoryId));

                    await _dbContext.SaveChangesAsync();

                    scope.Complete();
                }
                _cache.Clear();
            }
        }
Example #18
0
        public async Task ExecuteAsync(AddPageCommand command, IExecutionContext executionContext)
        {
            // Custom Validation
            await ValidateIsPageUniqueAsync(command, executionContext);

            var page = await MapPage(command, executionContext);

            _dbContext.Pages.Add(page);

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                await _dbContext.SaveChangesAsync();

                await _pageStoredProcedures.UpdatePublishStatusQueryLookupAsync(page.PageId);

                scope.Complete();
            }

            _pageCache.ClearRoutes();

            // Set Ouput
            command.OutputPageId = page.PageId;

            await _messageAggregator.PublishAsync(new PageAddedMessage()
            {
                PageId = page.PageId,
                HasPublishedVersionChanged = command.Publish
            });
        }
Example #19
0
        public async Task ExecuteAsync(DeletePageDraftVersionCommand command, IExecutionContext executionContext)
        {
            var draft = await _dbContext
                        .PageVersions
                        .SingleOrDefaultAsync(v => v.PageId == command.PageId &&
                                              v.WorkFlowStatusId == (int)WorkFlowStatus.Draft &&
                                              !v.IsDeleted);

            if (draft != null)
            {
                var versionId = draft.PageVersionId;
                draft.IsDeleted = true;
                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    await _commandExecutor.ExecuteAsync(new DeleteUnstructuredDataDependenciesCommand(PageVersionEntityDefinition.DefinitionCode, draft.PageVersionId), executionContext);

                    await _dbContext.SaveChangesAsync();

                    await _pageStoredProcedures.UpdatePublishStatusQueryLookupAsync(command.PageId);

                    scope.Complete();
                }
                _pageCache.Clear(command.PageId);

                await _messageAggregator.PublishAsync(new PageDraftVersionDeletedMessage()
                {
                    PageId        = command.PageId,
                    PageVersionId = versionId
                });
            }
        }
Example #20
0
        public async Task ExecuteAsync(UpdateDocumentAssetCommand command, IExecutionContext executionContext)
        {
            bool hasNewFile = command.File != null;

            var documentAsset = await _dbContext
                                .DocumentAssets
                                .Include(a => a.DocumentAssetTags)
                                .Include(a => a.DocumentAssetTags.Select(pt => pt.Tag))
                                .FilterById(command.DocumentAssetId)
                                .SingleOrDefaultAsync();

            documentAsset.Title       = command.Title;
            documentAsset.Description = command.Description ?? string.Empty;
            documentAsset.FileName    = SlugFormatter.ToSlug(command.Title);
            _entityTagHelper.UpdateTags(documentAsset.DocumentAssetTags, command.Tags, executionContext);
            _entityAuditHelper.SetUpdated(documentAsset, executionContext);

            using (var scope = _transactionScopeFactory.Create())
            {
                if (hasNewFile)
                {
                    await _documentAssetCommandHelper.SaveFile(command.File, documentAsset);
                }

                await _dbContext.SaveChangesAsync();

                scope.Complete();
            }
        }
Example #21
0
 private Func <System.Transactions.TransactionScope> CreateScopeFactory(
     System.Transactions.TransactionScopeOption transactionScopeOption = System.Transactions.TransactionScopeOption.Required,
     System.Transactions.IsolationLevel isolationLevel = System.Transactions.IsolationLevel.ReadCommitted
     )
 {
     return(() => _transactionScopeFactory.Create(
                transactionScopeOption,
                isolationLevel
                ));
 }
        public async Task ExecuteAsync(UpdateCustomEntityDraftVersionCommand command, IExecutionContext executionContext)
        {
            var definition = _customEntityDefinitionRepository.GetByCode(command.CustomEntityDefinitionCode);
            var draft      = await GetDraftVersionAsync(command);


            using (var scope = _transactionScopeFactory.Create())
            {
                draft = await CreateDraftIfRequiredAsync(command, draft);
                await ValidateTitle(command, draft, definition);

                UpdateDraft(command, draft);

                await _dbContext.SaveChangesAsync();

                var dependencyCommand = new UpdateUnstructuredDataDependenciesCommand(
                    CustomEntityVersionEntityDefinition.DefinitionCode,
                    draft.CustomEntityVersionId,
                    command.Model);

                await _commandExecutor.ExecuteAsync(dependencyCommand);

                scope.Complete();
            }

            _customEntityCache.Clear(command.CustomEntityDefinitionCode, command.CustomEntityId);
            await _messageAggregator.PublishAsync(new CustomEntityDraftVersionUpdatedMessage()
            {
                CustomEntityId             = command.CustomEntityId,
                CustomEntityDefinitionCode = command.CustomEntityDefinitionCode,
                CustomEntityVersionId      = draft.CustomEntityVersionId
            });

            if (command.Publish)
            {
                using (var scope = _transactionScopeFactory.Create())
                {
                    await _commandExecutor.ExecuteAsync(new PublishCustomEntityCommand(draft.CustomEntityId));

                    scope.Complete();
                }
            }
        }
Example #23
0
        public void ResetPassword(User user, IResetUserPasswordCommand command, IExecutionContext executionContext)
        {
            ValidateUserAccountExists(user);
            ValidateUserArea(user.UserAreaCode);

            var existingIncompleteRequests = QueryIncompleteRequests(user).ToList();

            SetExistingRequestsComplete(existingIncompleteRequests);
            var request = CreateRequest(executionContext, user);

            SetMailTemplate(command, user, request);

            using (var scope = _transactionScopeFactory.Create())
            {
                _dbContext.SaveChanges();
                _mailService.Send(user.Email, user.GetFullName(), command.MailTemplate);

                scope.Complete();
            }
        }
Example #24
0
        public async Task <string> CreateAccount(User user)
        {
            bool conflictFound = await UserRepo.UserExistsByUsernameOrEmail(user.Username, user.EmailAddress);

            if (conflictFound)
            {
                throw new CritterException($"Sorry, someone already exists with that name or email!", $"Duplicate account creation attempt on {user.Username} or {user.EmailAddress}", System.Net.HttpStatusCode.Conflict);
            }

            using (var trans = TransactionScopeFactory.Create())
            {
                user.Cash     = 500; //TODO economics
                user.IsActive = true;
                user.Salt     = BCrypt.Net.BCrypt.GenerateSalt();
                user.Password = BCrypt.Net.BCrypt.HashPassword(user.Password, user.Salt);

                user.Id = await UserRepo.CreateUser(user) ?? throw new CritterException("Could not create account, try again!", null, System.Net.HttpStatusCode.Conflict);

                List <int> metaphones = new List <int>();
                var        doubles    = new List <ShortDoubleMetaphone>();
                doubles.Add(new ShortDoubleMetaphone(user.Username));
                doubles.Add(new ShortDoubleMetaphone(user.FirstName));
                doubles.Add(new ShortDoubleMetaphone(user.LastName));
                doubles.ForEach(d => { metaphones.Add(d.PrimaryShortKey); metaphones.Add(d.AlternateShortKey); });
                metaphones = metaphones.Distinct().AsList();
                if (!await UserRepo.InsertMetaphone(user.Id, metaphones.ToArray()))
                {
                    Log.Logger.Error($"Failed to create metaphone for {user.Id}");
                }

                if (!await UserRepo.CreateUserMeta(user.Id, ""))
                {
                    throw new CritterException("Could not create account, try again!", $"Failed to create a user meta for user ID {user.Id}", System.Net.HttpStatusCode.InternalServerError);
                }

                trans.Complete();
            }
            user = await RetrieveUser(user.Id);

            return(JWTProvider.GenerateToken(user));
        }
Example #25
0
        public async Task ExecuteAsync(PublishCustomEntityCommand command, IExecutionContext executionContext)
        {
            // Prefer draft, but update published entity if no draft (only one draft permitted)
            var version = await _dbContext
                          .CustomEntityVersions
                          .Include(v => v.CustomEntity)
                          .Where(v => v.CustomEntityId == command.CustomEntityId && (v.WorkFlowStatusId == (int)WorkFlowStatus.Draft || v.WorkFlowStatusId == (int)WorkFlowStatus.Published))
                          .OrderByDescending(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Draft)
                          .ThenByDescending(v => v.CreateDate)
                          .FirstOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(version, command.CustomEntityId);

            var definition = _customEntityDefinitionRepository.GetByCode(version.CustomEntity.CustomEntityDefinitionCode);

            EntityNotFoundException.ThrowIfNull(definition, version.CustomEntity.CustomEntityDefinitionCode);

            await _permissionValidationService.EnforceCustomEntityPermissionAsync <CustomEntityPublishPermission>(definition.CustomEntityDefinitionCode);

            UpdatePublishDate(command, executionContext, version);

            if (version.WorkFlowStatusId == (int)WorkFlowStatus.Published)
            {
                // only thing we can do with a published version is update the date
                await _dbContext.SaveChangesAsync();
            }
            else
            {
                await ValidateTitle(version, definition);

                using (var scope = _transactionScopeFactory.Create(_dbContext))
                {
                    await UpdateUrlSlugIfRequired(version, definition);

                    version.WorkFlowStatusId = (int)WorkFlowStatus.Published;
                    version.CustomEntity.PublishStatusCode = PublishStatusCode.Published;

                    await _dbContext.SaveChangesAsync();

                    await _customEntityStoredProcedures.UpdatePublishStatusQueryLookupAsync(command.CustomEntityId);

                    scope.Complete();
                }
            }

            _customEntityCache.Clear(version.CustomEntity.CustomEntityDefinitionCode, command.CustomEntityId);

            await _messageAggregator.PublishAsync(new CustomEntityPublishedMessage()
            {
                CustomEntityId             = command.CustomEntityId,
                CustomEntityDefinitionCode = version.CustomEntity.CustomEntityDefinitionCode
            });
        }
Example #26
0
        public void Execute(CompleteUserPasswordResetCommand command, IExecutionContext executionContext)
        {
            var validationResult = _queryExecutor.Execute(CreateValidationQuery(command));

            ValidatePasswordRequest(validationResult);

            var request = QueryPasswordRequestIfToken(command).SingleOrDefault();

            EntityNotFoundException.ThrowIfNull(request, command.UserPasswordResetRequestId);

            UpdatePasswordAndSetComplete(request, command, executionContext);
            SetMailTemplate(command, request.User);

            using (var scope = _transactionScopeFactory.Create())
            {
                _dbContext.SaveChanges();
                _mailService.Send(request.User.Email, request.User.GetFullName(), command.MailTemplate);

                scope.Complete();
            }
        }
Example #27
0
        public IActionResult Post([FromForm] RegisterDocumentModel model)
        {
            Guard.AgainstNull(model, nameof(model));

            try
            {
                model.ApplyInvariants();
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            var id = Guid.NewGuid();
            var effectiveFromDate = DateTime.Now;

            using (var scope = _transactionScopeFactory.Create())
                using (_databaseContextFactory.Create())
                    using (var stream = new MemoryStream())
                    {
                        var result = _documentQuery.Search(new DataAccess.Query.Document.Specification().AddId(model.Id).GetActiveOnly()).ToList();

                        if (result.Any())
                        {
                            var document = result.First();

                            if (model.EffectiveFromDate <= document.EffectiveFromDate)
                            {
                                return(BadRequest(
                                           $"Existing active document (id = '{document.Id}' / reference id = '{document.ReferenceId}') is effective from date '{document.EffectiveFromDate:O}' and the document being registered for the same reference id is effective from date '{model.EffectiveFromDate:O}' which on or after the new one.  The new document should be effective from a date after the existing document."));
                            }
                        }

                        model.Document.CopyTo(stream);

                        _documentRepository.Save(new Document(id, model.Id, model.Document.FileName, model.ContentType,
                                                              stream.ToArray(), model.SystemName, model.Username, effectiveFromDate));

                        _serviceBus.Send(new RegisterDocumentCommand
                        {
                            Id = id
                        });

                        scope.Complete();
                    }

            return(Ok(new
            {
                DocumentId = id,
                EffectiveFromDate = $"{effectiveFromDate:O}"
            }));
        }
        public async Task ExecuteAsync(UnPublishPageCommand command, IExecutionContext executionContext)
        {
            var page = await _dbContext
                       .Pages
                       .FilterActive()
                       .FilterByPageId(command.PageId)
                       .SingleOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(page, command.PageId);

            if (page.PublishStatusCode == PublishStatusCode.Unpublished)
            {
                // No action
                return;
            }

            var version = await _dbContext
                          .PageVersions
                          .Include(p => p.Page)
                          .Where(v => v.PageId == command.PageId &&
                                 !v.IsDeleted &&
                                 !v.Page.IsDeleted &&
                                 (v.WorkFlowStatusId == (int)WorkFlowStatus.Draft || v.WorkFlowStatusId == (int)WorkFlowStatus.Published))
                          .OrderByDescending(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Draft)
                          .ThenByDescending(v => v.CreateDate)
                          .FirstOrDefaultAsync();

            EntityNotFoundException.ThrowIfNull(version, command.PageId);

            page.PublishStatusCode   = PublishStatusCode.Unpublished;
            version.WorkFlowStatusId = (int)WorkFlowStatus.Draft;

            using (var scope = _transactionScopeFactory.Create(_dbContext))
            {
                await _dbContext.SaveChangesAsync();

                await _pageStoredProcedures.UpdatePublishStatusQueryLookupAsync(command.PageId);

                scope.Complete();
            }

            _pageCache.Clear();

            await _messageAggregator.PublishAsync(new PageUnPublishedMessage()
            {
                PageId = command.PageId
            });
        }
        public void Execute(OnStartTransactionScope pipelineEvent)
        {
            var state = pipelineEvent.Pipeline.State;
            var scope = state.GetTransactionScope();

            if (scope != null)
            {
                throw new InvalidOperationException(
                          string.Format(Resources.TransactionAlreadyStartedException, GetType().FullName,
                                        MethodBase.GetCurrentMethod().Name));
            }

            scope = _transactionScopeFactory.Create();

            state.SetTransactionScope(scope);
        }
        public async Task ExecuteAsync(PublishCustomEntityCommand command, IExecutionContext executionContext)
        {
            var versions = await _dbContext
                           .CustomEntityVersions
                           .Include(v => v.CustomEntity)
                           .Where(p => p.CustomEntityId == command.CustomEntityId &&
                                  (p.WorkFlowStatusId == (int)WorkFlowStatus.Draft || p.WorkFlowStatusId == (int)WorkFlowStatus.Published))
                           .ToListAsync();

            var publishedVersion = versions.SingleOrDefault(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Published);
            var draftVersion     = versions.SingleOrDefault(v => v.WorkFlowStatusId == (int)WorkFlowStatus.Draft);

            EntityNotFoundException.ThrowIfNull(draftVersion, "Draft:" + command.CustomEntityId);

            var definition = _customEntityDefinitionRepository.GetByCode(draftVersion.CustomEntity.CustomEntityDefinitionCode);

            EntityNotFoundException.ThrowIfNull(definition, draftVersion.CustomEntity.CustomEntityDefinitionCode);

            _permissionValidationService.EnforceCustomEntityPermission <CustomEntityPublishPermission>(definition.CustomEntityDefinitionCode);
            await ValidateTitle(draftVersion, definition);

            using (var scope = _transactionScopeFactory.Create())
            {
                // Find the published one and make it approved
                if (publishedVersion != null)
                {
                    publishedVersion.WorkFlowStatusId = (int)WorkFlowStatus.Approved;
                    await _dbContext.SaveChangesAsync();
                }

                await UpdateUrlSlugIfRequired(draftVersion, definition);

                // Find the draft page and make it published
                draftVersion.WorkFlowStatusId = (int)WorkFlowStatus.Published;
                await _dbContext.SaveChangesAsync();

                scope.Complete();
            }

            _customEntityCache.Clear(draftVersion.CustomEntity.CustomEntityDefinitionCode, command.CustomEntityId);

            await _messageAggregator.PublishAsync(new CustomEntityPublishedMessage()
            {
                CustomEntityId             = command.CustomEntityId,
                CustomEntityDefinitionCode = draftVersion.CustomEntity.CustomEntityDefinitionCode
            });
        }