Example #1
0
        public ActionResult Login(UserLoginViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (UnitOfWork uow = new UnitOfWork())
                    {
                        AuthorRepository ar = new AuthorRepository(uow.Current);
                        Author au = ar.GetAuthorByEmail(model.Email);

                        if (au != null && au.ValidatePassword(model.Password) && au.IsAdministrator)
                        {
                            //Login OK
                            if (FormsAuthentication.IsEnabled && FormsAuthentication.CookiesSupported)
                                FormsAuthentication.SetAuthCookie(model.Email, true);
                            return RedirectToAction("Index", "Manage");
                        }
                        else
                        {
                            model.Message = "Email e/o password errate, oppure non hai i diritti per accedere!";
                            return View(model);
                        }
                    }
                }
                else
                    return View(model);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
Example #2
0
        private static IDictionary<string, int> PrefillAuthors(IList<boeken> books, AuthorRepository authorsRepo, UnitOfWork unitOfWork)
        {
            var allAuthorsInOldDb = books.Select(_ => _.auteurs.Trim()).Distinct().ToList();
            var newAuthors = authorsRepo.All.ToList();
            var result =  new Dictionary<string, int>();
            Console.WriteLine("Found {0} authors in old db", allAuthorsInOldDb.Count());
            foreach(var a in allAuthorsInOldDb)
            {
                var candidate = newAuthors.FirstOrDefault(_ => _.Name.ToLower() == a.ToLower());

                if (candidate == null)
                {
                    candidate = new Author()
                    {
                        State = State.Added,
                        Name = a
                    };

                    authorsRepo.InsertOrUpdate(candidate);                    
                    unitOfWork.Save();
                    newAuthors.Add(candidate);
                }
                result[a.ToLower()] = candidate.Id;                
            }
            

            return result;
        }
Example #3
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (model.RecreateDB)
                    DBHelper.Generate();

                var authorRepository = new AuthorRepository();
                if (authorRepository.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
 public RecipeViewModel()
 {
     _entities = new DbContextFactory().GetFitnessRecipeEntities();
     _authorRepository = new AuthorRepository(_entities);
     _categoryRepository = new CategoryRepository(_entities);
     _mealIngredientRepository = new MealIngredientRepository(_entities);
     _dietRepository = new DietRepository(_entities);
 }
Example #5
0
 public void SendCommentToServer(int? parentMessageId, string comment)
 {
     string userName = Context.User.Identity.Name;
     var authorRepository = new AuthorRepository();
     var author = authorRepository.GetAllFilteredBy(x => x.Login.Equals(userName, StringComparison.InvariantCultureIgnoreCase)).Single();
     var messageRepository = new MessageRepository();
     Message newMessage = messageRepository.AddMessage(parentMessageId, comment, author, messageRepository);
     Clients.addComment(parentMessageId, newMessage.Id, comment, new { Id = author.Id, Name = author.Name, SmallPicturePath = author.SmallPicturePath, MediumPicturePath = author.MediumPicturePath });
 }
Example #6
0
 public UnitOfWork(LuaContext context)
 {
     _context = context;
     Authors = new AuthorRepository(_context);
     Books = new BookRepository(_context);
     Customers = new CustomerRepository(_context);
     Rentals = new RentalRepository(_context);
     Stocks = new StockRepository(_context);
 }
Example #7
0
        private static void Main(string[] args)
        {
            using (var context = new rubenvh_boekenEntities())
            using (var unitOfWork = new UnitOfWork())
            using (var booksRepo = new BooksRepository(unitOfWork))
            using (var categoriesRepo = new CategoryRepository(unitOfWork))
            using (var authorsRepo = new AuthorRepository(unitOfWork))
            {
                Console.WriteLine("Found {0} books.", context.boeken.Count());

                var categories = categoriesRepo.All.ToList();

                var allBooksQuery = context.boeken
                    .Include(_ => _.Readings)
                    .Include(_ => _.GenreLinks)
                    .Include(_ => _.GenreLinks.Select(g => g.Genre));
                var allBooks = allBooksQuery.ToList();

                var authorDictionary = PrefillAuthors(allBooks, authorsRepo, unitOfWork);
                var newBooks = new List<Book>(allBooks.Count);

                foreach (var book in allBooks)
                {
                    Console.WriteLine("Book {0} in {1}: {2}",
                        book.boekID,
                        book.GenreLinks.First().Genre.naam,
                        book.Readings.Any() ? book.Readings.First().datum.ToString() : "not read");

                    newBooks.Add(new Book()
                    {
                        State = State.Added,
                        FirstPublished = book.jaar.HasValue && book.jaar!=0? new DateTime(book.jaar.Value, 1, 1) : default(DateTime?),
                        Isbn = book.isbn,
                        Pages = book.blz ?? 0,
                        Title = book.titel,
                        Authors = new List<Author>() { authorsRepo.Find(authorDictionary[book.auteurs.ToLower()]) },
                        Readings = book.Readings.Select(_ => new Reading()
                                    {
                                        State = State.Added,
                                        PagesRead = book.blz ?? 0,
                                        Date = _.datum
                                    }).ToList(),
                        CategoryId = categories.Single(_ => _.Name == book.GenreLinks.First().Genre.naam).Id,
                        Tags = book.tags
                    });
                }

                newBooks.ForEach(booksRepo.InsertOrUpdateGraph);
                unitOfWork.Save();
            }
           
        }
        public void Should_Delete_An_Entity()
        {
            var repository = new AuthorRepository();
            var author = repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            repository.Delete(author.Id);
            author = repository.GetById(author.Id);
            Assert.IsNull(author);
        }
 public ActionResult Edit(int id)
 {
     var author = new AuthorRepository().GetById(id);
     if (author == null)
         return RedirectToAction("Index");
     return View(new AuthorModel
                     {
                         FirstName = author.FirstName,
                         LastName = author.LastName,
                         Id = author.Id,
                         IsEditMode = true
                     });
 }
Example #10
0
 public ActionResult Index()
 {
     if (!Request.IsAuthenticated)
     {
         return Redirect("/Account/Logon");
     }
     else
     {
         var authorRepository = new AuthorRepository();
         var author = authorRepository.GetAllFilteredBy(x => x.Login.Equals(User.Identity.Name, StringComparison.InvariantCultureIgnoreCase)).Single();
         return View(author);
     }
 }
        public void CreateNewAuthorSuccessfulTest()
        {
            using (UnitOfWork uow = new UnitOfWork())
            {
                AuthorRepository ar = new AuthorRepository(uow.Current);
                BlogRepository br = new BlogRepository(uow.Current);

                br.Save(b);
                Author a = new Author("Pasquale", "Garzillo", Convert.ToDateTime("27/12/1987"), "*****@*****.**", true, "rofox2011", b);

                ar.Save(a);

                uow.Commit();
            }
        }
        public ActionResult Index(AuthorsListSuccessMessage message = AuthorsListSuccessMessage.None)
        {
            var authors = new AuthorRepository().GetAll();
            var model = new AuthorsListModel
                            {
                                Authors = authors.Select(author => new AuthorListItemModel
                                                                       {
                                                                           Id = author.Id,
                                                                           FullName = author.FirstName + " " + author.LastName
                                                                       }).ToList()
                            };
            if (message != AuthorsListSuccessMessage.None)
                model.SuccessMessage = message.GetDescriptionAttributeValue();

            return View(model);
        }
        public void Should_Find_An_Entity()
        {
            var repository = new AuthorRepository();
            repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            repository.Insert(new Author()
            {
                FirstName = "Dick",
                LastName = "Grayson"
            });

            Assert.IsTrue(repository.Any(author => author.FirstName == "Dick" && author.LastName == "Grayson"));
        }
Example #14
0
        public ActionResult Index(SetupViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Model.Domain.Entities.Blog b = new Model.Domain.Entities.Blog(model.Blog,
                        model.Descrizione);

                    Author au = new Author(model.Nome,
                        model.Cognome,
                        model.Nascita,
                        model.Email,
                        true,
                        model.Password,
                        b);

                    Category cc = new Category("Nessuna categoria", "Categoria generica");

                    using (UnitOfWork uow = new UnitOfWork())
                    {
                        BlogRepository br = new BlogRepository(uow.Current);
                        AuthorRepository ar = new AuthorRepository(uow.Current);
                        CategoryRepository cr = new CategoryRepository(uow.Current);

                        br.Save(b);
                        ar.Save(au);
                        cr.Save(cc);

                        uow.Commit();
                    }
                    //Vai alla pagina di gestione
                    return RedirectToAction("Index", "Manage");
                }
                else
                    return View(model);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        public void Should_Add_An_Entity()
        {
            var repository = new AuthorRepository();
            var author = repository.Insert(new Author()
                                  {
                                      FirstName = "Bruce",
                                      LastName = "Wayne"
                                  });

            Assert.IsTrue(author.Id > 0);
            Assert.AreEqual("Bruce", author.FirstName);
            Assert.AreEqual("Wayne", author.LastName);

            var authorId = author.Id;

            author = repository.GetById(authorId);
            Assert.AreEqual(authorId, author.Id);
            Assert.AreEqual("Bruce", author.FirstName);
            Assert.AreEqual("Wayne", author.LastName);
        }
        public void Should_Map_A_Books_List_To_Its_Model()
        {
            var repository = new AuthorRepository();
            var bruce = repository.Insert(new Author
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });
            var author = repository.Insert(new Author
            {
                FirstName = "Cormac",
                LastName = "McCarthy"
            });

            var model = Mapper.Map<IEnumerable<Book>, BooksListModel>(new List<Book>
            {
                new Book(repository)
                    {
                        Id = 5,
                        Title = "The Road",
                        ISBN = "1234567891234",
                        AuthorId = author.Id
                    },
                 new Book(repository)
                    {
                        Id = 6,
                        Title = "The Bat",
                        ISBN = "2345678912345",
                        AuthorId = bruce.Id
                    }
            });
            Assert.AreEqual(2, model.Books.Count);
            Assert.AreEqual(5, model.Books[0].Id);
            Assert.AreEqual("The Road", model.Books[0].Title);
            Assert.AreEqual("1234567891234", model.Books[0].ISBN);
            Assert.AreEqual("Cormac McCarthy", model.Books[0].AuthorFullName);
            Assert.AreEqual(6, model.Books[1].Id);
            Assert.AreEqual("The Bat", model.Books[1].Title);
            Assert.AreEqual("2345678912345", model.Books[1].ISBN);
            Assert.AreEqual("Bruce Wayne", model.Books[1].AuthorFullName);
        }
        public void Changing_An_Entity_Retrieved_By_The_Repository_Should_Not_Change_The_Stored_List()
        {
            var repository = new AuthorRepository();
            var author = repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            var authorId = author.Id;

            author = repository.GetById(authorId);

            author.FirstName = "Dick";
            author.LastName = "Grayson";

            var authorStored = repository.GetById(authorId);
            Assert.AreEqual(authorId, authorStored.Id);
            Assert.AreEqual("Bruce", authorStored.FirstName);
            Assert.AreEqual("Wayne", authorStored.LastName);
        }
Example #18
0
        public ActionResult AccountManagment()
        {
            try
            {
                UserViewModel uvm = new UserViewModel();
                if (FormsAuthentication.IsEnabled && FormsAuthentication.CookiesSupported && Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    if (!String.IsNullOrEmpty(username))
                    {
                        using (UnitOfWork uow = new UnitOfWork())
                        {
                            AuthorRepository ar = new AuthorRepository(uow.Current);
                            Author au = ar.GetAuthorByEmail(username);

                            if (au != null)
                            {
                                uvm.Cognome = au.Surname;
                                uvm.Email = au.Email;
                                uvm.Nascita = au.BirthDate.Value;
                                uvm.Nome = au.Name;
                                uvm.Password = au.Password;
                            }
                            else
                                uvm.Message = "Si è verificato un problema durante il caricamento dati.";
                        }
                    }
                    else
                        uvm.Message = "Si è verificato un problema durante il caricamento dati.";

                    return View(uvm);
                }
                else
                {
                    uvm.Message = "Sessione utente probabilmente scaduta! Riprova a fare il login e assicurati di avere i cookie abilitati!";
                    return View(uvm);
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
            
        }
Example #19
0
        public ActionResult PageDetail(int id)
        {
            try
            {
                PageViewModel pvm = new PageViewModel();
                using (UnitOfWork uow = new UnitOfWork())
                {
                    PageRepository pr = new PageRepository(uow.Current);
                    AuthorRepository ar = new AuthorRepository(uow.Current);
                    BlogRepository br = new BlogRepository(uow.Current);
                    CategoryRepository cr = new CategoryRepository(uow.Current);

                    Page p = pr.GetById(id);
                    if (p != null)
                    {
                        IList<Author> tmpAuthors = ar.FindAll().ToList();
                        if (tmpAuthors != null && tmpAuthors.Count > 0)
                        {
                            IEnumerable<SelectListItem> tmpAuthorsItems;

                            tmpAuthorsItems =   from s in tmpAuthors
                                                select new SelectListItem
                                                {
                                                    Text = s.NameAndSurname,
                                                    Value = s.Id.ToString()
                                                };

                            pvm.Authors = tmpAuthorsItems;
                            pvm.SelectedAuthor = p.Author.Id.ToString();
                        }
                        IList<Blog.Model.Domain.Entities.Blog> tmpBlogs = br.FindAll().ToList();
                        if (tmpBlogs != null && tmpBlogs.Count > 0)
                        {
                            IEnumerable<SelectListItem> tmpBlogsItems;

                            tmpBlogsItems = from b in tmpBlogs
                                              select new SelectListItem
                                              {
                                                  Text = b.Name,
                                                  Value = b.Id.ToString()
                                              };

                            pvm.Blogs = tmpBlogsItems;
                            pvm.SelectedBlog = p.Blog.Id.ToString();
                        }
                        IList<Category> tmpCategories = cr.FindAll().ToList();
                        if (tmpCategories != null && tmpCategories.Count > 0)
                        {
                            IEnumerable<SelectListItem> tmpCategoriesItems;

                            tmpCategoriesItems = from b in tmpCategories
                                            select new SelectListItem
                                            {
                                                Text = b.Name,
                                                Value = b.Id.ToString()
                                            };

                            pvm.Categories = tmpCategoriesItems;
                            pvm.SelectedCategory = p.Category.Id.ToString();
                        }

                        pvm.Data = p.Date.Value;
                        pvm.Id = p.Id;
                        pvm.Titolo = p.Title;
                        pvm.Descrizione = p.Description;
                        pvm.FileName = p.ImageName;
                        pvm.Body = p.BodyText;

                        if (p.Tags != null && p.Tags.Count > 0)
                            pvm.Tags = String.Join(", ", p.Tags.Select(x=>x.Name));
                    }
                }
                return View(pvm);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
Example #20
0
        public ActionResult AccountManagment(UserViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (FormsAuthentication.IsEnabled && FormsAuthentication.CookiesSupported)
                    {
                        string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                        if (!String.IsNullOrEmpty(username))
                        {
                            using (UnitOfWork uow = new UnitOfWork())
                            {

                                AuthorRepository ar = new AuthorRepository(uow.Current);
                                Author au = ar.GetAuthorByEmail(username);

                                au.ModifyAuthor(model.Nome, model.Cognome, model.Nascita, model.Email);

                                ar.SaveOrUpdate(au);

                                uow.Commit();

                                model.Message = "Modifica dei dati eseguita con successo!";
                            }
                        }
                        else
                            model.Message = "Si è verificato un problema durante il recupero dei dati. Non è stato possibile apportare le modifiche richieste!";
                    }
                    return View(model);
                }
                else
                    return View(model);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
 public AuthorController(IConfiguration configuration)
 {
     authorRepository = new AuthorRepository(configuration);
 }
        public void GetAuthors_PageSizeIsThree_ReturnsThreeAuthors()
        {
            // Arrange

            var connectionStringBuilder =
                new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(connectionStringBuilder.ToString());

            var options = new DbContextOptionsBuilder <CourseContext>()
                          .UseSqlite(connection)
                          .Options;


            using (var context = new CourseContext(options))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();
                context.Countries.Add(new Entities.Country()
                {
                    Id          = "BE",
                    Description = "Belgium"
                });

                context.Countries.Add(new Entities.Country()
                {
                    Id          = "US",
                    Description = "United States of America"
                });

                context.Authors.Add(new Entities.Author()
                {
                    FirstName = "Kevin", LastName = "Dockx", CountryId = "BE"
                });
                context.Authors.Add(new Entities.Author()
                {
                    FirstName = "Gill", LastName = "Cleeren", CountryId = "BE"
                });
                context.Authors.Add(new Entities.Author()
                {
                    FirstName = "Julie", LastName = "Lerman", CountryId = "US"
                });
                context.Authors.Add(new Entities.Author()
                {
                    FirstName = "Shawn", LastName = "Wildermuth", CountryId = "BE"
                });
                context.Authors.Add(new Entities.Author()
                {
                    FirstName = "Deborah", LastName = "Kurata", CountryId = "US"
                });

                context.SaveChanges();
            }

            using (var context = new CourseContext(options))
            {
                var authorRepository = new AuthorRepository(context);

                // Act
                var authors = authorRepository.GetAuthors(1, 3);

                // Assert
                Assert.Equal(3, authors.Count());
            }
        }
        public void Should_Map_A_Model_To_A_Book()
        {
            var repository = new AuthorRepository();
            var author = repository.Insert(new Author
            {
                FirstName = "Cormac",
                LastName = "McCarthy"
            });

            var book = new BookRepository(repository).CreateNew();

            book = Mapper.Map<BookModel, Book>(new BookModel
            {
                Id = 5,
                Title = "The Road",
                ISBN = "1234567891234",
                AuthorId = author.Id,
                IsEditMode = false
            }, book);

            Assert.AreEqual(5, book.Id);
            Assert.AreEqual("The Road", book.Title);
            Assert.AreEqual("1234567891234", book.ISBN);
            Assert.AreEqual(author.Id, book.AuthorId);
        }
Example #24
0
 public ArticlesService(string ConnectionString)
 {
     _articleRepository = new ArticleRepository(ConnectionString);
     _authorRepository  = new AuthorRepository(ConnectionString);
 }
Example #25
0
 public void UpdateList()
 {
     _authorRepository = new AuthorRepository();
     AuthorsListBox.Items.Clear();
     _authorRepository.GetAllAuthors().ForEach(book => AuthorsListBox.Items.Add(book));
 }
Example #26
0
 public UnitOfWork(SampleAppContext context)
 {
     _context = context;
     Courses  = new CourseRepository(_context);
     Authors  = new AuthorRepository(_context);
 }
Example #27
0
        public void AddAuthor_AuthorWithoutCountryId_AuthorHasBEAsCountryId()
        {
            // Arrange
            //var logs = new List<string>();

            // we commented this line because we are going to use Sqlite instead of ImMemory Provider
            // var options = new DbContextOptionsBuilder<CourseContext>().UseInMemoryDatabase($"CourseDatabaseForTesting {Guid.NewGuid()}").Options;
            var connectionStringBuilder = new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(connectionStringBuilder.ToString());
            var options    = new DbContextOptionsBuilder <CourseContext>().UseLoggerFactory(new LoggerFactory(
                                                                                                new[] { new LogToActionLoggerProvider((log) => {
                    //logs.Add(log);
                    //Debug.WriteLine(log);
                    // this will makes you see the actual SQL Server Queries that has been executed
                    _output.WriteLine(log);
                }) }
                                                                                                )).UseSqlite(connection).Options;

            using (var context = new CourseContext(options))
            {
                // note that we opened only the connection for one time, and we did not open it again in the other opened context.
                // this is because the connection is reused across our contexts, so it remains open untill it goes out of the scope, which means untill the test is done
                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                // note that below add is not required when you are using "InMemory Provider" because in this provider it doesnot depend on relational features,
                // but if you are using Sql Lite, below line should exist because it acts as foreign key for Author Table, so it will throws exception if below line is missing.
                context.Countries.Add(new Entities.Country()
                {
                    Id          = "BE",
                    Description = "Belgium"
                });

                context.SaveChanges();
            }

            using (var context = new CourseContext(options))
            {
                var authorRepo = new AuthorRepository(context);

                var authorToAdd = new Author()
                {
                    FirstName = "Kevin",
                    LastName  = "Dockx",
                    Id        = Guid.Parse("d84d3d7e-3fbc-4956-84a5-5c57c2d86d7b")
                };

                authorRepo.AddAuthor(authorToAdd);
                authorRepo.SaveChanges();
            }

            using (var context = new CourseContext(options))
            {
                var authorRepo = new AuthorRepository(context);

                var addedAuthor = authorRepo.GetAuthor(Guid.Parse("d84d3d7e-3fbc-4956-84a5-5c57c2d86d7b"));

                Assert.Equal("BE", addedAuthor.CountryId);
            }
        }
        public string get()
        {
            using (var ctx = new libraryContext())
            {
                var AuthorRepo    = new AuthorRepository(ctx);
                var PublisherRepo = new PublisherRepository(ctx);
                var BooksRepo     = new BooksRepository(ctx);
                try
                {
                    var authorFile = @"E:\OneDrive - The University of Texas at Dallas\Spring18\DB\Projects\project1\books.csv";
                    //var borrowerFile = "";
                    List <Model>     list       = new List <Model>();
                    var              fileStream = new FileStream(authorFile, FileMode.Open, FileAccess.Read);
                    HashSet <string> authors    = new HashSet <string>();
                    HashSet <string> publishers = new HashSet <string>();
                    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                    {
                        string line;
                        line = streamReader.ReadLine();
                        while ((line = streamReader.ReadLine()) != null)
                        {
                            var temp = line.Split('\t');
                            foreach (var author in temp[3].Split(','))
                            {
                                authors.Add(author);
                            }

                            publishers.Add(temp[5]);

                            int pages = Int16.Parse(temp[6]);
                            var model = new Model(temp[0], temp[2], temp[3].Split(','), temp[4], temp[5], pages);
                            list.Add(model);
                            //BooksRepo.Add(temp[0], temp[2], temp[5], Int16.Parse(temp[6]), temp[4], temp[3].Split(','));
                            //ctx.SaveChanges();
                        }
                    }
                    foreach (var author in authors)
                    {
                        AuthorRepo.Add(author);
                    }
                    foreach (var publisher in publishers)
                    {
                        PublisherRepo.Add(publisher);
                    }
                    ctx.SaveChanges();
                    var count = 0;
                    foreach (var item in list)
                    {
                        count++;
                        BooksRepo.Add(item.isbn, item.title, item.cover, item.pages, item.publisher, item.authors);
                        if (count % 5000 == 0)
                        {
                            Console.Write(ctx.SaveChanges());
                        }
                    }
                    ctx.SaveChanges();
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
                return("Success");
            }
        }
Example #29
0
 public UnitOfWork(CustomContext context)
 {
     _context = context;
     Courses  = new CourseRepository(_context);
     Authors  = new AuthorRepository(_context);
 }
Example #30
0
 public UserController(SubscriberRepository subscriberRepository,
                       AuthorRepository authorRepository)
 {
     this.authorRepository     = authorRepository;
     this.subscriberRepository = subscriberRepository;
 }
Example #31
0
 public NoteRepositoryTests()
 {
     SetupTestingEnv();
     _author  = AuthorRepository.GetEntities().FirstOrDefault();
     _catalog = CatalogRepository.GetEntities().FirstOrDefault(cat => cat.IsDefault);
 }
 public void FindTest()
 {
     var repository = new AuthorRepository();
     repository.Find(1);
 }
Example #33
0
        public static void Map()
        {
            RegisterMappers();

            Mapper.Entity <Config>("Config").RegisterModel();

            Mapper.Entity <RootFolder>("RootFolders").RegisterModel()
            .Ignore(r => r.Accessible)
            .Ignore(r => r.FreeSpace)
            .Ignore(r => r.TotalSpace);

            Mapper.Entity <ScheduledTask>("ScheduledTasks").RegisterModel();

            Mapper.Entity <IndexerDefinition>("Indexers").RegisterModel()
            .Ignore(x => x.ImplementationName)
            .Ignore(i => i.Enable)
            .Ignore(i => i.Protocol)
            .Ignore(i => i.SupportsRss)
            .Ignore(i => i.SupportsSearch)
            .Ignore(d => d.Tags);

            Mapper.Entity <ImportListDefinition>("ImportLists").RegisterModel()
            .Ignore(x => x.ImplementationName)
            .Ignore(i => i.Enable)
            .Ignore(i => i.ListType);

            Mapper.Entity <NotificationDefinition>("Notifications").RegisterModel()
            .Ignore(x => x.ImplementationName)
            .Ignore(i => i.SupportsOnGrab)
            .Ignore(i => i.SupportsOnReleaseImport)
            .Ignore(i => i.SupportsOnUpgrade)
            .Ignore(i => i.SupportsOnRename)
            .Ignore(i => i.SupportsOnAuthorDelete)
            .Ignore(i => i.SupportsOnBookDelete)
            .Ignore(i => i.SupportsOnBookFileDelete)
            .Ignore(i => i.SupportsOnBookFileDeleteForUpgrade)
            .Ignore(i => i.SupportsOnHealthIssue)
            .Ignore(i => i.SupportsOnDownloadFailure)
            .Ignore(i => i.SupportsOnImportFailure)
            .Ignore(i => i.SupportsOnBookRetag);

            Mapper.Entity <MetadataDefinition>("Metadata").RegisterModel()
            .Ignore(x => x.ImplementationName)
            .Ignore(d => d.Tags);

            Mapper.Entity <DownloadClientDefinition>("DownloadClients").RegisterModel()
            .Ignore(x => x.ImplementationName)
            .Ignore(d => d.Protocol)
            .Ignore(d => d.Tags);

            Mapper.Entity <EntityHistory>("History").RegisterModel();

            Mapper.Entity <Author>("Authors")
            .Ignore(s => s.RootFolderPath)
            .Ignore(s => s.Name)
            .Ignore(s => s.ForeignAuthorId)
            .HasOne(a => a.Metadata, a => a.AuthorMetadataId)
            .HasOne(a => a.QualityProfile, a => a.QualityProfileId)
            .HasOne(s => s.MetadataProfile, s => s.MetadataProfileId)
            .LazyLoad(a => a.Books, (db, a) => db.Query <Book>(new SqlBuilder().Where <Book>(b => b.AuthorMetadataId == a.AuthorMetadataId)).ToList(), a => a.AuthorMetadataId > 0);

            Mapper.Entity <Series>("Series").RegisterModel()
            .Ignore(s => s.ForeignAuthorId)
            .LazyLoad(s => s.LinkItems,
                      (db, series) => db.Query <SeriesBookLink>(new SqlBuilder().Where <SeriesBookLink>(s => s.SeriesId == series.Id)).ToList(),
                      s => s.Id > 0)
            .LazyLoad(s => s.Books,
                      (db, series) => db.Query <Book>(new SqlBuilder()
                                                      .Join <Book, SeriesBookLink>((l, r) => l.Id == r.BookId)
                                                      .Join <SeriesBookLink, Series>((l, r) => l.SeriesId == r.Id)
                                                      .Where <Series>(s => s.Id == series.Id)).ToList(),
                      s => s.Id > 0);

            Mapper.Entity <SeriesBookLink>("SeriesBookLink").RegisterModel()
            .HasOne(l => l.Book, l => l.BookId)
            .HasOne(l => l.Series, l => l.SeriesId);

            Mapper.Entity <AuthorMetadata>("AuthorMetadata").RegisterModel();

            Mapper.Entity <Book>("Books").RegisterModel()
            .Ignore(x => x.AuthorId)
            .HasOne(r => r.AuthorMetadata, r => r.AuthorMetadataId)
            .LazyLoad(x => x.BookFiles,
                      (db, book) => db.Query <BookFile>(new SqlBuilder()
                                                        .Join <BookFile, Edition>((l, r) => l.EditionId == r.Id)
                                                        .Where <Edition>(b => b.BookId == book.Id)).ToList(),
                      b => b.Id > 0)
            .LazyLoad(x => x.Editions,
                      (db, book) => db.Query <Edition>(new SqlBuilder().Where <Edition>(e => e.BookId == book.Id)).ToList(),
                      b => b.Id > 0)
            .LazyLoad(a => a.Author,
                      (db, book) => AuthorRepository.Query(db,
                                                           new SqlBuilder()
                                                           .Join <Author, AuthorMetadata>((a, m) => a.AuthorMetadataId == m.Id)
                                                           .Where <Author>(a => a.AuthorMetadataId == book.AuthorMetadataId)).SingleOrDefault(),
                      a => a.AuthorMetadataId > 0)
            .LazyLoad(b => b.SeriesLinks,
                      (db, book) => db.Query <SeriesBookLink>(new SqlBuilder().Where <SeriesBookLink>(s => s.BookId == book.Id)).ToList(),
                      b => b.Id > 0);

            Mapper.Entity <Edition>("Editions").RegisterModel()
            .HasOne(r => r.Book, r => r.BookId)
            .LazyLoad(x => x.BookFiles,
                      (db, edition) => db.Query <BookFile>(new SqlBuilder().Where <BookFile>(f => f.EditionId == edition.Id)).ToList(),
                      b => b.Id > 0);

            Mapper.Entity <BookFile>("BookFiles").RegisterModel()
            .Ignore(x => x.PartCount)
            .HasOne(f => f.Edition, f => f.EditionId)
            .LazyLoad(x => x.Author,
                      (db, f) => AuthorRepository.Query(db,
                                                        new SqlBuilder()
                                                        .Join <Author, AuthorMetadata>((a, m) => a.AuthorMetadataId == m.Id)
                                                        .Join <Author, Book>((l, r) => l.AuthorMetadataId == r.AuthorMetadataId)
                                                        .Join <Book, Edition>((l, r) => l.Id == r.BookId)
                                                        .Where <Edition>(a => a.Id == f.EditionId)).SingleOrDefault(),
                      t => t.Id > 0);

            Mapper.Entity <QualityDefinition>("QualityDefinitions").RegisterModel()
            .Ignore(d => d.GroupName)
            .Ignore(d => d.GroupWeight)
            .Ignore(d => d.Weight);

            Mapper.Entity <QualityProfile>("QualityProfiles").RegisterModel();
            Mapper.Entity <MetadataProfile>("MetadataProfiles").RegisterModel();
            Mapper.Entity <Log>("Logs").RegisterModel();
            Mapper.Entity <NamingConfig>("NamingConfig").RegisterModel();

            Mapper.Entity <Blocklist>("Blocklist").RegisterModel();
            Mapper.Entity <MetadataFile>("MetadataFiles").RegisterModel();
            Mapper.Entity <OtherExtraFile>("ExtraFiles").RegisterModel();

            Mapper.Entity <PendingRelease>("PendingReleases").RegisterModel()
            .Ignore(e => e.RemoteBook);

            Mapper.Entity <RemotePathMapping>("RemotePathMappings").RegisterModel();
            Mapper.Entity <Tag>("Tags").RegisterModel();
            Mapper.Entity <ReleaseProfile>("ReleaseProfiles").RegisterModel();

            Mapper.Entity <DelayProfile>("DelayProfiles").RegisterModel();
            Mapper.Entity <User>("Users").RegisterModel();
            Mapper.Entity <CommandModel>("Commands").RegisterModel()
            .Ignore(c => c.Message);

            Mapper.Entity <IndexerStatus>("IndexerStatus").RegisterModel();
            Mapper.Entity <DownloadClientStatus>("DownloadClientStatus").RegisterModel();
            Mapper.Entity <ImportListStatus>("ImportListStatus").RegisterModel();

            Mapper.Entity <CustomFilter>("CustomFilters").RegisterModel();
            Mapper.Entity <ImportListExclusion>("ImportListExclusions").RegisterModel();

            Mapper.Entity <CachedHttpResponse>("HttpResponse").RegisterModel();

            Mapper.Entity <DownloadHistory>("DownloadHistory").RegisterModel();
        }
 // Dependency Injection
 public AuthorController(IHostingEnvironment environment,
                         IConfiguration configuration, AuthorRepository repository)
 {
     this.Repository = repository;
 }
 public UnitOfWork(PlutoContext context)
 {
     _context = context;
     Courses = new CourseRepository(_context);
     Authors = new AuthorRepository(_context);
 }
 public AuthorsController(AuthorRepository authorRepository)
 {
     _authorRepository = authorRepository;
 }
Example #37
0
        //// GET api/authors
        //public IEnumerable<Author> Get()
        //{
        //    var repo = new AuthorRepository();

        //    return repo.GetAuthors();
        //}

        // GET api/authors
        public Task <IEnumerable <Author> > Get()
        {
            var repo = new AuthorRepository();

            return(Task.Factory.FromAsync <IEnumerable <Author> >(repo.BeginGetAuthors, repo.EndGetAuthors, null));
        }
Example #38
0
 public AuthorService(AuthorRepository authorRepository)
 {
     _authorRepository = authorRepository;
 }
 public AuthorsController()
 {
     repository = new Quality.Test.repositories.AuthorRepository();
 }
Example #40
0
 public NewsItemService(IMapper mapper)
 {
     _newsItemRepository = new NewsItemRepository(mapper);
     _authorRepository   = new AuthorRepository(mapper);
     _categoryRepository = new CategoryRepository(mapper);
 }
Example #41
0
 public AddAuthorForm()
 {
     _authorRepository = new AuthorRepository();
     InitializeComponent();
 }
Example #42
0
 public void Delete()
 {
     AuthorRepository.DeleteUnused();
 }
Example #43
0
 public AuthorProcessor(AuthorRepository authorRepository, XsltTransformationManager xsltTransformationManager,
                        IKernel container)
     : base(xsltTransformationManager, container)
 {
     m_authorRepository = authorRepository;
 }
Example #44
0
 public UnitOfWork(PlutoContext context)
 {
     _context = context;
     Courses  = new CourseRepository(context);
     Authors  = new AuthorRepository(context);
 }
Example #45
0
        public ActionResult PageNew(PageViewModel model) 
        {
            try
            {
                //Carica tutti gli elementi necessari a video
                using (UnitOfWork uow = new UnitOfWork())
                {
                    AuthorRepository ar = new AuthorRepository(uow.Current);
                    BlogRepository br = new BlogRepository(uow.Current);
                    CategoryRepository cr = new CategoryRepository(uow.Current);

                    //Ricarica la lista autori
                    IList<Author> tmpAuthors = ar.FindAll().ToList();
                    if (tmpAuthors != null && tmpAuthors.Count > 0)
                    {
                        IEnumerable<SelectListItem> tmpAuthorsItems;

                        tmpAuthorsItems = from s in tmpAuthors
                                          select new SelectListItem
                                          {
                                              Text = s.NameAndSurname,
                                              Value = s.Id.ToString()
                                          };

                        model.Authors = tmpAuthorsItems;
                    }

                    IList<Blog.Model.Domain.Entities.Blog> tmpBlogs = br.FindAll().ToList();
                    if (tmpBlogs != null && tmpBlogs.Count > 0)
                    {
                        IEnumerable<SelectListItem> tmpBlogsItems;

                        tmpBlogsItems = from b in tmpBlogs
                                        select new SelectListItem
                                        {
                                            Text = b.Name,
                                            Value = b.Id.ToString()
                                        };

                        model.Blogs = tmpBlogsItems;
                    }

                    IList<Category> tmpCategories = cr.FindAll().ToList();
                    if (tmpCategories != null && tmpCategories.Count > 0)
                    {
                        IEnumerable<SelectListItem> tmpCategoriesItems;

                        tmpCategoriesItems = from b in tmpCategories
                                             select new SelectListItem
                                             {
                                                 Text = b.Name,
                                                 Value = b.Id.ToString()
                                             };

                        model.Categories = tmpCategoriesItems;
                    }
                }

                if (ModelState.IsValid)
                {
                    using (UnitOfWork uow = new UnitOfWork())
                    {
                        string fileName = null;
                        if (model.File != null && model.File.ContentLength > 0)
                        {
                            //SALVA IL FILE
                            fileName = Path.GetFileName(model.File.FileName);
                            var path = Path.Combine(Server.MapPath("/Uploads"), fileName);
                            model.File.SaveAs(path);
                            model.FileName = fileName;
                        }

                        model.SelectedAuthor = model.SelectedAuthor;
                        model.SelectedBlog = model.SelectedBlog;
                        model.SelectedCategory = model.SelectedCategory;

                        PageRepository pr = new PageRepository(uow.Current);
                        AuthorRepository ar = new AuthorRepository(uow.Current);
                        BlogRepository br = new BlogRepository(uow.Current);
                        CategoryRepository cr = new CategoryRepository(uow.Current);
                        TagRepository tr = new TagRepository(uow.Current);

                        Author au = ar.GetById(Convert.ToInt32(model.SelectedAuthor));
                        Blog.Model.Domain.Entities.Blog bb = br.GetById(Convert.ToInt32(model.SelectedBlog));
                        Category cc = cr.GetById(Convert.ToInt32(model.SelectedCategory));

                        Page p = new Page(model.Titolo, model.Descrizione, model.Data, model.Body, au, bb, cc);

                        if (!String.IsNullOrEmpty(model.Tags))
                        {
                            foreach(var t in model.Tags.Split(','))
                            {
                                if (!String.IsNullOrEmpty(t))
                                {
                                    Tag tg = tr.GetTagByName(t.TrimStart().TrimEnd());
                                    if (tg != null)
                                    {
                                        p.AddTag(tg);
                                    }
                                    else
                                    {
                                        Tag tempTag = new Tag(t.TrimStart().TrimEnd());
                                        p.AddTag(tempTag);
                                    }
                                }
                            }
                        }

                        if (!String.IsNullOrEmpty(fileName))
                            p.SetImagePath(fileName);
                        else
                            model.FileName = p.ImageName;

                        pr.SaveOrUpdate(p);
                        uow.Commit();

                        model.Message = "Salvataggio eseguito con successo!";
                    }
                }
                return View(model);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        public void Should_Save_An_Entity()
        {
            var repository = new AuthorRepository();
            var author = repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            author.FirstName = "Dick";
            author.LastName = "Grayson";

            repository.Save(author);

            var authorId = author.Id;
            author = repository.GetById(authorId);

            Assert.AreEqual(authorId, author.Id);
            Assert.AreEqual("Dick", author.FirstName);
            Assert.AreEqual("Grayson", author.LastName);
        }
Example #47
0
        public ActionResult PageNew()
        {
            try
            {
                PageViewModel pvm = new PageViewModel();
                using (UnitOfWork uow = new UnitOfWork())
                {
                    AuthorRepository ar = new AuthorRepository(uow.Current);
                    BlogRepository br = new BlogRepository(uow.Current);
                    CategoryRepository cr = new CategoryRepository(uow.Current);

                    //Ricarica la lista autori
                    IList<Author> tmpAuthors = ar.FindAll().ToList();
                    if (tmpAuthors != null && tmpAuthors.Count > 0)
                    {
                        IEnumerable<SelectListItem> tmpAuthorsItems;

                        tmpAuthorsItems = from s in tmpAuthors
                                          select new SelectListItem
                                          {
                                              Text = s.NameAndSurname,
                                              Value = s.Id.ToString()
                                          };

                        pvm.Authors = tmpAuthorsItems;

                    }

                    IList<Blog.Model.Domain.Entities.Blog> tmpBlogs = br.FindAll().ToList();
                    if (tmpBlogs != null && tmpBlogs.Count > 0)
                    {
                        IEnumerable<SelectListItem> tmpBlogsItems;

                        tmpBlogsItems = from b in tmpBlogs
                                        select new SelectListItem
                                        {
                                            Text = b.Name,
                                            Value = b.Id.ToString()
                                        };

                        pvm.Blogs = tmpBlogsItems;
                    }

                    IList<Category> tmpCategories = cr.FindAll().ToList();
                    if (tmpCategories != null && tmpCategories.Count > 0)
                    {
                        IEnumerable<SelectListItem> tmpCategoriesItems;

                        tmpCategoriesItems = from b in tmpCategories
                                             select new SelectListItem
                                             {
                                                 Text = b.Name,
                                                 Value = b.Id.ToString()
                                             };

                        pvm.Categories = tmpCategoriesItems;
                    }

                    pvm.Data = DateTime.Today.Date;
                }
                return View(pvm);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        public void Should_Search_An_Entity()
        {
            var repository = new AuthorRepository();
            repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            var authorToFind = repository.Insert(new Author()
            {
                FirstName = "Dick",
                LastName = "Grayson"
            });

            var authorsFound = repository.SearchFor(author => author.FirstName == "Dick" && author.LastName == "Grayson");

            Assert.AreEqual(1, authorsFound.Count());
            Assert.AreEqual(authorToFind.Id, authorsFound.First().Id);
        }
 public AuthorService()
 {
     _authorRepository = new AuthorRepository();
 }
Example #50
0
 public List <Author> List()
 {
     return(AuthorRepository.GetAll());
 }
Example #51
0
 public AuthorDTO GetAuthorById(Int32 id)
 {
     return(AuthorRepository.SelectById(id, a => new AuthorDTO {
         FullName = a.FirstName, Tagline = a.Tagline, Bio = a.Bio
     }));
 }
 public UnitOfWork(PlutoContext ctx)
 {
     _ctx    = ctx;
     Courses = new CourseRepository(_ctx);
     Authors = new AuthorRepository(_ctx);
 }
Example #53
0
 public AuthorController()
 {
     _context         = new ApplicationDbContext();
     authorRepository = new AuthorRepository(_context);
 }
 public HomeController(AuthorRepository authorRepository)
 {
     this.AuthorRepository = authorRepository;
 }
        public void Should_Map_A_Book_To_Its_Model()
        {
            var repository = new AuthorRepository();
            var bruce = repository.Insert(new Author
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });
            var author = repository.Insert(new Author
                                  {
                                      FirstName = "Cormac",
                                      LastName = "McCarthy"
                                  });

            var model = Mapper.Map<Book, BookModel>(new Book(repository)
            {
                Id = 5,
                Title = "The Road",
                ISBN = "1234567891234",
                AuthorId = author.Id
            });
            Assert.AreEqual(5, model.Id);
            Assert.AreEqual("The Road", model.Title);
            Assert.AreEqual("1234567891234", model.ISBN);
            Assert.AreEqual(author.Id, model.AuthorId);
            Assert.AreEqual(false, model.IsEditMode);
            Assert.AreEqual(2, model.Authors.Count);
            Assert.AreEqual(bruce.Id, model.Authors[0].Id);
            Assert.AreEqual("Bruce Wayne", model.Authors[0].FullName);
            Assert.AreEqual(author.Id, model.Authors[1].Id);
            Assert.AreEqual("Cormac McCarthy", model.Authors[1].FullName);
            Assert.IsFalse(model.IsEditMode);
        }
 public AuthorService(AuthorRepository repository, BookAuthorRepository bookAuthorRepository)
 {
     _repository           = repository;
     _bookAuthorRepository = bookAuthorRepository;
 }
Example #57
0
 public AuthorManager(IUserInterfaceManager parentUI, string connectionString)
 {
     _parentUI         = parentUI;
     _authorRepository = new AuthorRepository(connectionString);
     _connectionString = connectionString;
 }
Example #58
0
 public AuthorService(ApplicationContext context)
 {
     _authorRepository = new AuthorRepository <Author>(context);
 }
        public void Should_Get_All_Entities()
        {
            var repository = new AuthorRepository();
            var bruce = repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            var dick = repository.Insert(new Author()
            {
                FirstName = "Dick",
                LastName = "Grayson"
            });

            var authors = repository.GetAll();

            Assert.AreEqual(2, authors.Count());
            Assert.AreEqual(bruce.Id, authors.ToList()[0].Id);
            Assert.AreEqual(dick.Id, authors.ToList()[1].Id);
        }
Example #60
0
 public AuthorService(IMapper mapper)
 {
     _authorRepo = new AuthorRepository(mapper);
 }