public BookController(BookRepo bookRepo, AuthorRepo authors, GenreRepo genres, IWebHostEnvironment webHostEnvironment)
 {
     _bookrepo           = bookRepo;
     _authorRepo         = authors;
     _genreRepo          = genres;
     _webHostEnvironment = webHostEnvironment;
 }
Esempio n. 2
0
        public AuthorAdd()
        {
            InitializeComponent();
            var personRepo = new PersonRepo();

            _authorRepo = new AuthorRepo(personRepo);
        }
        public void Setup()
        {
            var        config = GeneralHelpers.InitConfiguration();
            AuthorRepo a      = new AuthorRepo(config);

            _testRepo = a;
        }
Esempio n. 4
0
 public Manager(UserRepo _userGenericRepository,
                AuthorRepo _authorGenericRepository,
                ArticleRepo _articleGenericRepository)
 {
     this._userGenericRepository    = _userGenericRepository;
     this._authorGenericRepository  = _authorGenericRepository;
     this._articleGenericRepository = _articleGenericRepository;
 }
Esempio n. 5
0
 public BookByAuthor()
 {
     InitializeComponent();
     _personRepo = new PersonRepo();
     _authorRepo = new AuthorRepo(_personRepo);
     InitializeList();
     RefreshInfo();
 }
Esempio n. 6
0
 public Manager(UserRepo _userGenericRepository, 
                AuthorRepo _authorGenericRepository, 
                ArticleRepo _articleGenericRepository)
 {
     this._userGenericRepository = _userGenericRepository;
     this._authorGenericRepository = _authorGenericRepository;
     this._articleGenericRepository = _articleGenericRepository;
 }
        static void Main(string[] args)
        {
            var repo    = new AuthorRepo();
            var authors = repo.GetAuthors();

            Console.WriteLine($"There are {authors.Count()} total authors");
            Console.WriteLine($"with {authors.SelectMany(a => a.Books).Count()} total books");

            //================= 1 =================
            Console.WriteLine("1. How many books are collaborations (have more than one author)?");
            var booksCollaborations = authors
                                      .SelectMany(author => author.Books)
                                      .GroupBy(book => book.ID)
                                      .Where(duplicate => duplicate.Count() > 1)
                                      .ToList();

            Console.WriteLine($"- {booksCollaborations.Count()} books.");

            //================= 2 =================
            Console.WriteLine("2. Which book has the most authors (and how many)?");
            var bookMostAuthors = booksCollaborations
                                  .OrderByDescending(duplicateNo => duplicateNo.Count())
                                  .FirstOrDefault();
            var bookTitle = bookMostAuthors
                            .FirstOrDefault();

            var collaborationAuthorsNo = bookMostAuthors.Count();

            Console.WriteLine($"- {bookTitle.Title} has {collaborationAuthorsNo} authors.");

            //================= 3 =================
            Console.WriteLine("3. What author wrote most collaborations?");

            var collaborationList = authors
                                    .SelectMany(book => book.Books)
                                    .Where(book => (booksCollaborations
                                                    .Select(a => a.Key))
                                           .Any(b => b == book.ID))
                                    .ToList();

            var collaborationsNo = authors
                                   .Select(author => author.Books
                                           .Where(books => collaborationList
                                                  .Any(book => book.ID == books.ID))
                                           .Count())
                                   .Max();

            var authorMostCollaborations = authors
                                           .Where(author => author.Books
                                                  .Where(books => collaborationList
                                                         .Any(book => book.ID == books.ID))
                                                  .Count() == collaborationsNo)
                                           .FirstOrDefault();

            Console.WriteLine($"Author: {authorMostCollaborations.Name} Collaborations: {collaborationsNo}");

            Console.ReadLine();
        }
        public AuthorRemove()
        {
            InitializeComponent();
            var personRepo = new PersonRepo();

            _authorRepo = new AuthorRepo(personRepo);
            _index      = 0;
            SetData();
        }
Esempio n. 9
0
        public ActionResult Index()
        {
            var model = AuthorRepo.List();

            if (Request.IsAjaxRequest())
            {
                return(PartialView("AuthorPartialView", model));
            }
            return(View(model));
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            var authorRepo = new AuthorRepo();
            var authors    = authorRepo.GetAuthors();

            var result = authors.SelectMany(a => a.Books).GroupBy(b => b.ID).Where(g => g.Count() > 1);

            foreach (var duplicates in result)
            {
                foreach (var book in duplicates)
                {
                    Console.WriteLine(book);
                }
            }

            //Random r = new Random();

            //var randomHalf = authors.Where(_ => r.NextDouble() > 0.5);

            //Console.WriteLine(authors.Count());
            //Console.WriteLine(randomHalf.Count());

            var totalBooks = authors.SelectMany(a => a.Books).Distinct(new BookComparer());

            var bookIds = authors.SelectMany(a => a.Books).Select(b => b.ID).Distinct();

            Console.WriteLine(totalBooks.Count());
            Console.WriteLine(bookIds.Count());

            var doubles = totalBooks.Where(b => b.ID == 21358);

            Console.WriteLine(doubles.Count());

            foreach (var book in doubles)
            {
                Console.WriteLine(book);
            }

            totalBooks
            //.Select((b, index)=> (Index:index+1, Title:b.Title, ID: b.ID ))
            .Select((b, index) => (Index: index + 1, b.Title, b.ID))
            .Print(item => $"{item.Index}. {item.Title} ({item.ID})");

            //  Name (ID)
            //  Name (ID)
            //  Name (ID)
            //

            //  1. Name (ID)
            //  2. Name (ID)
            //  3. Name (ID)
            //
        }
Esempio n. 11
0
        public ActionResult Create(Author collection)
        {
            ReturnEx(collection.Id);
            // TODO: Add insert logic here
            AuthorRepo.Create(collection);
            if (Request.IsAjaxRequest())
            {
                return(PartialView("AuthorPartialView", collection));
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 12
0
        public BookAdd()
        {
            InitializeComponent();
            var _personRepo = new PersonRepo();

            _bookRepo       = new BookRepo();
            _typeBookRepo   = new TypeBookRepo(_bookRepo);
            _genreRepo      = new GenreRepo();
            _publisherRepo  = new PublisherRepo();
            _authorRepo     = new AuthorRepo(_personRepo);
            _firstIteration = true;
            StartingPoint();
        }
Esempio n. 13
0
        public BookEdit()
        {
            InitializeComponent();
            var personRepo = new PersonRepo();
            var bookRepo   = new BookRepo();

            _typeBook       = new TypeBookRepo(bookRepo);
            _authorRepo     = new AuthorRepo(personRepo);
            _publisherRepo  = new PublisherRepo();
            _genreRepo      = new GenreRepo();
            _index          = 0;
            _firstIteration = true;
            SetData();
        }
        static void Main(string[] args)
        {
            var repo    = new AuthorRepo();
            var authors = repo.GetAuthors();

            //-How many books are collaborations(have more than one author)?
            //-Which book has the most authors(and how many) ?
            //-What author wrote most collaborations ? "

            //-In what year were published most books in a specific genre? Which genre ?
            //-Which author has most books nominated for an award?
            //-Which author has most books that won an award ?
            //-Which author has most books nominated for an award, without winning a single award ?
            //-Make a histogram of books published per decade per genre.
            //- Which author has a highest percentage of nominated books ?
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            UserRepo userRepo = new UserRepo();
            ArticleRepo articleRepo = new ArticleRepo();
            AuthorRepo authorRepo = new AuthorRepo();

            UserValidator userValidator = new UserValidator();
            ArticleValidator articleValidator = new ArticleValidator();
            AuthorValidator authorValidator = new AuthorValidator();

            userRepo.SetValidator(userValidator);
            articleRepo.SetValidator(articleValidator);
            authorRepo.SetValidator(authorValidator);

            Manager manager = new Manager(userRepo, authorRepo, articleRepo);

            ConsoleUI console = new ConsoleUI(manager);
            console.Run();
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            UserRepo    userRepo    = new UserRepo();
            ArticleRepo articleRepo = new ArticleRepo();
            AuthorRepo  authorRepo  = new AuthorRepo();

            UserValidator    userValidator    = new UserValidator();
            ArticleValidator articleValidator = new ArticleValidator();
            AuthorValidator  authorValidator  = new AuthorValidator();

            userRepo.SetValidator(userValidator);
            articleRepo.SetValidator(articleValidator);
            authorRepo.SetValidator(authorValidator);

            Manager manager = new Manager(userRepo, authorRepo, articleRepo);

            ConsoleUI console = new ConsoleUI(manager);

            console.Run();
        }
Esempio n. 17
0
        private void OnTimer(object sender, ElapsedEventArgs args)
        {
            using (var wrapper = new RabbitMQWrapper())
            {
                using (var authorRepo = new AuthorRepo())
                {
                    var authors  = authorRepo.GetALL();
                    var json     = JsonConvert.SerializeObject(authors);
                    var byteData = Encoding.UTF8.GetBytes(json);
                    wrapper.SendMessage(ConfigurationManager.AppSettings["RabbitMQExchange"], "Author", byteData);
                }

                using (var bookRepo = new BookRepo())
                {
                    var books    = bookRepo.GetALL();
                    var json     = JsonConvert.SerializeObject(books);
                    var byteData = Encoding.UTF8.GetBytes(json);
                    wrapper.SendMessage(ConfigurationManager.AppSettings["RabbitMQExchange"], "Book", byteData);
                }
            }
        }
        private MockSetupResult <Author, int> Setup(List <Author> inputDataSource)
        {
            //1.Setup data
            var author = new Author()
            {
                Age       = 123,
                Books     = new List <Book>(),
                FirstName = "Just Mocked First Name",
                Id        = 123,
                LastName  = "Just Mocked Last Name"
            };
            var dataSource = new List <Author>()
            {
                author
            };

            if (inputDataSource != null)
            {
                dataSource = dataSource.Concat(inputDataSource).ToList(); //<-- this will hold data
            }
            //2.Setup Db, reference to MockDbSet in helper for more detail.
            var mockSet     = new MockDbSet <Author, int>(dataSource);
            var mockContext = new Mock <BookstoreContext>();

            mockContext.Setup(c => c.Set <Author>()).Returns(mockSet.Object);

            //3.Setup repo,service,uow
            AuthorRepo        = new AuthorRepo(mockContext.Object);
            AuthorRepo        = new AuthorRepo(mockContext.Object);
            Uow               = new UnitOfWork(mockContext.Object);
            _uowService       = new UnitOfWorkService(Uow);
            _serviceUnderTest = new AuthorService(_mapper, AuthorRepo);
            return(new MockSetupResult <Author, int>
            {
                DataSource = dataSource,
                MockSet = mockSet
            });
        }
 public AuthorService(IMapper mapper)
 {
     _authorRepo = new AuthorRepo(mapper);
     _newsRepo   = new NewsRepo(mapper);
 }
Esempio n. 20
0
 public CreateController()
 {
     _bookRepo   = new BookRepo();
     _authorRepo = new AuthorRepo();
 }
Esempio n. 21
0
 public AuthorService()
 {
     _authorRepo = new AuthorRepo();
 }
        static void Main(string[] args)
        {
            // Console.WriteLine(3.Add(5));


            var source  = new AuthorRepo();
            var authors = source.GetAuthors();

            ////authors.Where(a => a.Name.StartsWith("A"));

            Action <int> printer = x => Console.WriteLine(x);

            Action <int, int> mulPrinter = (x, y) => Console.WriteLine(x * y);

            printer(3);
            printer(2 + 2);
            printer(3.Add(5));
            mulPrinter(3, 5);

            Action line = () => Console.WriteLine("-----------------------------");

            line();

            // DO NOT DO THIS - BAD PRACTICE
            Action <bool, bool, bool, bool> condPrinter = (isActive, isEnabled, isEven, isWeekday) =>
            {
                if (!isActive)
                {
                    Console.WriteLine("Inactive");
                }
                else if (isEnabled)
                {
                    if (isEven && isWeekday)
                    {
                        Console.WriteLine("Something else");
                    }
                    else
                    {
                        Console.WriteLine("Weekend");
                    }
                }
                else
                {
                    Console.WriteLine("Disabled");
                }
            };

            condPrinter(true, false, true, true);

            line();

            Action <string, int> repeat = (text, times) =>
            {
                for (int i = 0; i < times; i++)
                {
                    Console.Write(text);
                }
                Console.WriteLine();
            };

            repeat("weko", 5);

            line();

            Func <int, int, int> add = (x, y) => x + y;
            var z = add(4, 7);

            Console.WriteLine(z);



            Action <IEnumerable <Author> > authorPrinter = (collection) => {
                foreach (var author in collection.Take(3))
                {
                    Console.WriteLine($"{author.Name}");
                }
                line();
            };

            // A - Authors

            Func <Author, bool> nameStartsWithA = author => author.Name.StartsWith("A");

            // var aauthors = Enumerable.Where(authors, nameStartsWithA);
            var aauthors = authors.Where(nameStartsWithA);

            authorPrinter(aauthors);

            // B - Authors

            Func <Author, bool> nameStartsWithB = author => author.Name.StartsWith("B");

            var bauthors = authors.Where(nameStartsWithB);

            authorPrinter(bauthors);

            // C - Authors

            Func <Author, bool> nameStartsWithC = GetNameLambdaForCharacter('C');

            var cauthors = authors.Where(nameStartsWithC);

            authorPrinter(cauthors);

            // D - Authors

            var dauthors = authors.Where(GetNameLambdaForCharacter('D'));

            authorPrinter(dauthors);

            // F - Authors

            // ADVANCED, CAUSES BRAIN HURT
            // Func<char, Func<Author, bool>> nameStartsWith = c => author => author.Name.StartsWith(c);

            int countExec = 0;

            Func <char, Func <Author, bool> > nameStartsWith = c => {
                return(author =>
                {
                    countExec += 1;
                    Console.WriteLine($"I've been called for {author.Name}");
                    return author.Name.StartsWith(c);
                });
            };

            var firstAuthor          = authors.First();
            var isFirstAuthorWithAnF = nameStartsWith('F')(firstAuthor);
            var isFirstAuthorWithAnD = GetNameLambdaForCharacter('D')(firstAuthor);

            line();

            Console.WriteLine("BEFORE WHERE");

            var fauthors = authors.Where(nameStartsWith('C'));

            var fauthorName = fauthors.Select(f => f.Name).ToList();

            Console.WriteLine("AFTER WHERE; BEFORE PRINT");

            authorPrinter(fauthors);

            Console.WriteLine(countExec);

            line();

            // E - Authors
            var startsWithE = GetStartsWithLambda <Author>('E', a => a.Name);
            var eauthors    = authors.Where(startsWithE);

            authorPrinter(eauthors);

            var allBooks = authors.SelectMany(a => a.Books);

            Console.WriteLine(allBooks.Count());

            Action <IEnumerable <Book> > bookPrinter = (collection) => {
                foreach (var book in collection)
                {
                    Console.WriteLine($"{book.Title}");
                }
                line();
            };

            line();

            // A - Books
            var bookStartsWithA = GetStartsWithLambda <Book>('A', b => b.Title);
            var abooks          = allBooks.Where(bookStartsWithA);

            bookPrinter(abooks);

            // Advanced Advanced - Hurts Lecturers Brain

            //var bookStartsWithB = GetStartsWithLambda<Book>('B', b => b.Title);
            //var bookStartsWithC = GetStartsWithLambda<Book>('C', b => b.Title);
            //var bookStartsWithD = GetStartsWithLambda<Book>('D', b => b.Title);
            //var bookStartsWithE = GetStartsWithLambda<Book>('E', b => b.Title);
            //var bookStartsWithF = GetStartsWithLambda<Book>('F', b => b.Title);

            //var bookStartsWithB = GetTitleLambdaForCharacter('B');
            //var bookStartsWithC = GetTitleLambdaForCharacter('C');
            //var bookStartsWithD = GetTitleLambdaForCharacter('D');
            //var bookStartsWithE = GetTitleLambdaForCharacter('E');
            //var bookStartsWithF = GetTitleLambdaForCharacter('F');

            var getTitleLambdaForCharacter = GetStartsWithLambdaGenerator <Book>(b => b.Title);

            var bookStartsWithB = getTitleLambdaForCharacter('B');
            var bookStartsWithC = getTitleLambdaForCharacter('C');
            var bookStartsWithD = getTitleLambdaForCharacter('D');
            var bookStartsWithE = getTitleLambdaForCharacter('E');
            var bookStartsWithF = getTitleLambdaForCharacter('F');

            bookPrinter(allBooks.Where(bookStartsWithF));

            var authorsWithoutBooks = authors.Select(a => new
            {
                a.ID,
                a.Name
            });

            var booksWithAuthorId = authors.SelectMany(a => a.Books.Select(b => new
            {
                b.ID,
                b.Title,
                AuthorID = a.ID
            }));

            var authorBooks = from a in authorsWithoutBooks
                              join b in booksWithAuthorId on a.ID equals b.AuthorID
                              select new
            {
                a.Name,
                b.Title
            };

            // unclear syntax
            //var authorBooks = authorsWithoutBooks.Join(booksWithAuthorId, a => a.ID, b => b.AuthorID, (a, b) => new
            //{
            //    a.Name,
            //    b.Title
            //});

            foreach (var ab in authorBooks)
            {
                Console.WriteLine($"{ab.Name} wrote {ab.Title}");
            }

            Console.WriteLine(authorBooks.Count());
            line();

            // var booksCount = authors.Sum(a => a.Books.Count());

            int accumulator = 0;

            foreach (var author in authors)
            {
                accumulator = accumulator + author.Books.Count();
            }
            Console.WriteLine(accumulator);

            int booksCount = authors.Aggregate(0, (acc, author) => acc + author.Books.Count());

            Console.WriteLine(booksCount);


            // select-many via aggregate
            var aggregateBooks = authors.Aggregate(new List <Book>(), (acc, author) => acc.Concat(author.Books).ToList());

            Console.WriteLine(aggregateBooks.Count);

            // where via aggregate
            // authors.Where(a => a.Name.StartsWith('A'));
            var authorNamesWithA = authors.Aggregate(new List <Author>(), (acc, author) => author.Name.StartsWith('A') ? acc.Append(author).ToList() : acc);

            authorPrinter(authorNamesWithA);

            // implement Select, Any, All, Distinct, SingleOrDefault with Aggregate
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            var repo    = new AuthorRepo();
            var authors = repo.GetAuthors();

            Console.WriteLine($"There are {authors.Count()} total authors");
            Console.WriteLine($"with {authors.SelectMany(a => a.Books).Count()} total books");

            Console.WriteLine("=======================================");
            Console.WriteLine("How many books are collaborations (have more than one author)?");

            var collaborations = authors.SelectMany(book => book.Books)
                                 .GroupBy(id => id.ID)
                                 .Where(dup => dup.Count() > 1)
                                 .Select(bk => bk)
                                 .ToList();

            Console.WriteLine($"{collaborations.Count()} are collaborations");
            Console.WriteLine("=======================================");
            Console.WriteLine("Which book has the most authors (and how many)?");

            var mostAuthors = authors.SelectMany(book => book.Books)
                              .GroupBy(id => id.ID)
                              .OrderBy(x => x.Count())
                              .Select(y => y)
                              .ToList()
                              .LastOrDefault();

            var bookTitle = mostAuthors.Select(x => x.Title)
                            .ToList()
                            .FirstOrDefault();

            var numOfAuthors = mostAuthors.Count();

            Console.WriteLine($"The book {bookTitle} has most  authors.({numOfAuthors})");
            Console.WriteLine("=======================================");
            Console.WriteLine("What author wrote most collaborations?");

            var allBooks = authors.SelectMany(book => book.Books)
                           .ToList();

            var collaborationsIds = collaborations.Select(x => x.Key)
                                    .ToList();

            var listOfColl = allBooks.Where(book => collaborationsIds
                                            .Any(bk => bk == book.ID))
                             .ToList();

            var maxColl = authors.Select(q => q.Books
                                         .Where(w => listOfColl
                                                .Any(r => r.ID == w.ID))
                                         .Count())
                          .Max();

            var authorMax = authors.Where(bk => bk.Books
                                          .Where(x => listOfColl
                                                 .Any(id => id.ID == x.ID))
                                          .Count() == maxColl)
                            .FirstOrDefault();


            Console.WriteLine($"{authorMax.Name} wrote most the collaborations {maxColl}");
            Console.WriteLine("=======================================");
            Console.ReadLine();
        }
 public ValuesController(IConfiguration config, ILogger <ValuesController> log)
 {
     authorRepo = new AuthorRepo(config);
     _log       = log;
 }
Esempio n. 25
0
 public AuthorController()
 {
     _authorRepo = new AuthorRepo();
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            var repo    = new AuthorRepo();
            var authors = repo.GetAuthors();

            //-How many books are collaborations(have more than one author)?

            List <Book> allBooks = authors
                                   .SelectMany(x => x.Books)
                                   .ToList();

            List <IGrouping <int, Book> > colaborationBooks = allBooks
                                                              .GroupBy(x => x.ID)
                                                              .Where(group => group.Count() > 1)
                                                              .Select(el => el)
                                                              .ToList();

            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine($"The number of books that have multiple authors is: '{colaborationBooks.Count}'.");
            Console.WriteLine("----------------------------------------------------------------------");



            //-Which book has the most authors(and how many) ?

            int bookWithMostAuthorsNumberOfAuthors = allBooks
                                                     .GroupBy(x => x.ID)
                                                     .OrderByDescending(g => g.Count())
                                                     .FirstOrDefault()
                                                     .Count();

            int bookWithMostAuthorsID = allBooks
                                        .GroupBy(x => x.ID)
                                        .OrderByDescending(g => g.Count())
                                        .FirstOrDefault()
                                        .Key;

            Book theBookWithMostAuthors = allBooks
                                          .FirstOrDefault(x => x.ID == bookWithMostAuthorsID);

            Console.WriteLine($"The Book with Most Authors is: '{theBookWithMostAuthors.Title}' and has '{bookWithMostAuthorsNumberOfAuthors}' Authors.");
            Console.WriteLine("----------------------------------------------------------------------");


            //-What author wrote most collaborations ? "

            Author authorWithMostBooks = authors
                                         .OrderByDescending(aut => aut.Books
                                                            .Where(x => colaborationBooks
                                                                   .Any(g => g.Key == x.ID))
                                                            .Count())
                                         .FirstOrDefault();


            int numberOfColaborationBookByAuthor = authorWithMostBooks.Books
                                                   .Where(x => colaborationBooks
                                                          .Any(g => g.Key == x.ID))
                                                   .Count();


            Console.WriteLine($"The Author With Most Colaboration Books is: '{authorWithMostBooks.Name}' with total of: '{numberOfColaborationBookByAuthor}' Books");
            Console.WriteLine("----------------------------------------------------------------------");



            //-In what year were published most books in a specific genre? Which genre ?



            //-Which author has most books nominated for an award?

            Author mostNominatedAuthor = authors
                                         .FirstOrDefault(a => a.Books
                                                         .Select(x => x.Nominations)
                                                         .Sum() == authors
                                                         .Select(au => au.Books
                                                                 .Select(a => a.Nominations).Sum())
                                                         .Max());

            int mostBookNominations = mostNominatedAuthor.Books
                                      .Where(b => b.Nominations > 0)
                                      .Count();


            Console.WriteLine($"The Author with Most Book Award Nomination is: '{mostNominatedAuthor.Name} with '{mostBookNominations}' Books ");
            Console.WriteLine("----------------------------------------------------------------------");

            //-Which author has most books that won an award ?

            Author mostAwardedAuthor = authors
                                       .FirstOrDefault(a => a.Books
                                                       .Where(x => x.Wins > 0)
                                                       .Count() == authors
                                                       .Select(au => au.Books
                                                               .Where(a => a.Wins > 0).Count())
                                                       .Max());

            int mostBookWins = mostNominatedAuthor.Books
                               .Where(b => b.Wins > 0)
                               .Count();

            Console.WriteLine($"The Author with Most Awarded Books is: '{mostAwardedAuthor.Name} with '{ mostBookWins}' Wins ");
            Console.WriteLine("----------------------------------------------------------------------");

            //-Which author has most books nominated for an award, without winning a single award ?

            List <Author> authorsWithNoWins = authors
                                              .Where(x => x.Wins == 0)
                                              .ToList();

            Author authorWithMostNominations = authorsWithNoWins
                                               .OrderByDescending(x => x.Nominations)
                                               .FirstOrDefault();

            Console.WriteLine($"The Author that has most books nominated for an award, without winning a single award Books is: '{authorWithMostNominations.Name}' with '{authorWithMostNominations.Nominations}' nominations and '{ authorWithMostNominations.Wins}' Wins.");
            Console.WriteLine("----------------------------------------------------------------------");

            //-Make a histogram of books published per decade per genre.



            //- Which author has a highest percentage of nominated books ?

            //??? OVDE DOBIV  Helene Wecker KAKO REZULTAT, IMA 5 NOMINACII I 1 KNIGA STO BI DOSLO 500% AKO SE BROJAT SITE NOMINACII ILI 100% AKO SE BROI KAKO EDNA NOMINACIJA???



            Author authorWithMostNominationsPercentage = authors
                                                         .OrderByDescending(x => x.Nominations / x.Books.Count * 100)
                                                         .FirstOrDefault();

            int mostNominationsPercentage = authors
                                            .OrderByDescending(x => x.Nominations)
                                            .Count();

            double bookPercent = (authorWithMostNominationsPercentage.Nominations / authorWithMostNominationsPercentage.Books.Count) * 100;

            Console.WriteLine($"Author that has the highest percentage of nominated books is '{authorWithMostNominationsPercentage.Name}' with '{bookPercent}%' . ");
            Console.WriteLine("----------------------------------------------------------------------");
        }
Esempio n. 27
0
 public AuthorController(IWebHostEnvironment hostEnvironment, AuthorRepo authorRepo)
 {
     _authourRepo     = authorRepo;
     _hostEnvironment = hostEnvironment;
 }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var repo    = new AuthorRepo();
            var authors = repo.GetAuthors();

            Console.WriteLine($"There are {authors.Count()} total authors");
            Console.WriteLine($"with {authors.SelectMany(a => a.Books).Count()} total books");

            Console.WriteLine("How many books are collaborations (have more than one author)?");
            var collaborations = authors.SelectMany(a => a.Books).GroupBy(b => b.ID).Where(g => g.Count() > 1);

            Console.WriteLine($"There are {collaborations.Count()} collaborations in the dabatase");
            Console.WriteLine("--------------------");

            Console.WriteLine("Which book has the most authors (and how many)?");
            var mostAuthors = collaborations.Select(g => new
            {
                ID         = g.Key,
                Title      = g.First().Title,
                NumAuthors = g.Count()
            }).OrderByDescending(c => c.NumAuthors).First();

            Console.WriteLine($"The book {mostAuthors.ID}: {mostAuthors.Title} has most authors with {mostAuthors.NumAuthors} different authors");
            Console.WriteLine("--------------------");

            Console.WriteLine("What author wrote most collaborations?");
            var booksWithAuthors = authors.SelectMany(a => a.Books.Select(b => new
            {
                BookID     = b.ID,
                BookTitle  = b.Title,
                AuthorID   = a.ID,
                AuthorName = a.Name
            }));

            var authorCollaborations = booksWithAuthors
                                       .GroupBy(ba => ba.BookID)
                                       .Where(g => g.Count() > 1)
                                       .SelectMany(g => g)
                                       .GroupBy(ba => ba.AuthorID)
                                       .OrderByDescending(g => g.Count())
                                       .First();

            var authorData = authorCollaborations.First();

            Console.WriteLine($"The author with most collaborations is {authorData.AuthorName} with ${authorCollaborations.Count()} collaborations");
            Console.WriteLine("--------------------");


            Console.WriteLine("In what year were published most books in a specific genre? Which genre?");
            var allBooks         = authors.SelectMany(a => a.Books);
            var genres           = Enum.GetValues(typeof(Genre)) as Genre[];
            var mostBooksByGenre = genres.Select(g => new
            {
                Genre = g,
                Books = allBooks.Where(b => b.Genres.Contains(g)).GroupBy(b => b.Year).OrderByDescending(g => g.Count()).First()
            }).OrderByDescending(bg => bg.Books.Count()).First();

            Console.WriteLine($"Most books in a genre were published in {mostBooksByGenre.Genre} in {mostBooksByGenre.Books.Key}, total {mostBooksByGenre.Books.Count()}");
            Console.WriteLine("--------------------");

            Console.WriteLine("Which author has most books nominated for an award?");
            var mostNominatedBooks = authors.OrderByDescending(a => a.Books.Count(b => b.Nominations > 0)).First();

            Console.WriteLine($"The author with most nominated books is {mostNominatedBooks.Name} with {mostNominatedBooks.Books.Count(b => b.Nominations > 0)} nominated books");
            Console.WriteLine("--------------------");

            Console.WriteLine("Which author has most books that won an award?");
            var mostWinningBooks = authors.OrderByDescending(a => a.Books.Count(b => b.Wins > 0)).First();

            Console.WriteLine($"The author with most books that won an award is {mostWinningBooks.Name} with {mostWinningBooks.Books.Count(b => b.Wins > 0)} winners");
            Console.WriteLine("--------------------");

            Console.WriteLine("Which author has most books nominated for an award, without winning a single award?");
            var bestLoser = authors.Where(a => a.Wins == 0).OrderByDescending(a => a.Books.Count(b => b.Nominations > 0)).First();

            Console.WriteLine($"The author with most nominated non-winner books is {bestLoser.Name} with {bestLoser.Books.Count(b => b.Nominations > 0)} nominated books");
            Console.WriteLine("--------------------");

            Console.WriteLine("Make a histogram of books published per decade per genre.");
            var booksByGenreByDecade = genres.Select(g => new
            {
                Genre = g,
                Books = allBooks.Where(b => b.Genres.Contains(g)).GroupBy(b => b.Year / 10 * 10).Select(g => new
                {
                    Decade    = g.Key,
                    Published = g.Count()
                }).OrderBy(db => db.Decade)
            }).ToDictionary(bgd => bgd.Genre, bgd => bgd.Books);

            var decades = booksByGenreByDecade.SelectMany(bgd => bgd.Value.Select(bd => bd.Decade)).Distinct().OrderBy(d => d);

            Console.Write("\t");
            foreach (var genre in genres)
            {
                Console.Write($"\t{genre}");
            }
            Console.WriteLine();

            foreach (var decade in decades)
            {
                Console.Write(decade);
                Console.Write("\t\t");
                foreach (var genre in genres)
                {
                    var genreBooks = booksByGenreByDecade[genre].FirstOrDefault(bd => bd.Decade == decade);
                    if (genreBooks == null)
                    {
                        Console.Write($"\t ");
                    }
                    else
                    {
                        Console.Write($"\t{genreBooks.Published}");
                    }
                }
                Console.WriteLine();
            }

            Console.WriteLine("--------------------");

            Console.WriteLine("Which author has a highest percentage of nominated books?");
            Console.WriteLine("  Tiebreakers: more total books");
            Console.WriteLine("             : more wins");

            var authorBooks = authors.Select(a => new
            {
                AuthorID       = a.ID,
                AuthorName     = a.Name,
                TotalBooks     = a.Books.Count(),
                NominatedBooks = a.Books.Count(b => b.Nominations > 0),
                Wins           = a.Wins
            });

            var highestPercentage = authorBooks
                                    .OrderByDescending(ab => ab.NominatedBooks * 100 / ab.TotalBooks)
                                    .ThenByDescending(ab => ab.TotalBooks)
                                    .ThenByDescending(ab => ab.Wins)
                                    .First();

            Console.WriteLine($"Highest percentage is {highestPercentage.NominatedBooks * 100  / highestPercentage.TotalBooks}%");
            Console.WriteLine($"  for the author {highestPercentage.AuthorName}, ({highestPercentage.AuthorID})");
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            var repo    = new AuthorRepo();
            var authors = repo.GetAuthors();

            Console.WriteLine($"There are {authors.Count()} total authors");
            Thread.Sleep(7000);
            Console.WriteLine($"with {authors.SelectMany(a => a.Books).Count()} total books");

            Console.WriteLine("1) How many books are collaborations (have more than one author)?");

            var booksCollabs = authors
                               .SelectMany(author => author.Books)
                               .GroupBy(book => book.ID)
                               .Where(dupl => dupl.Count() > 1)
                               .ToList();


            Console.WriteLine($"{booksCollabs.Count()} books are collaborations");
            Console.WriteLine("");


            Thread.Sleep(2000);
            Console.WriteLine("2) Which book has the most authors (and how many)?");


            var theAuthors = booksCollabs
                             .OrderByDescending(num => num.Count())
                             .First();

            var mostAuthorsBook = theAuthors.First();

            Console.WriteLine($"The book '{mostAuthorsBook.Title}' has {theAuthors.Count()} authors");
            Console.WriteLine("");

            Thread.Sleep(5000);
            Console.WriteLine("3) What author wrote most collaborations?");



            var collabList = authors
                             .SelectMany(book => book.Books)
                             .Where(book => (booksCollabs.Select(a => a.Key))
                                    .Any(b => b == book.ID))
                             .ToList();

            var collabNum = authors
                            .Select(author => author.Books.Where(books => collabList.Any(book => book.ID == books.ID))
                                    .Count())
                            .Max();

            var mostCollabAuthor = authors
                                   .Where(author => author.Books
                                          .Where(books => collabList.Any(book => book.ID == books.ID)).Count() == collabNum)
                                   .FirstOrDefault();


            Console.WriteLine($"The author {mostCollabAuthor.Name} has {collabNum} collaborations");
            Console.WriteLine("");


            Console.ReadLine();
        }