public async Task <ActionResult <BookResource> > GetBooks(int id) { var bookFromRepo = await _bookRepository.Get(id); if (bookFromRepo == null) { return(NotFound()); } var listOfAuthorResource = new List <AuthorCreateResource>(); foreach (var author in bookFromRepo.Authors) { var authorResource = new AuthorCreateResource { Id = author.Id, FullName = author.FullName }; listOfAuthorResource.Add(authorResource); } var bookResource = new BookResource { Id = bookFromRepo.Id, Title = bookFromRepo.Title, Description = bookFromRepo.Description, IsAvailable = bookFromRepo.IsAvailable, Publisher = bookFromRepo.Publisher.Name, PublishedDate = bookFromRepo.PublishedDate, AuthorNames = listOfAuthorResource //AuthorNames = bookFromRepo.Authors.Select(e => e.FullName).ToList() }; return(Ok(bookResource)); }
public static List <BookResource> BookAuthorResource(this IEnumerable <Book> entity) { var lsitOfBookResource = new List <BookResource>(); foreach (var book in entity) { var bookResource = new BookResource { Id = book.Id, Title = book.Title, Description = book.Description, IsAvailable = book.IsAvailable, Publisher = book.Publisher.Name, PublishedDate = book.PublishedDate, AuthorNames = new List <AuthorCreateResource>(), }; foreach (var author in book.Authors) { bookResource.AuthorNames.Add(new AuthorCreateResource { Id = author.Id, FullName = author.FullName }); } lsitOfBookResource.Add(bookResource); } return(lsitOfBookResource); }
public IActionResult Put([FromBody] BookResource book) { if (book == null) { return(BadRequest()); } return(Ok(_bookService.Update(book))); }
public async Task <ActionResult <BookResource> > PostBook([FromBody] BookModel bookModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Here map (model) -> entity var authors = _authorRepository.Get().Result.ToList().Where(e => bookModel.AuthorIds.Contains(e.Id)).ToList(); if (authors.Count < bookModel.AuthorIds.Count) { throw new Exception("Id is not correct"); } var bookEntity = new Book { Title = bookModel.Title, Description = bookModel.Description, IsAvailable = bookModel.IsAvailable, PublisherId = bookModel.PublisherId, PublishedDate = bookModel.PublishedDate, Authors = authors }; // insert this record to database by repo var newBook = await _bookRepository.Create(bookEntity); // map author list into book resource var listOfAuthorResource = new List <AuthorCreateResource>(); foreach (var author in authors) { var authorResource = new AuthorCreateResource { Id = author.Id, FullName = author.FullName }; listOfAuthorResource.Add(authorResource); } // Here map (newBook which is Entity) -> Resource var bookResource = new BookResource { Id = newBook.Id, Title = newBook.Title, Description = newBook.Description, IsAvailable = newBook.IsAvailable, Publisher = newBook.Publisher.Name, PublishedDate = newBook.PublishedDate, AuthorNames = listOfAuthorResource }; return(CreatedAtAction(nameof(GetBooks), new { id = newBook.Id }, bookResource)); }
public IActionResult Get(long id) { BookResource book = _bookService.GetById(id); if (book == null) { return(NotFound()); } return(Ok(book)); }
public BookResource Query(int bookId) { BookResource resource = null; Book book = _bookRepository.Get(bookId); if (book != null) { resource = _bookResourceMapper.MapToResouce(book); } return(resource); }
public async Task <IActionResult> CreateBook([FromBody] BookResource bookResource) { var book = mapper.Map <BookResource, Book>(bookResource); repository.AddBook(book); await unitOfWork.CompleteAsync(); book = await repository.GetBookById(book.Id); var result = mapper.Map <Book, BookResource>(book); return(Ok(result)); }
public Ability(string _nameKey, bool _isActive, string _descriptionKey, List <GenreEnum> _availableGenres, GameTimeIntervalEnum _gameTimeInterval, BookResource _bookResource, bool _isUsable) { this._nameKey = (_nameKey == null) ? "INVALID_ABILITY" : _nameKey; this._isActive = _isActive; this._descriptionKey = (_descriptionKey == null) ? "INVALID_DESCRIPTION" : _descriptionKey; this._availableGenres = (_availableGenres == null || _availableGenres.Count == 0) ? this._availableGenres = new List <GenreEnum>(PAPIApplication.GetAllGenres()) : _availableGenres; this._gameTimeInterval = _gameTimeInterval; this._bookResource = _bookResource; this._isUsable = _isUsable; WfLogger.Log(this, LogLevel.DETAILED, "Ability '" + this._nameKey + "' was created"); }
public CriticalInjury(string _nameKey, uint _lowerBoundD100, uint _upperBoundD100, DifficultyEnum _severity, string _descriptionKey, bool _hasPermanentEffect, BookResource _bookResource, List <GenreEnum> _availableGenres) { this._nameKey = (_nameKey == null || _nameKey == "") ? "INVALID_CRITICAL_INJURY" : _nameKey; this._lowerBoundD100 = _lowerBoundD100; this._upperBoundD100 = (_upperBoundD100 < this._lowerBoundD100) ? this._lowerBoundD100 : _upperBoundD100; this._severity = _severity; this._descriptionKey = (_descriptionKey == null || _descriptionKey == "") ? "INVALID_DESCRIPTION" : _descriptionKey; this._hasPermanentEffect = _hasPermanentEffect; this._bookResource = (_bookResource == null) ? new BookResource(RuleBookEnum.NO_RULE_BOOK, 0) : _bookResource; this._availableGenres = (_availableGenres == null || _availableGenres.Count == 0) ? new List <GenreEnum>(PAPIApplication.GetAllGenres()) : _availableGenres; WfLogger.Log(this, LogLevel.DETAILED, "Created new Critical Injury " + this._nameKey); }
public async Task <ActionResult> Post([FromBody] BookResource bookResource) { if (!context.Books.Any(b => (b.Category.Id == bookResource.Category.Id) && (b.Author.Id == bookResource.Author.Id))) { return(BadRequest()); } var book = mapper.Map <BookResource, Book>(bookResource); await context.Books.AddAsync(book); await context.SaveChangesAsync(); return(Ok(book)); }
public Book Map(BookResource from) { if (from == null) { return(null); } return(new Book { Id = from.Id, Title = from.Title, Author = from.Author, Price = from.Price, LaunchDate = from.LaunchDate }); }
// -------------------------------------------------------------------------------------------------------------------------------- /// <summary> /// creates a copy of the given ability /// </summary> /// <param name="other">if null, an invalid ability is created</param> public Ability(Ability other) : this() { if (other == null) { return; } _nameKey = other._nameKey; _isActive = other._isActive; _descriptionKey = other._descriptionKey; _availableGenres = new List <GenreEnum>(other._availableGenres); _gameTimeInterval = other._gameTimeInterval; _bookResource = new BookResource(other._bookResource); _isUsable = other._isUsable; WfLogger.Log(this, LogLevel.DETAILED, "Created new Ability from another"); }
public async Task <IActionResult> UpdateBook(long id, [FromBody] BookResource bookResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var book = await context.Book.FindAsync(id); mapper.Map <BookResource, Book>(bookResource, book); await context.SaveChangesAsync(); var result = mapper.Map <Book, BookResource>(book); return(Ok(result)); }
public IActionResult Get() { try { logger.LogInformation("In BooksController Get"); //test data var bookResource = new BookResource() { UserFullName = GetUserInfo("name"), UserName = GetUserInfo("preferred_username"), Books = new List <Book>() { new Book() { BookId = 1, BookName = "City of Girls", AuthorName = "Elizabeth Gilbert", Category = "Novel" }, new Book() { BookId = 2, BookName = "The Silent Patient", AuthorName = "Alex Michaelides", Category = "Thriller" }, new Book() { BookId = 3, BookName = "Once More We Saw Stars", AuthorName = "Jayson Greene", Category = "Memoir" } } }; return(Ok(bookResource)); } catch (Exception ex) { logger.LogError($"Error in BooksController: {ex.Message}"); return(BadRequest($"{BadRequest().StatusCode} : {ex.Message}")); } }
// -------------------------------------------------------------------------------------------------------------------------------- /// <summary> /// Creates a copy of the given Critical Injurie /// </summary> /// <param name="other">if null, the a default one is created</param> public CriticalInjury(CriticalInjury other) : this() { if (other == null) { return; } _nameKey = other._nameKey; _lowerBoundD100 = other._lowerBoundD100; _upperBoundD100 = other._upperBoundD100; _severity = other._severity; _descriptionKey = other._descriptionKey; _hasPermanentEffect = other._hasPermanentEffect; _bookResource = new BookResource(other._bookResource); _availableGenres = new List <GenreEnum>(other._availableGenres); WfLogger.Log(this, LogLevel.DETAILED, "Created new Critical Injury from another"); }
public async Task <IActionResult> UpdateBook(int id, [FromBody] BookResource bookResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var book = await repository.GetBookById(id); if (book == null) { return(NotFound()); } mapper.Map(bookResource, book); await unitOfWork.CompleteAsync(); return(Ok(mapper.Map <Book, BookResource>(book))); }
static void Main(string[] args) { var artistResource = new ArtistResource(new Artist()); var bookResource = new BookResource(new Book()); //Two different view for artist resource var longFormViewForArtist = new LongFormView(artistResource); var shortFormViewForArtist = new ShortFormView(artistResource); //Two different view for book resource var longFormViewForBook = new LongFormView(bookResource); var shortFormViewForBook = new ShortFormView(bookResource); //We can completely change the behavior of sources via theirs objects Console.WriteLine(longFormViewForArtist.generateHTML()); Console.WriteLine(shortFormViewForArtist.generateHTML()); Console.WriteLine(longFormViewForBook.generateHTML()); Console.WriteLine(shortFormViewForBook.generateHTML()); }
static void Main(string[] args) { Book book = new Book("Feel Good", "C:/Books", "This is a Good Book", "Http://www.feelgood.com"); MusicArtist musicArtist = new MusicArtist("Dua Lipa", "C:/MusicArtist", "Great Singer", "Http://www.dualipa.com"); IResource bookResource = new BookResource(book); IResource musicArtistResource = new MusicArtistResource(musicArtist); View bookLongFormView = new LongFormView(bookResource); View musicArtistlongFormView = new LongFormView(musicArtistResource); View bookArtistShortFormView = new ShortFormView(bookResource); View musicArtistShortFormView = new ShortFormView(musicArtistResource); Console.WriteLine(bookLongFormView.Show()); Console.WriteLine(bookArtistShortFormView.Show()); Console.WriteLine(musicArtistlongFormView.Show()); Console.WriteLine(musicArtistShortFormView.Show()); Console.ReadKey(); }
private BookResource ToBookResource(Book book) { var ratings = this._dataBeastContext.Ratings.Where(e => e.BookId == book.Id); int numberOfRatings = ratings.Count(); decimal?averageRating = null; if (numberOfRatings != 0) { averageRating = ratings.Sum(e => e.RatingGiven) / numberOfRatings; } var bookResource = new BookResource(book) { PendingRequests = this._dataBeastContext.PendingRequests.Count(e => e.BookId == book.Id), AverageRating = averageRating }; return(bookResource); }
public async Task <IActionResult> CreateBook([FromBody] BookResource bookResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //var bookCheck = await context.Book.FindAsync(bookResource.BookId); //if (bookCheck == null) //{ // ModelState.AddModelError("BookId", "Invalid bookId."); // return BadRequest(ModelState); //} var book = mapper.Map <BookResource, Book>(bookResource); context.Book.Add(book); await context.SaveChangesAsync(); var result = mapper.Map <Book, BookResource>(book); return(Ok(result)); }
protected override void Execute(CodeActivityContext executionContext) { //Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); //Entity bookresource = (Entity)service.Retrieve("bookableresourcebooking", context.PrimaryEntityId, new ColumnSet(true)); //string campaignName = (string)regCampaign.Attributes["name"]; //EntityReference ownerid = (EntityReference)regCampaign.Attributes["ownerid"]; Entity emailEntity = new Entity("email"); Entity fromParty = new Entity("activityparty"); fromParty.Attributes["partyid"] = Systemuser.Get <EntityReference>(executionContext); EntityCollection from = new EntityCollection(); from.Entities.Add(fromParty); Entity toParty = new Entity("activityparty"); toParty.Attributes["partyid"] = ContactRef.Get <EntityReference>(executionContext); EntityCollection to = new EntityCollection(); to.Entities.Add(toParty); EntityReference regarding = new EntityReference("bookableresourcebooking", context.PrimaryEntityId); emailEntity["to"] = to; emailEntity["from"] = from; emailEntity["subject"] = "Technical Report from your WorkOrder"; emailEntity["regardingobjectid"] = regarding; Guid EmailID = service.Create(emailEntity); //EntityReference abc = SourceCompaign.Get<EntityReference>(executionContext); AddAttachmentToEmailRecord(service, EmailID, BookResource.Get <EntityReference>(executionContext), PortalComment.Get <EntityReference>(executionContext)); }
public BookResource MapToResouce(Book book) { BookResource resource = new BookResource(); resource.Id = book.Id; resource.Title = book.Title; resource.Author = book.Author; resource.Description = book.Description; resource.Self = _resourceLinker.GetResourceLink <BooksController>(request => request.Get(book.Id), "self", book.Title, HttpMethod.Get); resource.Links = new List <Link>(); if (book.IsCheckedOut) { var checkInLink = _resourceLinker.GetResourceLink <CheckInController>(request => request.Post(book.Id), "Check In", book.Title, HttpMethod.Post); resource.Links.Add(checkInLink); } if (book.IsCheckedIn) { var checkoutLink = _resourceLinker.GetResourceLink <CheckedOutController>(request => request.Post(book.Id), "Check Out", book.Title, HttpMethod.Post); resource.Links.Add(checkoutLink); } resource.Links.Add(_resourceLinker.GetResourceLink <RootController>(request => request.Get(), "Home", "Go Home", HttpMethod.Get)); return(resource); }
public static BookResource ToResource(this Book book, HttpRequestMessage request) { BookResource br = new BookResource(); br.ISBN = book.ISBN; br.ImageUrl = book.ImageUrl; br.Price = book.Price; br.Title = book.Title; var urlHelper = new UrlHelper(request); var routeValues = new { isbn = book.ISBN }; string link = urlHelper.Link("BookByISBN", routeValues); br.Links.Add(new Link() { Relationship = Relationship.Self, Verb = "GET", Uri = link }); br.Links.Add(new Link() { Relationship = Relationship.Parent, Verb = "GET", Uri = urlHelper.Route("ListOfBooks", new object()) }); return(br); }
public async Task <ActionResult <BookResource> > PutBook(int id, [FromBody] BookModel bookModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // You can make it like Yazan said from his document. var bookToUpdate = await _bookRepository.Get(id); if (bookToUpdate == null) { return(NotFound()); } var authors = _authorRepository.Get().Result.ToList().Where(e => bookModel.AuthorIds.Contains(e.Id)).ToList(); if (authors.Count < bookModel.AuthorIds.Count) { throw new Exception("Id is not correct"); } bookToUpdate.Title = bookModel.Title; bookToUpdate.Description = bookModel.Description; bookToUpdate.IsAvailable = bookModel.IsAvailable; bookToUpdate.PublisherId = bookModel.PublisherId; bookToUpdate.PublishedDate = bookModel.PublishedDate; bookToUpdate.Authors = authors; if (bookToUpdate == null) { return(NotFound()); } await _bookRepository.Update(bookToUpdate); // map authors list into book resource var listOfAuthorResource = new List <AuthorCreateResource>(); foreach (var author in authors) { var authorResource = new AuthorCreateResource { Id = author.Id, FullName = author.FullName }; listOfAuthorResource.Add(authorResource); } var bookResource = new BookResource { Id = bookToUpdate.Id, Title = bookToUpdate.Title, Description = bookToUpdate.Description, IsAvailable = bookToUpdate.IsAvailable, Publisher = bookToUpdate.Publisher.Name, PublishedDate = bookToUpdate.PublishedDate, AuthorNames = listOfAuthorResource }; //JObject obj = (JObject)JToken.FromObject(bookResource); //Console.WriteLine(bookResource); return(Ok(bookResource)); }
public BookResource SaveBook([FromBody] BookResource bookResource) { List <Tag> serverTags = this._dataBeastContext.Tags.ToList(); var tagsToSave = new List <Tag>(); foreach (Tag tag in bookResource.Tags .Split(',') .Select(e => e.Trim()) .Distinct() .Select(e => new Tag() { TagName = e.Trim(), })) { Tag tagToSave = serverTags.SingleOrDefault(e => tag.TagName == e.TagName); if (tagToSave != null) { // NOOP } else { tagToSave = this._dataBeastContext.Tags.Add(tag); } tagsToSave.Add(tagToSave); } var book = new Book() { Description = bookResource.Description, ISBN = bookResource.ISBN, InOrganizationSince = DateTime.Now, Tags = tagsToSave, Image = new byte[0], TimesTransfered = 0, Title = bookResource.Title, Author = bookResource.Author }; book.BookCopies = new List <BookCopy>() { new BookCopy() { Book = book, LastTransferDate = DateTime.Now, LendedTo = User.Identity.Name, Owner = this.User.Identity.Name } }; this._dataBeastContext.Books.Add(book); // Perist changes this._dataBeastContext.SaveChanges(); bookResource.Id = book.Id; bookResource.InOrganizationSince = book.InOrganizationSince; return(bookResource); }
public BookResource Update(BookResource book) { return(_modelToResourceMapper.Map(_bookRepository.Update(_resourceToModelMapper.Map(book)))); }
public GetBookResponse GetExamples() { BookResource bookResource = new BookResource { Id = Guid.NewGuid().ToString(), Title = "Hands-On Domain-Driven Design with .NET Core", PageCount = 446, Isbn = "9781788834094", DateOfPublication = new DateTime(2019, 04, 30), Authors = new BookAuthorsResource { Authors = new List <AuthorResource> { new AuthorResource { Name = "Alexey Zimarev", Description = "Alexey Zimarev is a ..." } } }, TableOfContents = new BookTableOfContentsResource { Chapters = new List <ChapterResource> { new ChapterResource { Number = "1", Name = "Why Domain-Driven Design?", Subsections = new List <SubsectionResource> { new SubsectionResource { Number = "1", Name = "Understanding the problem" }, new SubsectionResource { Number = "2", Name = "Dealing with complexity" } } }, new ChapterResource { Number = "2", Name = "Language and Context" }, new ChapterResource { Number = "3", Name = "EventStorming" }, } }, ShortDescription = "Solve complex business problems...", Description = new BookDescriptionResource { Learn = new LearnResource { Points = new List <string> { "Discover and...", "Avoid common...", } }, About = @"Developers across the world...", Features = new FeaturesResource { Points = new List <string> { "Apply DDD principles...", "Learn how DDD...", } } }, Publisher = "Packt", Url = "https://www.packtpub.com/application-development/hands-domain-driven-design-net-core" }; GetBookResponse response = new GetBookResponse(bookResource, StatusCodes.Status200OK); return(response); }