示例#1
0
        public async Task <PublisherResponse> UpdateAsync(int id, Publisher publisher)
        {
            try
            {
                var _publisher = await _publisherRepository.FindByIdAsync(id);

                if (publisher == null)
                {
                    return(new PublisherResponse($"this publisher doesn't exist by id {id}"));
                }

                _publisher.PublicName      = publisher.PublicName;
                _publisher.CorporativeName = publisher.CorporativeName;
                _publisher.Cnpj            = publisher.Cnpj;
                _publisher.Products        = publisher.Products;

                _publisherRepository.Update(_publisher);
                await _unityOfWork.CompleteAsync();

                return(new PublisherResponse(_publisher));
            }
            catch (Exception e)
            {
                return(new PublisherResponse($"An error ocurred {e.Message}"));
            }
        }
示例#2
0
        public async Task <DatasetResponse> CreateGitLabProject(Task <Dataset> createDatasetTask, Dataset exsistingDataset)
        {
            // NOTE: Her venter jeg på at datasettet skal opprettes uten feil,
            // før det opprettes i gitlab, for å hindre at det eksisterer løse prosjekter
            // i gitlab.
            // Dette kan kanskje gjøres smoothere.
            var gitlabProjectResponse = await await createDatasetTask.ContinueWith(async(antecedent) => {
                var dataset = antecedent.Result;

                var publisher = await _publisherRepository.FindByIdAsync(dataset.PublisherId);

                // NOTE: Enn så lenge så må vi verifisere at det eksisterer en gitlab-gruppe for publisher
                // før vi kan lage et prosjekt i riktig gruppe. I produksjon vil ikke dette være nødvendig,
                // og det bør heller ikke kjøre, fordi hvis det ikke eksisterer betyr det at noe har gått
                // galt ved opprettelse av publisher. (TODO: ordne dette en gang)
                if (publisher.GitlabGroupNamespaceId == null)
                {
                    var gitlabGroupResponse = await _gitlabService.CreateGitlabGroupForPublisher(publisher);
                    if (gitlabGroupResponse.Success)
                    {
                        publisher.GitlabGroupPath        = gitlabGroupResponse.Resource.full_path;
                        publisher.GitlabGroupNamespaceId = gitlabGroupResponse.Resource.id;
                        _publisherRepository.Update(publisher);
                        await _unitOfWork.CompleteAsync();
                    }
                    else
                    {
                        // hvis vi havner her så har ting gått veldig galt. (Dette er midlertidige saker uansett.)
                        // typisk skjer dette hvis det allerede eksisterer en gruppe i gitlab for publisher,
                        // men dette er ikke reflektert i databasen.
                        return(new GitlabResponse <GitlabProject>(gitlabGroupResponse.Message + " ======> Noe har gått veldig galt med sære ting: Nei, vil ikke (Erna Solberg, 2018)"));
                    }
                }

                return(await _gitlabService.CreateDatasetProject(dataset));
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            if (gitlabProjectResponse.Success)
            {
                exsistingDataset.GitlabProjectId         = gitlabProjectResponse.Resource.id;
                exsistingDataset.GitlabProjectPath       = gitlabProjectResponse.Resource.path_with_namespace;
                exsistingDataset.GitlabDiscussionBoardId = gitlabProjectResponse.Resource.defaultGitlabIssueBoardId;
                _datasetRepository.Update(exsistingDataset);
                await _unitOfWork.CompleteAsync();

                return(new DatasetResponse(exsistingDataset));
            }
            else
            {
                // Hvis opprettelse av prosjekt i gitlab feiler bør datasettet fjernes fra databasen
                // Denne kan nå også potensielt fjerne eksisterende datasett som ikke enda har fått en gitlab tilknytting om det oppstår en feil
                _datasetRepository.Remove(exsistingDataset);
                await _unitOfWork.CompleteAsync();

                return(new DatasetResponse("GitLab project response failed:" + gitlabProjectResponse.Message));
            }
        }
示例#3
0
        public async Task Consume(ConsumeContext <GetBookInfo> context)
        {
            _logger.LogInformation("GetBookInfoConsumer: Started Consuming Message {MessageId} : {@Message}", context.MessageId, context.Message);
            var book = (await _bookRepository.GetAllByIds(new List <int>()
            {
                context.Message.BookId
            })).FirstOrDefault();

            if (book is null)
            {
                await context.RespondAsync <BookInfoResult>(new
                {
                    Result = (BookInfoDto)null
                });
            }
            var result = _mapper.Map <BookInfoDto>(book);
            var pub    = await _publisherRepository.FindByIdAsync(book.PublisherId ?? 0);

            var img = book.Images?.FirstOrDefault(i => i.IsMain);

            result.Publisher = pub is not null?_mapper.Map <PublisherBusResponseDto>(pub) : null;

            result.Image = img is not null?_mapper.Map <ImageBusResponseDto>(img) : null;

            _logger.LogInformation("GetBookInfoConsumer: Message: {MessageId} Ended with value : {@Value}", context.MessageId, result);
            await context.RespondAsync <BookInfoResult>(new
            {
                Result = result
            });
        }
示例#4
0
        public async Task Consume(ConsumeContext <GetBooksInfo> context)
        {
            _logger.LogInformation("GetBooksInfoConsumer: Started Consuming Message {MessageId} : {@Message}", context.MessageId, context.Message);

            var books = await _bookRepository.GetAllByIds(context.Message.BooksIds);

            var results = _mapper.Map <IEnumerable <BookInfoDto> >(books).ToList();



            foreach (var book in books)
            {
                foreach (var res in results)
                {
                    var pub = await _publisherRepository.FindByIdAsync(book.PublisherId ?? 0);

                    var img = book.Images?.FirstOrDefault(i => i.IsMain);
                    res.Publisher = pub is not null?_mapper.Map <PublisherBusResponseDto>(pub) : null;

                    res.Image = img is not null?_mapper.Map <ImageBusResponseDto>(img) : null;
                }
            }

            _logger.LogInformation("GetBooksInfoConsumer: Message: {MessageId} Ended with value : {@Value}", context.MessageId, results);

            await context.RespondAsync <BooksInfoResult>(new
            {
                Results = results
            });
        }
        public async Task <CreateBookCommandResult> Handle(CreateBookManualCommand request, CancellationToken cancellationToken)
        {
            var categories = await _categoryRepository.GetAllByIdAsync(request.CategoriesIds);

            if (!categories.Any())
            {
                return(new CreateBookCommandResult(false, new[] { "Requested category/s not found" }));
            }

            var authors = await _authorRepository.GetAllByIdAsync(request.AuthorsIds);

            if (!authors.Any())
            {
                return(new CreateBookCommandResult(false, new[] { "Requested category/s not found" }));
            }

            var book = new Domain.Book(request.Title,
                                       request.Description, request.Isbn10,
                                       request.Isbn13, request.LanguageId,
                                       request.PublisherId, request.PageCount,
                                       request.Visibility, request.PublishedDate);

            foreach (var category in categories)
            {
                book.AddCategory(category);
            }

            foreach (var author in authors)
            {
                book.AddAuthor(author);
            }

            var result = _bookRepository.Add(book);

            if (await _bookRepository.UnitOfWork.SaveChangesAsync(cancellationToken) < 1)
            {
                return(new CreateBookCommandResult(false, new[] { "Error occured during saving Book" }));
            }


            var bookResult = _mapper.Map <CommandBookDto>(result);

            var bookResultEvent = _mapper.Map <CreateBook>(result);

            bookResultEvent.Language = result.LanguageId > 0
                ? _mapper.Map <LanguageDto>(await _languageRepository.FindByIdAsync(result.LanguageId ?? 0))
                : null;
            bookResultEvent.Publisher = result.LanguageId > 0
                ? _mapper.Map <PublisherDto>(await _publisherRepository.FindByIdAsync(result.PublisherId ?? 0))
                : null;


            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri($"queue:{EventBusConstants.CreateBookQueue}"));

            await endpoint.Send(bookResultEvent, cancellationToken);

            return(new CreateBookCommandResult(true, bookResult));
        }
示例#6
0
        public CreateBookManualCommandValidator(IAuthorRepository authorRepository,
                                                ICategoryRepository categoryRepository,
                                                ILanguageRepository languageRepository,
                                                IPublisherRepository publisherRepository)
        {
            _authorRepository    = authorRepository;
            _categoryRepository  = categoryRepository;
            _languageRepository  = languageRepository;
            _publisherRepository = publisherRepository;

            RuleFor(b => b.Title)
            .MinimumLength(3)
            .MaximumLength(100);

            RuleFor(b => b.Description)
            .MinimumLength(3)
            .MaximumLength(5000);

            RuleFor(b => b.Isbn10)
            .Length(10)
            .Matches("^[0-9]+$").WithMessage("ISBN10 Field must contain only digits");
            RuleFor(b => b.Isbn13)
            .Length(13)
            .Matches("^[0-9]+$").WithMessage("ISBN13 Field must contain only digits");

            RuleFor(b => b.PageCount)
            .GreaterThanOrEqualTo((ushort)1);

            const int authorIdMinValue = 1;

            RuleFor(b => b.AuthorsIds)
            .NotEmpty()
            .ForEach(a =>
                     a.GreaterThanOrEqualTo(authorIdMinValue)
                     .WithMessage($"Author id must be greater then {authorIdMinValue - 1}"))
            .AllValuesMustExistsInDb(nameof(Author.Id), _authorRepository.GetAllAsync());

            RuleFor(b => b.LanguageId)
            .GreaterThanOrEqualTo(1)
            .ValueMustExistsInDb(id => _languageRepository.FindByIdAsync(id ?? 0));


            RuleFor(b => b.PublisherId)
            .GreaterThanOrEqualTo(1)
            .ValueMustExistsInDb(id => _publisherRepository.FindByIdAsync(id ?? 0));

            const int categoryIdMinValue = 1;

            RuleFor(b => b.CategoriesIds)
            .ForEach(c =>
                     c.GreaterThanOrEqualTo(categoryIdMinValue)
                     .WithMessage($"Category id must be greater than {categoryIdMinValue - 1}"))
            .AllValuesMustExistsInDb(nameof(Category.Id), _categoryRepository.GetAllAsync());
        }
示例#7
0
        public async Task <PublisherResponse> UpdateAsync(int id, Publisher publisher)
        {
            var existingPublisher = await _publisherRepository.FindByIdAsync(id);

            if (existingPublisher == null)
            {
                return(new PublisherResponse("Publisher not found."));
            }

            existingPublisher.Name = publisher.Name;

            try
            {
                await _unitOfWork.CompleteAsync();

                return(new PublisherResponse(existingPublisher));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new PublisherResponse($"An error occurred when updating the publisher: {ex.Message}"));
            }
        }
        public async Task <ApplicationResponse> SaveAsync(Application application)
        {
            try
            {
                var coordination = await _coordinationRepository.FindByIdAsync(application.CoordinationId);

                if (coordination == null)
                {
                    return(new ApplicationResponse("Coordination not found."));
                }

                if (application.DatasetId != null && application.DatasetId != 0)
                {
                    var dataset = await _datasetRepository.FindByIdAsync((int)application.DatasetId);

                    if (dataset == null)
                    {
                        return(new ApplicationResponse("Dataset not found."));
                    }
                    // Send notification
                    await _notificationService.AddPublisherNotificationsAsync(coordination, dataset, coordination.Title + " - " + coordination.Publisher.Name, "Datasettet '" + dataset.Title + "' har spurt om å være med i din samordning.");
                }
                else if (application.PublisherId != null && application.PublisherId != 0)
                {
                    var publisher = await _publisherRepository.FindByIdAsync((int)application.PublisherId);

                    if (publisher == null)
                    {
                        return(new ApplicationResponse("Publisher not found."));
                    }
                    // Send notification
                    await _notificationService.AddPublisherNotificationsAsync(publisher, coordination, coordination.Title + " - " + coordination.Publisher.Name, "En bruker ønsker at du publiserer et dataset i samordningen '" + coordination.Title + "'.");
                }
                else
                {
                    return(new ApplicationResponse("No dataset or publisher was found."));
                }

                await _applicationRepository.AddAsync(application);

                await _unitOfWork.CompleteAsync();


                return(new ApplicationResponse(application));
            }
            catch (Exception ex)
            {
                return(new ApplicationResponse($"An error occured when saving the tag: {ex.Message}"));
            }
        }
示例#9
0
        public async Task <PublisherResponse> DeleteAsync(int id)
        {
            var existingPublisher = await publisherRepository.FindByIdAsync(id);

            if (existingPublisher == null)
            {
                return(new PublisherResponse("Publisher not found"));
            }
            if (existingPublisher.Books.Count > 0)
            {
                return(new PublisherResponse("Publisher is used in books"));
            }
            try
            {
                publisherRepository.Remove(existingPublisher);
                await unitOfWork.CompleteAsync();

                return(new PublisherResponse(existingPublisher));
            }
            catch (Exception ex)
            {
                return(new PublisherResponse($"Error when deleting Publisher: {ex.Message}"));
            }
        }
示例#10
0
        public async Task <Publisher> FindByIdAsync(int id)
        {
            _logger.LogInfoMethodStarted <Publisher>(PublisherRepositoryType, nameof(FindByIdAsync), new object[] { id });

            var result = await _publisherRepository.FindByIdAsync(id);

            if (result is null)
            {
                _logger.LogWarningNotFound <Publisher>(PublisherRepositoryType, nameof(FindByIdAsync), new object[] { id });
            }


            _logger.LogInfoMethodEnded(PublisherRepositoryType, nameof(FindByIdAsync), result);
            return(result);
        }
        private async Task <(Boolean success, String error)> idChecks(Coordination coordination)
        {
            // Make sure the publisher exists
            var existingPublisher = await _publisherRepository.FindByIdAsync(coordination.PublisherId);

            if (existingPublisher == null)
            {
                return(false, "Invalid publisher id.");
            }

            // Make sure the category exists
            var existingCategory = await _categoryRepository.FindByIdAsync(coordination.CategoryId);

            if (existingCategory == null)
            {
                return(false, "Invalid category id.");
            }

            return(true, "Success.");
        }