public Book?GetCopies(string isbn) { var query = "SELECT LibraryBooks.isbn, Books.title, Books.authors, LibraryBooks.bookId, AspNetUsers.UserName, Loans.dueDate " + "FROM LibraryBooks " + "JOIN Books ON LibraryBooks.isbn = Books.isbn " + "LEFT JOIN Loans ON LibraryBooks.bookId = Loans.bookId " + "LEFT JOIN AspNetUsers ON AspNetUsers.Id = Loans.userId " + $"WHERE LibraryBooks.isbn='{isbn}';"; Book?outBook = null; var bookWithCopies = databaseConnection.Query <Book, BookCopy, Book>( query, (book, bookCopy) => { outBook ??= book; outBook.bookCopies.Add(bookCopy); return(outBook); }, splitOn: "bookId") .FirstOrDefault(); return(bookWithCopies); }
private static bool TryParseBook(string input, out Book?book) { // Verify an ET EXT No. exists in the chunk; if (!EtExtRegex.IsMatch(input)) { book = null; return(false); } // Try parsing the chunk with the ET EXT No. filtered out. var filtered = EtExtRegex.Replace(input, string.Empty); var bookMatch = BookRegex.Match(filtered); if (!bookMatch.Success) { book = null; return(false); } var title = bookMatch.Groups["Title"].Value.Replace("\n", string.Empty); var author = bookMatch.Groups["Author"].Value; book = new Book(title, author); return(true); }
private static async Task <IResult> GetBookById(string id, IRepository <Book> bookRepository, IRepository <BookByIdReference> bookByIdReferenceRepository) { string?category; try { BookByIdReference?idReference = await bookByIdReferenceRepository.GetAsync(id); category = idReference.Category; } catch (CosmosException e) when(e.StatusCode is HttpStatusCode.NotFound) { Console.WriteLine(e); throw; } try { Book?book = await bookRepository.GetAsync(id, category); return(Results.Ok(book.ToBookDto())); } catch (CosmosException e) when(e.StatusCode is HttpStatusCode.NotFound) { return(Results.NotFound()); } }
public async Task TemporalPointInTimeQueryAsync() { Book?book = await _booksContext.Books.FindAsync(1); if (book is null) { return; } // read shadow property for time if (_booksContext.Entry(book).CurrentValues["PeriodStart"] is DateTime periodStart) { DateTime previousTime = periodStart.AddSeconds(-4); var previousBook = await _booksContext.Books .TemporalAsOf(previousTime) .TagWith("temporalasof") .SingleOrDefaultAsync(b => b.BookId == book.BookId); Console.WriteLine($"actual: {book.BookId}: {book.Title}, {book.Publisher}"); if (previousBook is not null) { Console.WriteLine($"earlier: {previousBook.BookId}: {previousBook.Title}, " + $"{previousBook.Publisher}"); } } }
public BookChangeEvent(Guid eventId, string version, Guid bookId, ChangeType type, Book?data) { EventId = eventId; Version = version; BookId = bookId; Type = type; Data = data; }
public override Book CreateCopy(Book?item) { int id = item?.BookId ?? -1; string title = item?.Title ?? "enter a title"; string publisher = item?.Publisher ?? "enter a publisher"; return(new Book(title, publisher, id)); }
private static async Task <BookDto> CreateBook(CreateBookDto createBookDto, IRepository <Book> bookRepository) { Book book = createBookDto.ToBook(); Book?createdBook = await bookRepository.CreateAsync(book); return(createdBook.ToBookDto()); }
public Task <bool> DeleteAsync(int id) { Book?bookToDelete = _books.Find(b => b.BookId == id); if (bookToDelete != null) { return(Task.FromResult(_books.Remove(bookToDelete))); } return(Task.FromResult(false)); }
public async Task <IActionResult> Delete(int id) { Book?book = await _session.GetAsync <Book>(id); if (book != null) { await _session.DeleteAsync(book); } return(NoContent()); }
static void Main(string[] args) { int? @int = null; // int @int = null; // Error, harus ada operator nullable (<type>? <variable>) short? @short = null; // short @short = null; // Error, harus ada operator nullable (<type>? <variable>) long? @long = null; // long @long = null; // Error, harus ada operator nullable (<type>? <variable>) float? @float = null; // long @long = null; // Error, harus ada operator nullable (<type>? <variable>) double? @double = null; // long @long = null; // Error, harus ada operator nullable (<type>? <variable>) decimal? @decimal = null; // decimal @decimal = null; // Error, harus ada operator nullable (<type>? <variable>) bool? @bool = null; // bool @bool = null; // Error, harus ada operator nullable (<type>? <variable>) char? @char = null; // char @char = null; // Error, harus ada operator nullable (<type>? <variable>) byte? @byte = null; // byte? @byte = null; // Error, harus ada operator nullable (<type>? <variable>) Book?book = null; // Book book = null; // Error, harus ada operator nullable (<type>? <variable>) Shapes shape = null; string @string = null; // Tidak Error, // Using null coalescing operator string str01 = null, str02 = null, str03 = null, str04 = "Have String", str05 = "Second string"; string strFinal = str01 ?? str02 ?? str03 ?? str04 ?? str05; Console.WriteLine("String yang dicetak : " + strFinal); int?var01 = null; int?var02 = null; int?var03 = null; int?var04 = null; int?var05 = 100; int?var06 = 500; int?strF = var01 ?? var02 ?? var03 ?? var04 ?? var05 ?? var06; Console.WriteLine("String yang dicetak : {0}", strF); Console.ReadKey(); }
public ValueTask ExecuteAsync(IConsole console) { Book?book = _libraryService.GetBook(Title); if (book is null) { throw new CommandException("Book not found.", 1); } console.RenderBook(book); return(default);
public Task <Book?> UpdateAsync(Book item) { Book?bookToUpdate = _books.Find(b => b.BookId == item.BookId); if (bookToUpdate == null) { return(Task.FromResult <Book?>(null)); } int ix = _books.IndexOf(bookToUpdate); _books[ix] = item; return(Task.FromResult <Book?>(_books[ix])); }
public async Task UpdateBookAsync() { Book?book = _booksContext.Books.Find(1); if (book != null) { book.Title = "Professional C# and .NET - 2021 Edition"; int records = await _booksContext.SaveChangesAsync(); Console.WriteLine($"{records} record updated"); } Console.WriteLine(); }
public async Task <int> PrepareUpdateAsync(string user, int id = 0) { _user = user; if (id is 0) { _selectedBook = await _booksContext.Books.OrderBy(b => b.BookId).LastAsync(); return(_selectedBook.BookId); } _selectedBook = await _booksContext.Books.FindAsync(id); return(id); }
public ValueTask ExecuteAsync(IConsole console) { Book?book = _libraryService.GetBook(Title); if (book == null) { throw new CommandException("Book not found.", 1); } _libraryService.RemoveBook(book); console.Output.WriteLine($"Book {Title} removed."); return(default);
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Book = await _context.Books !.AsQueryable().FirstOrDefaultAsync(m => m.Id == id); if (Book == null) { return(NotFound()); } return(Page()); }
public async Task <IActionResult> Update(int id, [FromBody] UpdateBookArgs args) { Book?book = await _session.GetAsync <Book>(id); if (book == null) { return(NotFound()); } book.Author = args.Author; book.Price = args.Price; book.Title = args.Title; await _session.UpdateAsync(book); return(NoContent()); }
public ActionResult Index(Book book) { Book?oldBook = Session["book"] as Book?; if (oldBook.HasValue) { Votes.ChangeVote(oldBook.Value, book); } else { Votes.RegisterVote(book); } ViewBag.SelectedBook = Session["book"] = book; return(View()); }
public async Task UpdateBookAsync() { Book?book = await _booksContext.Books.FindAsync(1); Console.WriteLine("Just a short delay before updating..."); await Task.Delay(TimeSpan.FromSeconds(5)); if (book != null) { book.Title = "Professional C# and .NET - 2021 Edition"; int records = await _booksContext.SaveChangesAsync(); Console.WriteLine($"{records} record updated"); } Console.WriteLine(); }
public async Task <IActionResult> OnGetAsync(string key) { var books = from s in _db.Book where s.Key == key select s; Books = await books.AsNoTracking().ToListAsync().ConfigureAwait(false); if (Books == null || !Books.Any()) { return(RedirectToPage("book-accuracy-list")); } Book = Books.First(); return(Page()); }
public async Task <IActionResult> PutBook(string isbnString, EditBookVM bookVm) { var isbn = _isbnFactory.Create(isbnString); Book?book = await _repository.Get(isbn); if (book == null) { return(NotFound()); } book.Title = bookVm.Title; book.Description = bookVm.Description; await _repository.Update(book); return(NoContent()); }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } Book = await _context.Books.FindAsync(id); if (Book != null) { _context.Books.Remove(Book); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Book = await _context.Books .Include(b => b.Language) .Include(b => b.Publisher).FirstOrDefaultAsync(m => m.BookId == id); if (Book == null) { return(NotFound()); } return(Page()); }
public async Task UpdateBookAsync() { Book?book = await _booksContext.Books.FindAsync(1); if (book != null) { // detach the existing object from the context which allows to attach it with the Update method _booksContext.Entry(book).State = EntityState.Detached; Book bookUpdate = book with { Title = "Professional C# and .NET - 2021 Edition" }; _booksContext.Update(bookUpdate); int records = await _booksContext.SaveChangesAsync(); Console.WriteLine($"{records} record updated"); } Console.WriteLine(); }
public IActionResult Update([FromBody] Book?book) { var validationError = ValidateBook(book); if (validationError != null) { return(BadRequest(validationError)); } var updatedBook = booksRepository.TryUpdate(book !); if (updatedBook == null) { return(BadRequest("Book has not updated")); } return(Ok(updatedBook)); }
private string?ValidateBook(Book?book) { if (book == null) { return("Body is required"); } if (string.IsNullOrEmpty(book.IsbnNumber)) { return("IsbnNumber is required"); } if (string.IsNullOrEmpty(book.Name)) { return("Name is required"); } return(null); }
public async Task CacheTimestamp_Abs_TestAsync(int?absoluteSecondsRelativeToNow, int?slidingSeconds) { DistributedCacheEntryOptions entryOptions = new DistributedCacheEntryOptions(); entryOptions.AbsoluteExpirationRelativeToNow = absoluteSecondsRelativeToNow == null ? null : (TimeSpan?)TimeSpan.FromSeconds(absoluteSecondsRelativeToNow.Value); entryOptions.SlidingExpiration = slidingSeconds == null ? null : (TimeSpan?)TimeSpan.FromSeconds(slidingSeconds.Value); IDatabase database = _redisConnection.GetDatabase(_databaseNumber); Book book = Mocker.MockOne(); await AddToDatabaeAsync(new Book[] { book }).ConfigureAwait(false); //typeof(Book).GetProperty("Guid").SetValue(book, "123"); //book.Guid = "12345"; //book.Name = "abc"; //book.BookID = 222; await _cache.SetAsync(nameof(Book) + book.Id.ToString(), book, TimeUtil.UtcNowTicks, entryOptions).ConfigureAwait(false); Assert.True(database.KeyExists(_applicationName + nameof(Book) + book.Id.ToString())); await Task.Delay(10 * 1000); Book?cached3 = await _cache.GetAsync <Book>(nameof(Book) + book.Id.ToString()).ConfigureAwait(false); Assert.True(cached3 != null); Assert.True(SerializeUtil.ToJson(book) == SerializeUtil.ToJson(cached3 !)); await Task.Delay(10 * 1000); Book?cached4 = await _cache.GetAsync <Book>(nameof(Book) + book.Id.ToString()); Assert.False(cached4 != null); }
public override ValueTask Handle(ReadOnlyMemory <byte> data) { var update = JsonSerializer.Deserialize <BookUpdate>(data.Span, SerializationOptions.Instance); if (update.Snapshot) { _book = Book.FromSnapshot(ref update); } else if (_book is not null) { _book = _book.Apply(ref update); } if (_book is not null) { foreach (var subscriber in _subscriptions) { subscriber.Handle(_book); } } return(default);
public async Task <bool> SaleOut(string bookName, int bookCount) { Book?aBook = await GetByBookName(bookName); //找不到书籍 if (aBook == null) { return(false); } //数量不足 int i = aBook.Quantity - bookCount; if (i < 0) { return(false); } //成功修改 aBook.Quantity = aBook.Quantity - bookCount; _context.SaveChanges(); return(true); }
public static void StructDemos() { // Initialize: Coords coords1 = new Coords(); Coords coords2 = new Coords(10, 10); // Display results: Console.Write("Coords 1: "); Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y); Console.Write("Coords 2: "); Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y); // Declare an object: Coords coords3; // Initialize: coords3.x = 10; coords3.y = 20; // Display results: Console.Write("Coords 1: "); Console.WriteLine("x = {0}, y = {1}", coords3.x, coords3.y); Book?book123 = null; //nullable type; if your remove ? get erro for keyword null Book b1Obj = new Book("xx", "yy", 564); Console.WriteLine(b1Obj.DiaplyBookDetails()); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }