示例#1
0
        public ActionResult Detail(string id)
        {
            var service = new BooksService(new BaseClientService.Initializer()
            {
            });

            var request = service.Volumes.Get(id);
            var result = request.Execute();

            var industryIdentifier = result.VolumeInfo.IndustryIdentifiers.First(x => x.Type == "ISBN_13") ?? result.VolumeInfo.IndustryIdentifiers.First(x => x.Type == "ISBN_10");
            var imageLink = result.VolumeInfo.ImageLinks.Thumbnail;

            var viewModel = new BookDetailsViewModel {
                Author = result.VolumeInfo.Authors.Aggregate((i, j) => i + ", " + j),
                ISBN = industryIdentifier.Identifier,
                Title = result.VolumeInfo.Title,
                ImageLink = imageLink,
                Id = id,
                Description = result.VolumeInfo.Description
            };

            viewModel.Questions = new List<string> { "Which charater do you relate to the best, why?" };

            return View(viewModel);
        }
示例#2
0
        private void CheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
        {
            var bs          = new BooksService();
            var bookChecked = (CheckBox)sender;

            bs.UpdateBookCheck(bookChecked.IsChecked, Book);
        }
示例#3
0
        public async Task UpdateAndSaveTest()
        {
            var Books1 = new Books()
            {
                Book_id = "1", Book_title = "test Books 1", Book_shortDec = "test Book short 1", Book_dec = "test dec 1", Book_page = 1, Pub_id = "1"
            };
            var Books2 = new Books()
            {
                Book_id = "2", Book_title = "test Books 2", Book_shortDec = "test Book short 2", Book_dec = "test dec 2", Book_page = 2, Pub_id = "2"
            };
            var books = new List <Books> {
                Books1, Books2
            };

            var newBooks2 = new Books()
            {
                Book_id = "3", Book_title = "test Books 2", Book_shortDec = "test Book short 2", Book_dec = "test dec 2", Book_page = 2, Pub_id = "2"
            };

            var fakeBooksRepositoryMock = new Mock <IBooksRepository>();
            var fakeRoomRepositoryMock  = new Mock <IPublishersRepository>();

            fakeBooksRepositoryMock.Setup(x => x.Update(It.IsAny <Books>())).Callback <Books>(arg => books[1] = arg);

            var BooksService = new BooksService(fakeBooksRepositoryMock.Object, fakeRoomRepositoryMock.Object);

            await BooksService.UpdateAndSave(newBooks2);

            Assert.Equal("test Books 2", books[1].Book_title);
        }
        public void FindAllShould_ReturnCorrectResultIfPassedValueCanBeParsedToInt()
        {
            // Arrang
            int    catNum1 = 1;
            string title1  = "sometitle";
            int    catNum2 = 2;
            string title2  = "othertitle";
            Book   book1   = new Book()
            {
                CatalogueNumber = catNum1, Title = title1
            };
            Book book2 = new Book()
            {
                CatalogueNumber = catNum2, Title = title2
            };
            var list = new List <Book>()
            {
                book1, book2
            };
            var bookService = new BooksService(bookRepoMock.Object, contextMock.Object);

            // Act
            bookRepoMock.Setup(x => x.All).Returns(list.AsQueryable);
            var result = bookService.FindAll(catNum2.ToString()).First();

            // Assert
            Assert.AreEqual(result, book2);
        }
        public void FindSingleShould_ReturnCorrectValue()
        {
            // Arrange
            int  catNum = 1;
            Book book1  = new Book()
            {
                CatalogueNumber = catNum
            };
            Book book2 = new Book()
            {
                CatalogueNumber = catNum
            };
            var list = new List <Book>()
            {
                book1, book2
            };
            var bookService = new BooksService(bookRepoMock.Object, contextMock.Object);

            // Act
            bookRepoMock.Setup(x => x.AllAndDeleted).Returns(list.AsQueryable);
            var result = bookService.FindSingle(catNum);

            // Assert
            Assert.AreEqual(book1, result);
        }
示例#6
0
        public async Task GetBooksTest()
        {
            var books = new List <Books>
            {
                new Books()
                {
                    Book_Name = "super-patient", Author_Name = "super-patient2"
                },
                new Books()
                {
                    Book_Name = "invalid-patient", Author_Name = "invalid-patient2"
                },
            };

            var fakeRepositoryMock = new Mock <IBooksR>();

            fakeRepositoryMock.Setup(x => x.GetAll()).ReturnsAsync(books);


            var booksService = new BooksService(fakeRepositoryMock.Object);

            var resultBookss = await booksService.GetBooks();

            Assert.Collection(resultBookss, Books =>
            {
                Assert.Equal("super-patient", Books.Book_Name);
                Assert.Equal("super-patient2", Books.Author_Name);
            },
                              Books =>
            {
                Assert.Equal("invalid-patient", Books.Book_Name);
                Assert.Equal("invalid-patient2", Books.Author_Name);
            });
        }
 public GoogleBooksRepository(
     IGoogleBooksServiceFactory googleBooksServiceFactory,
     IMapper mapper)
 {
     _booksService = googleBooksServiceFactory.GetBooksService();
     _mapper       = mapper;
 }
示例#8
0
        public async Task GetBookByIdAsync_WithCorrectId_WorksCorrectly()
        {
            // Arrange
            var context      = this.NewInMemoryDatabase();
            var booksService = new BooksService(context);
            var expectedBook = new Book
            {
                Title     = "Book1",
                Publisher = new Publisher()
            };

            await context.Books.AddRangeAsync(expectedBook, new Book
            {
                Title     = "Book2",
                Publisher = new Publisher()
            });

            await context.SaveChangesAsync();

            // Act
            var actualBook = await booksService.GetBookByIdAsync <BookDetailsServiceModel>(expectedBook.Id);

            // Assert
            Assert.NotNull(actualBook);
            Assert.Equal(expectedBook.Title, actualBook.Title);
        }
示例#9
0
        private static void ListLibrary(BooksService service)
        {
            CommandLine.WriteAction("Listing Bookshelves ...");
            var response = service.Mylibrary.Bookshelves.List().Fetch();
            CommandLine.WriteLine();

            if (response.Items == null)
            {
                CommandLine.WriteError("No bookshelves found!");
                return;
            }
            foreach (Bookshelf item in response.Items)
            {
                CommandLine.WriteResult(item.Title, item.VolumeCount + " volumes");

                // List all volumes in this bookshelf.
                if (item.VolumeCount > 0)
                {
                    var request = service.Mylibrary.Bookshelves.Volumes.List(item.Id.ToString());
                    Volumes inBookshelf = request.Fetch();
                    if (inBookshelf.Items == null)
                    {
                        continue;
                    }

                    foreach (Volume volume in inBookshelf.Items)
                    {
                        CommandLine.WriteResult(
                            "-- " + volume.VolumeInfo.Title, volume.VolumeInfo.Description ?? "no description");
                    }
                }
            }
        }
        public void ReturnCorrectResultWhenThereAreNoBooksForApproval()
        {
            var mockedUnitOfWork = new Mock <IUnitOfWork>();
            var mockedRepository = new Mock <IRepository <Book> >();
            var bookService      = new BooksService(mockedRepository.Object, mockedUnitOfWork.Object);

            var mockedFirstBook = new Mock <Book>().Object;

            mockedFirstBook.IsApproved = true;

            var mockedSecondBook = new Mock <Book>().Object;

            mockedSecondBook.IsApproved = true;

            var books = new List <Book>();

            books.Add(mockedFirstBook);
            books.Add(mockedSecondBook);

            mockedRepository.Setup(x => x.GetAll).Returns(books.AsQueryable <Book>);

            var result = bookService.GetAllBooksForApproval().ToList();

            Assert.IsEmpty(result);
        }
        public void FindAllShould_ReturnEmptyCollectionIfNothingIsFound()
        {
            // Arrang
            int    catNum1 = 1;
            string title1  = "sometitle";
            int    catNum2 = 2;
            string title2  = "othertitle";
            Book   book1   = new Book()
            {
                CatalogueNumber = catNum1, Title = title1
            };
            Book book2 = new Book()
            {
                CatalogueNumber = catNum2, Title = title2
            };
            var list = new List <Book>()
            {
                book1, book2
            };
            var bookService = new BooksService(bookRepoMock.Object, contextMock.Object);

            // Act
            bookRepoMock.Setup(x => x.All).Returns(list.AsQueryable);
            var result = bookService.FindAll("book");

            // Assert
            Assert.AreEqual(0, result.Count());
        }
示例#12
0
        public async Task GetAllBooksAsync_WithBooks_WorksCorrectly()
        {
            // Arrange
            var expectedResult = new[] { "Book1", "Book2" };
            var context        = this.NewInMemoryDatabase();

            await context.Books.AddRangeAsync(
                new Book
            {
                Title = "Book2"
            },
                new Book
            {
                Title = "Book1"
            }
                );

            await context.SaveChangesAsync();

            var booksService = new BooksService(context);

            // Act
            var actualResult = (await booksService.GetAllBooksAsync <BookListingServiceModel>())
                               .Select(b => b.Title)
                               .ToArray();

            // Assert
            Assert.Equal(2, actualResult.Length);
            Assert.Equal(expectedResult, actualResult);
        }
示例#13
0
        private async Task Run()
        {
            UserCredential credential;
            var            path = Directory.GetCurrentDirectory() + @"\wwwroot\client_secrets.json";

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                dsAuthorizationBroker.RedirectUri = "http://*****:*****@gmail.com", CancellationToken.None, new FileDataStore("c://tmep")
                                                                        );

                //credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                //    GoogleClientSecrets.Load(stream).Secrets,
                //    new[] { BooksService.Scope.Books },
                //    "*****@*****.**", CancellationToken.None, new FileDataStore("c://tmep")
                //    );
            }

            // Create the service.
            var service = new BooksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Paluga",
            });

            // Revoke the credential.
            Console.WriteLine("\n!!!REVOKE ACCESS TOKEN!!!\n");
            await credential.RevokeTokenAsync(CancellationToken.None);

            // Reauthorize the user. A browser should be opened, and the user should enter his or her credential again.
            await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);
        }
        public void ReturnRatingOfTheCorrectBook()
        {
            // Arrange
            int id             = 5;
            int expectedRating = 10;
            var mockedData     = new Mock <IBetterReadsData>();
            var mockedBook1    = new BookMockedRating();

            mockedBook1.Id = 3;

            var mockedBook2 = new BookMockedRating();

            mockedBook2.Id = id;
            mockedBook2.SetRating(expectedRating);

            var booksData = new List <Book>
            {
                mockedBook1,
                mockedBook2
            }.AsQueryable();

            mockedData.Setup(x => x.Books.All).Returns(booksData);

            var service = new BooksService(mockedData.Object);

            // Act
            var rating = service.GetBookRating(id);

            // Assert
            Assert.AreEqual(expectedRating, rating);
        }
示例#15
0
        public async Task UpdateBooksAsync_WithCorrectData_WorksCorrectly()
        {
            // Arrange
            var context = this.NewInMemoryDatabase();

            var testBook = new Book
            {
                Title            = "TestBook1",
                Author           = "TestAuthor1",
                Price            = 11,
                Year             = 2011,
                Description      = "TestDescription1",
                ShortDescription = "TestShortDescription1",
                Pages            = 2,
                ImageUrl         = "http://example.com/favicon.ico1",
                Isbn             = "0000005000001",
                DownloadUrl      = "http://downloadtest.com/1"
            };

            await context.Books.AddAsync(testBook);

            await context.SaveChangesAsync();

            var updateModel = new BookEditServiceModel
            {
                Id               = testBook.Id,
                Title            = "TestBook",
                Author           = "TestAuthor",
                Price            = 1,
                Year             = 2001,
                Description      = "TestDescription",
                ShortDescription = "TestShortDescription",
                Pages            = 2,
                ImageUrl         = "http://example.com/favicon.ico",
                Isbn             = "0000005000000",
                DownloadUrl      = "http://downloadtest.com"
            };

            var booksService = new BooksService(context);

            // Act
            var result = await booksService.UpdateBookAsync(updateModel);

            // Assert
            Assert.True(result);

            var updatedBook = await context.Books.SingleOrDefaultAsync(b => b.Id == testBook.Id);

            Assert.NotNull(updatedBook);
            Assert.Equal(updateModel.Title, updatedBook.Title);
            Assert.Equal(updateModel.Author, updatedBook.Author);
            Assert.Equal(updateModel.Price, updatedBook.Price);
            Assert.Equal(updateModel.Year, updatedBook.Year);
            Assert.Equal(updateModel.Description, updatedBook.Description);
            Assert.Equal(updateModel.ShortDescription, updatedBook.ShortDescription);
            Assert.Equal(updateModel.Pages, updatedBook.Pages);
            Assert.Equal(updateModel.ImageUrl, updatedBook.ImageUrl);
            Assert.Equal(updateModel.Isbn, updatedBook.Isbn);
            Assert.Equal(updateModel.DownloadUrl, updatedBook.DownloadUrl);
        }
示例#16
0
        /// <summary>
        /// Retrieve Book Details From ISBN
        /// </summary>
        /// <param name="isbnNumber">ISBN Number for which Books information to be fetch.</param>
        /// <returns>Returns an Object</returns>
        public BookModel GetBookDetailFromISBN(string isbnNumber)
        {
            try
            {
                BooksService service = new BooksService(new BaseClientService.Initializer
                {
                    ApplicationName = "BooksAPI",
                    ApiKey          = ProjectConfiguration.GoogleBookService_APIKey
                });

                var result = service.Volumes.List($"isbn:{isbnNumber}").Execute()?.Items?.FirstOrDefault();
                if (result?.VolumeInfo != null)
                {
                    ////DateTime dt;
                    ////DateTime.TryParseExact(result.VolumeInfo.PublishedDate, new string[] { "yyyy-MM-dd", "yyyy-MM", "yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);

                    return(new BookModel
                    {
                        BookName = result.VolumeInfo.Title,
                        ISBNNo = isbnNumber,
                        Image = ConvertTo.ImageToBase64(result.VolumeInfo.ImageLinks?.Thumbnail),
                        Description = result.VolumeInfo.Description,
                        Authors = string.Join(", ", result.VolumeInfo.Authors ?? new[] { result.VolumeInfo.Publisher.String() }),
                        Publisher = result.VolumeInfo.Publisher,
                        ////PublishDate = dt == default(DateTime) ? (DateTime?)null : dt
                    });
                }
            }
            catch (Exception e)
            {
            }

            return(null);
        }
示例#17
0
        public void GetDataFromGoogleBooks()
        {
            ClearAll();

            // not a real test yet....
            var url = BooksService.GetSearchUrl("MonoTouch");

            var json   = new Cirrious.MvvmCross.Plugins.Json.MvxJsonConverter();
            var client = new Cirrious.MvvmCross.Plugins.Network.Rest.MvxJsonRestClient
            {
                JsonConverterProvider = () => json
            };
            var request = new MvxRestRequest(url);
            MvxDecodedRestResponse <BookSearchResult> theResponse = null;
            Exception exception = null;

            client.MakeRequestFor <BookSearchResult>(request,
                                                     (result) => { theResponse = result; },
                                                     (error) => { exception = error; });

            System.Threading.Thread.Sleep(3000);
            Assert.IsNotNull(theResponse);
            Assert.IsNull(exception);
            Assert.IsNotNull(theResponse.Result);
            Assert.AreEqual(HttpStatusCode.OK, theResponse.StatusCode);
            Assert.IsTrue(theResponse.Result.items.Count == 10);
            Assert.IsTrue(theResponse.Result.items[0].ToString().Contains("MonoTouch"));
        }
示例#18
0
        public async Task GetDataFromGoogleBooks()
        {
            ClearAll();

            // not a real test yet....
            var url = BooksService.GetSearchUrl("MonoTouch");

            var json   = new MvxJsonConverter();
            var client = new MvxJsonRestClient
            {
                JsonConverterProvider = () => json
            };
            var request = new MvxRestRequest(url);
            MvxDecodedRestResponse <BookSearchResult> theResponse = null;
            Exception exception = null;

            theResponse = await client.MakeRequestForAsync <BookSearchResult>(request);

            Assert.IsNotNull(theResponse);
            Assert.IsNull(exception);
            Assert.IsNotNull(theResponse.Result);
            Assert.AreEqual(HttpStatusCode.OK, theResponse.StatusCode);
            Assert.IsTrue(theResponse.Result.items.Count == 10);
            Assert.IsTrue(theResponse.Result.items[0].ToString().Contains("MonoTouch"));
        }
示例#19
0
        public async Task <GooglePayload> ValidateBearerTokenAsync(string authCode)
        {
            var authorizationCodeFlow = new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets()
                {
                    ClientId     = _identityOptions.GoogleClientId,
                    ClientSecret = _identityOptions.GoogleClientSecret
                }
            });

            TokenResponse tokenResponse = await authorizationCodeFlow
                                          .ExchangeCodeForTokenAsync("me", authCode, "http://localhost:8080", CancellationToken.None);

            UserCredential userCredential = new UserCredential(authorizationCodeFlow, "me", tokenResponse);

            BooksService booksService = new BooksService(new BaseClientService.Initializer
            {
                HttpClientInitializer = userCredential
            });

            Bookshelves test = await booksService.Mylibrary.Bookshelves.List().ExecuteAsync();

            Payload payload = await ValidateAsync(tokenResponse.IdToken, GetValidationSettings());

            return(new GooglePayload(payload, tokenResponse.AccessToken, tokenResponse.RefreshToken));
        }
示例#20
0
        private async Task DisplayVolumes(BooksService service, Bookshelves bookshelves)
        {
            if (bookshelves.Items == null)
            {
                Console.WriteLine("No bookshelves found!");
                return;
            }

            foreach (Bookshelf item in bookshelves.Items)
            {
                Console.WriteLine(item.Title + "\t" +
                                  (item.VolumeCount.HasValue ? item.VolumeCount + " volumes" : ""));

                // List all volumes in this bookshelf.
                if (item.VolumeCount > 0)
                {
                    Console.WriteLine("Query volumes... (Execute ASYNC)");
                    Console.WriteLine("--------------------------------");
                    var     request     = service.Mylibrary.Bookshelves.Volumes.List(item.Id.ToString());
                    Volumes inBookshelf = await request.ExecuteAsync();

                    if (inBookshelf.Items == null)
                    {
                        continue;
                    }
                    foreach (Volume volume in inBookshelf.Items)
                    {
                        Console.WriteLine("-- " + volume.VolumeInfo.Title + "\t" + volume.VolumeInfo.Description ??
                                          "no description");
                        Console.WriteLine();
                    }
                }
            }
        }
示例#21
0
        public async Task AddTagToBookAsync_WithExistingBookTagRelation_ReturnsFalse()
        {
            // Arrange
            var context      = this.NewInMemoryDatabase();
            var booksService = new BooksService(context);
            var tag          = new Tag();
            var book         = new Book();

            await context.Tags.AddAsync(tag);

            await context.Books.AddAsync(book);

            await context.BookTags.AddAsync(new BookTag
            {
                BookId = book.Id,
                TagId  = tag.Id
            });

            await context.SaveChangesAsync();

            // Act
            var result = await booksService.AddTagToBookAsync(book.Id, tag.Id);

            // Assert
            Assert.False(result);
        }
示例#22
0
        public void ShouldReturnFiltered()
        {
            //Arrange
            var mockRepo = new Mock <IBookRepository>();
            var list     = new List <Book> {
                new Book {
                    Name = "Gone", AuthorName = "AuthorTest1"
                }, new Book {
                    Name = "Gone in the wind", AuthorName = "AuthorTest2"
                },
                new Book {
                    Name = "The Bible", AuthorName = "AuthorTest2"
                }
            };

            mockRepo.Setup(x => x.GetAll()).Returns(list);
            var bookService = new BooksService(mockRepo.Object);

            //Act
            var booksReturned  = bookService.GetBooks("biB");
            var booksReturned2 = bookService.GetBooks("Bi");
            var booksReturned3 = bookService.GetBooks("GONE");
            var booksReturned4 = bookService.GetBooks("");

            //Assert
            Assert.Single(booksReturned);
            Assert.Single(booksReturned2);
            Assert.Equal(2, booksReturned3.Count());
            Assert.Equal(3, booksReturned4.Count());
        }
示例#23
0
        public async Task RemoveTagFromBookAsync_WithIncorrectBookId_ReturnsFalse()
        {
            // Arrange
            var tagId  = Guid.NewGuid().ToString();
            var fakeId = Guid.NewGuid().ToString();

            var context = this.NewInMemoryDatabase();

            await context.BookTags.AddAsync(new BookTag
            {
                BookId = Guid.NewGuid().ToString(),
                TagId  = tagId
            });

            await context.SaveChangesAsync();

            var booksService = new BooksService(context);

            // Act
            var result = await booksService.RemoveTagFromBookAsync(fakeId, tagId);

            // Assert
            Assert.False(result);
            Assert.Equal(1, await context.BookTags.CountAsync());
        }
示例#24
0
 public GoogleBookService()
 {
     _service = new BooksService(new BaseClientService.Initializer
     {
         ApiKey = ConfigurationManager.AppSettings["GoogleAccountApiKey"]
     });
 }
示例#25
0
        public async Task CreateBookAsync_WithIncorrectModel_ReturnsNull()
        {
            // Arrange
            var context = this.NewInMemoryDatabase();

            var serviceModel = new BookCreateServiceModel
            {
                Title            = "TestTitle",
                Author           = "TestAuthor",
                Price            = -300, // Invalid Price
                Year             = 2000,
                Description      = "TestDescription",
                ShortDescription = "TestShortDescription",
                Pages            = 1,
                ImageUrl         = "http://example.com/favicon.ico",
                Isbn             = "0000005000000",
                PublisherId      = Guid.NewGuid().ToString()
            };

            var booksService = new BooksService(context);

            // Act
            var createdId = await booksService.CreateBookAsync(serviceModel);

            // Assert
            Assert.Null(createdId);
            Assert.False(await context.Books.AnyAsync());
        }
示例#26
0
        public void ReturnCorrectBook(int id)
        {
            // Arrange
            var mockedData   = new Mock <IBetterReadsData>();
            var expectedBook = new Book();

            expectedBook.Id = id;
            var books = new List <Book>
            {
                new Mock <Book>().Object,
                new Mock <Book>().Object,
                expectedBook,
                new Mock <Book>().Object,
                new Mock <Book>().Object,
            }.AsQueryable();

            mockedData.Setup(x => x.Books.All).Returns(books);

            var service = new BooksService(mockedData.Object);

            // Act
            var book = service.GetById(id);

            // Assert
            Assert.AreEqual(expectedBook, book);
        }
示例#27
0
 public DeleteFavoriteBookshelfCommandHandler(
     IGoogleBooksServiceFactory googleBooksServiceFactory,
     IApplicationDbContext applicationDbContext)
 {
     _booksService = googleBooksServiceFactory.GetBooksService();
     _context      = applicationDbContext;
 }
示例#28
0
 public async Task DetailTest()
 {
     var fake         = Mock.Of <IBooksR>();
     var booksService = new BooksService(fake);
     var id           = 2;
     await booksService.DetailsBooks(id);
 }
示例#29
0
        public async Task CreateBookAsync_WithCorrectModel_WorksCorrectly()
        {
            // Arrange
            var context = this.NewInMemoryDatabase();

            var booksService = new BooksService(context);

            var serviceModel = new BookCreateServiceModel
            {
                Title            = "TestTitle",
                Author           = "TestAuthor",
                Price            = 1,
                Year             = 2000,
                Description      = "TestDescription",
                ShortDescription = "TestShortDescription",
                Pages            = 1,
                ImageUrl         = "http://example.com/favicon.ico",
                Isbn             = "0000005000000",
                PublisherId      = Guid.NewGuid().ToString(),
                DownloadUrl      = "http://example.com/download.ico"
            };

            // Act
            var createdId = await booksService.CreateBookAsync(serviceModel);

            // Assert
            Assert.NotNull(createdId);
            Assert.Equal(1, await context.Books.CountAsync());
            Assert.True(await context.Books.AnyAsync(b => b.Id == createdId));
        }
示例#30
0
 private void OnButtonClick(object sender, RoutedEventArgs e)
 {
     var service = new BooksService();
     // Book b = service.GetTheBook();
     // button2.Content = service.GetBooks();
     list1.ItemsSource = service.GetBooks();
     flip1.ItemsSource = service.GetBooks();
 }
示例#31
0
        public ActionResult Search(string searchTerm)
        {
            // Create the service.
            var service = new BooksService(new BaseClientService.Initializer()
            {
                //ApiKey = "IzaSyBv71CkLIRo_JmLo9UeZud8kRNFVJ1Sb0k"
            });

            var request = new VolumesResource.ListRequest(service, searchTerm);
            request.MaxResults = 40;

            var searchResult = request.Execute();

            var result = new SearchResultsViewModel();

            result.SearchTerm = searchTerm;

            foreach (var resultItem in searchResult.Items)
            {
                if (!result.Books.Exists(x => x.Title == resultItem.VolumeInfo.Title))
                {
                    var bookViewModel = new BookViewModel
                    {
                        Title = resultItem.VolumeInfo.Title,
                        ID = resultItem.Id
                    };
                    var author = resultItem.VolumeInfo.Authors != null ? resultItem.VolumeInfo.Authors.Aggregate((i, j) => i + ", " + j) : null;
                    Google.Apis.Books.v1.Data.Volume.VolumeInfoData.IndustryIdentifiersData industryIdentifier = null;

                    if (resultItem.VolumeInfo.IndustryIdentifiers != null && resultItem.VolumeInfo.IndustryIdentifiers.Any())
                    {
                        industryIdentifier = resultItem.VolumeInfo.IndustryIdentifiers.FirstOrDefault(x => x.Type == "ISBN_13") ??
                            resultItem.VolumeInfo.IndustryIdentifiers.FirstOrDefault(x => x.Type == "ISBN_10");
                    }

                    var imageLink = resultItem.VolumeInfo.ImageLinks != null ? resultItem.VolumeInfo.ImageLinks.SmallThumbnail : null;

                    if (industryIdentifier != null && imageLink != null && author != null)
                    {
                        bookViewModel.Author = author;
                        bookViewModel.ImageLink = imageLink;
                        bookViewModel.ISBN = industryIdentifier.Identifier;
                        result.Books.Add(bookViewModel);
                    }
                }
            }

            return View(result);
        }
示例#32
0
        static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Books API: List MyLibrary");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret = credentials.ClientSecret;
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);

            // Create the service.
            var service = new BooksService(auth);
            ListLibrary(service);
            CommandLine.PressAnyKeyToExit();
        }
        private async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { BooksService.Scope.Books },
                    "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
            }

            // Create the service.
            var service = new BooksService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Books API Sample",
                });

            // List library.
            await ListLibrary(service);

            // Revoke the credential.
            Console.WriteLine("\n!!!REVOKE ACCESS TOKEN!!!\n");
            await credential.RevokeTokenAsync(CancellationToken.None);

            // Request should fail now - invalid grant.
            try
            {
                await ListLibrary(service);
            }
            catch (TokenResponseException ex)
            {
                Console.WriteLine(ex.Error);
            }

            // Reauthorize the user. A browser should be opened, and the user should enter his or her credential again.
            await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);

            // The request should succeed now.
            await ListLibrary(service);
        }
        private async Task ListLibrary(BooksService service)
        {
            Console.WriteLine("\n\n\nListing Bookshelves... (Execute ASYNC)");
            Console.WriteLine("======================================");

            // Execute async.
            var bookselve = await service.Mylibrary.Bookshelves.List().ExecuteAsync();

            // On success display my library's volumes.
            await DisplayVolumes(service, bookselve);
        }
        private async Task DisplayVolumes(BooksService service, Bookshelves bookshelves)
        {
            if (bookshelves.Items == null)
            {
                Console.WriteLine("No bookshelves found!");
                return;
            }

            foreach (Bookshelf item in bookshelves.Items)
            {
                Console.WriteLine(item.Title + "\t" +
                    (item.VolumeCount.HasValue ? item.VolumeCount + " volumes" : ""));

                // List all volumes in this bookshelf.
                if (item.VolumeCount > 0)
                {
                    Console.WriteLine("Query volumes... (Execute ASYNC)");
                    Console.WriteLine("--------------------------------");
                    var request = service.Mylibrary.Bookshelves.Volumes.List(item.Id.ToString());
                    Volumes inBookshelf = await request.ExecuteAsync();
                    if (inBookshelf.Items == null)
                    {
                        continue;
                    }
                    foreach (Volume volume in inBookshelf.Items)
                    {
                        Console.WriteLine("-- " + volume.VolumeInfo.Title + "\t" + volume.VolumeInfo.Description ??
                            "no description");
                        Console.WriteLine();
                    }
                }
            }
        }