public void MakeSubscription(Book book, string userId, bool isToTheLibrary) { using (var context = new LibraryContext()) { DateTime returnDate; if (isToTheLibrary) { returnDate = DateTime.Today; } else { returnDate = DateTime.Today.AddDays(14); } context.InSubscriptions.Add(new InSubscription { ISBN = book.ISBN, IsInUse = true, UserId = userId, DateOfReceipt = DateTime.Today, ReturnDate = returnDate }); book.Quantity -= 1; EditBook(book); context.SaveChanges(); } }
public void AddBook(Book book) { using (var context = new LibraryContext()) { book.isDeleted = false; context.Books.Add(book); context.SaveChanges(); } }
/// <summary> /// ************************************************************************************************* /// USE CASE 7: Display details of all Loans for a Member specified by MemberId, /// and the details of that Member /// /// Object type required: Entire Object Graph /// Repository to be used: Loans /// Query logic: select everything /// Fetch strategy: Include Member, Copy, Title, Shelf /// Objects materialised: Loans , Member, Copy, Title, Shelf /// ************************************************************************************************* /// </summary> /// <returns></returns> public List<Loan> GetEntireObjectGraph() { using (LibraryContext db = new LibraryContext()) { var results = db.Loans .Include("Member") .Include("Copy") .Include("Copy.Title") .Include("Copy.Title.Shelf"); return results.ToList<Loan>(); } }
public DotNetCompiler(LibraryContext context, string filename) { Context = context; var fi = new FileInfo(filename); Path = fi; BuilderAppDomain = AppDomain.CurrentDomain; AssemblyBuilder = BuilderAppDomain.DefineDynamicAssembly(new AssemblyName(fi.Name), AssemblyBuilderAccess.RunAndSave, fi.DirectoryName); MainModule = AssemblyBuilder.DefineDynamicModule(fi.Name, fi.Name); ScriptsType = MainModule.DefineType("Scripts", TypeAttributes.Class); RoomsType = MainModule.DefineType("Rooms", TypeAttributes.Class); }
public void ReturnBook(int subscriptionId) { using (var context = new LibraryContext()) { var original = context.InSubscriptions.Find(subscriptionId); original.ReturnDate = DateTime.Today.Date; original.IsInUse = false; var book = context.Books.First(x => x.ISBN == original.ISBN); book.Quantity += 1; context.SaveChanges(); } }
/// <summary> /// ************************************************************************************************* /// USE CASE 6: Display the TitleName of and number of Loans for each Title - it is not /// necessary here to retrieve domain objects, just the data values specified /// /// Object type required: Title and count of Loans /// Repository to be used: Loans /// Query logic: Group the Loans by Title /// Fetch strategy: Project the title and count, no other objects need to be specifically fetched /// Objects materialised: Loan /// ************************************************************************************************* /// </summary> /// <returns></returns> public Dictionary<string, int> GetLoansPerTitle() { using (LibraryContext db = new LibraryContext()) { Dictionary<string, int> LoansPerTitle = new Dictionary<string, int>(); var results = db.Loans .GroupBy(l => l.Copy.Title.TitleName) .Select(g => new { Title = g.Key, Loans = g.Count() }); foreach (var a in results) { LoansPerTitle.Add(a.Title, a.Loans); } return LoansPerTitle; } }
public ActionResult AddBook(AccountRoomModel model) { using (var con = new LibraryContext()) { con.Books.Add(new Book { Author = model.EditBook.Author, Name = model.EditBook.Name, Description = model.EditBook.Description, ISBN = model.EditBook.Isbn }); con.SaveChanges(); model.AllBooks = con.Books.Take(10).ToList(); } return PartialView("Librarian/_EditBooksDatabasePartial", model); }
public SimpleMembershipInitializer() { //Database.SetInitializer<LibraryContext>(null); try { using (var context = new LibraryContext()) { if (!context.Database.Exists()) { context.Database.Initialize(true); // Create the SimpleMembership database without Entity Framework migration schema //((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("Library_dbConnection", "LibraryUsers", "LibraryUserId", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public void Initialize() { var connection = DbConnectionFactory.CreateTransient(); _context = new LibraryContext(connection); _repository = new BookRepository(_context); }
public PlayerFacade(LibraryContext context) { this.context = context; }
public UserController(LibraryContext context) { _context = context; }
public AsyncCategoryRepository(LibraryContext context) : base(context) { }
public Parser(LibraryContext context, TextReader r) : this(context, new Lexer(r)) { }
public CheckoutService(LibraryContext context) { _context = context; }
//TODO : 08 - Inyecto el servicio public LibraryRepository(LibraryContext context, IPropertyMappingService propertyMappingService) { _context = context; _propertyMappingService = propertyMappingService; }
/// <summary> /// ************************************************************************************************* /// USE CASE 3: Display details of all Titles which have copies available in a Category specified /// by Description at any Shelf with a specified SiteName, and display the details of the copies /// of those Titles /// /// Object type required: Title /// Repository to be used: Titles, Copies /// Query logic: Category.Description == value /// Shelf.SiteName = value /// At least 1 Copy is available. /// Fetch strategy: Include Copies /// Objects materialised: Title, Copies /// /// Note: No navigation possible from Category to Title or vice versa, therefore /// a Join is used to provide the association on the CategoryId foreign key. /// /// ************************************************************************************************* /// </summary> /// <param name="description"></param> /// <param name="siteName"></param> /// <returns></returns> public List<Title> GetTitlesWithCopiesForCategoryDescription(string description, string siteName) { using (LibraryContext db = new LibraryContext()) { int id = db.Categories.Where(c => c.Description == description).Select(c => c.CategoryId).Single(); var titles = db.Titles .Include("Copies") .Where(t => t.Shelf.SiteName == siteName && (t.Copies.Where(c => c.IsAvailable == true && c.Title.CategoryId == id).Count() > 0) && t.CategoryId == id); return titles.ToList<Title>(); } }
private void _UpdateFromCurrent() { // Search for the appropriate JMSML Library elements, given the current (2525D) // SIDC for this Symbol. string first10 = _sidc.PartAString; string second10 = _sidc.PartBString; _librarian.ResetStatusCode(); _version = _librarian.Version(Convert.ToUInt16(first10.Substring(0, 1)), Convert.ToUInt16(first10.Substring(1, 1))); _context = _librarian.Context(Convert.ToUInt16(first10.Substring(2, 1))); _standardIdentity = _librarian.StandardIdentity(Convert.ToUInt16(first10.Substring(3, 1))); _sig = _librarian.StandardIdentityGroup(_standardIdentity); _symbolSet = _librarian.SymbolSet(Convert.ToUInt16(first10.Substring(4, 1)), Convert.ToUInt16(first10.Substring(5, 1))); if (_symbolSet != null) { _dimension = _librarian.DimensionBySymbolSet(_symbolSet.ID); } if (_context != null && _dimension != null && _standardIdentity != null) { _affiliation = _librarian.Affiliation(_context.ID, _dimension.ID, _standardIdentity.ID); } _status = _librarian.Status(Convert.ToUInt16(first10.Substring(6, 1))); _hqTFDummy = _librarian.HQTFDummy(Convert.ToUInt16(first10.Substring(7, 1))); _amplifierGroup = _librarian.AmplifierGroup(Convert.ToUInt16(first10.Substring(8, 1))); if (_amplifierGroup != null) { _amplifier = _librarian.Amplifier(_amplifierGroup, Convert.ToUInt16(first10.Substring(9, 1))); } if (_symbolSet != null) { _entity = _librarian.Entity(_symbolSet, Convert.ToUInt16(second10.Substring(0, 1)), Convert.ToUInt16(second10.Substring(1, 1))); if (_entity != null) { _entityType = _librarian.EntityType(_entity, Convert.ToUInt16(second10.Substring(2, 1)), Convert.ToUInt16(second10.Substring(3, 1))); } if (_entityType != null) { _entitySubType = _librarian.EntitySubType(_entityType, Convert.ToUInt16(second10.Substring(4, 1)), Convert.ToUInt16(second10.Substring(5, 1))); if (_entitySubType == null) { _entitySubType = _librarian.EntitySubType(_symbolSet, Convert.ToUInt16(second10.Substring(4, 1)), Convert.ToUInt16(second10.Substring(5, 1))); } } _modifierOne = _librarian.ModifierOne(_symbolSet, Convert.ToUInt16(second10.Substring(6, 1)), Convert.ToUInt16(second10.Substring(7, 1))); _modifierTwo = _librarian.ModifierTwo(_symbolSet, Convert.ToUInt16(second10.Substring(8, 1)), Convert.ToUInt16(second10.Substring(9, 1))); _legacySymbol = _librarian.LegacySymbol(_symbolSet, _entity, _entityType, _entitySubType, _modifierOne, _modifierTwo); } _librarian.LogConversionResult(_sidc.PartAString + ", " + _sidc.PartBString); _ValidateStatus(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, LibraryContext libraryContext) { app.UseSwagger(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(appBuilder => { appBuilder.Run(async context => { var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandlerFeature != null) { var logger = loggerFactory.CreateLogger("Global exception logger"); logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message); } context.Response.StatusCode = 500; await context.Response.WriteAsync("An unexpected fault happened. Try again later."); }); }); } AutoMapper.Mapper.Initialize(cfg => { cfg.CreateMap <Entities.Author, Models.AuthorDto>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}")) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.GetCurrentAge(src.DateOfDeath))); cfg.CreateMap <Entities.Book, Models.BookDto>(); cfg.CreateMap <Models.AuthorForCreationDto, Entities.Author>(); cfg.CreateMap <Models.AuthorForCreationWithDateOfDeathDto, Entities.Author>(); cfg.CreateMap <Models.BookForCreationDto, Entities.Book>(); cfg.CreateMap <Models.BookForUpdateDto, Entities.Book>(); cfg.CreateMap <Entities.Book, Models.BookForUpdateDto>(); }); libraryContext.EnsureSeedDataForContext(); app.UseResponseCaching(); app.UseHttpCacheHeaders(); app.UseMvc(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", ".net core API sample"); }); }
public AuthorRepository(LibraryContext libraryContext) { _libraryContext = libraryContext; }
public PP2Controller(LibraryContext ctxt) { _context = ctxt; }
public BookRepository(LibraryContext context) { _context = context; }
public RentalsController(LibraryContext context) { _context = context; }
public LibrarianService() { _libraryContext = new LibraryContext(); }
/// <summary> /// ************************************************************************************************* /// USE CASE 5: Display details of Titles of which Copies are loaned between 12/1/13 and /// 22/1/13 of Titles located at a Shelf with a specified SiteName to a specified Member, and /// display details of the Member /// /// Object type required: Title /// Repository to be used: Loans /// Query logic: Loan.LoanDate within period /// Fetch strategy: Include Member /// Objects materialised: Title, Member /// ************************************************************************************************* /// </summary> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="siteName"></param> /// <param name="memberName"></param> /// <returns></returns> public Dictionary<Title, Member> GetTitlesLoanedByPeriod(DateTime fromDate, DateTime toDate, string siteName, string memberName) { using (LibraryContext db = new LibraryContext()) { Dictionary<Title, Member> loanedTitles = new Dictionary<Title, Member>(); var results = db.Loans .Include("Member") .Include("Copy.Title") .Where(l => l.LoanDate >= fromDate && l.LoanDate <= toDate) .Where(l => l.Copy.Title.Shelf.SiteName == siteName) .Where(l => l.Member.Name == memberName) .Select(l => new { Title = l.Copy.Title, Member = l.Member }); foreach (var a in results) { loanedTitles.Add(a.Title, a.Member); } return loanedTitles; } }
public ChartsController(LibraryContext context) { _context = context; }
public HomeController(LibraryContext context) { _context = context; }
public UserRepository(LibraryContext context) { _context = context; }
public BookRepository(LibraryContext libContext) : base(libContext) { }
public RepositoryCore(LibraryContext context) { this.Context = context; this.DbSet = this.Context.Set <TEntity>(); }
public SummonerController(LibraryContext ctxt) { _context = ctxt; }
public BookController(LibraryContext context) => _context = context;
public LibraryAssetService(LibraryContext context) { _context = context; }
public bool isSubscribedAlready(string isbn, string userId) { using (var context = new LibraryContext()) { InSubscription model = context.InSubscriptions.FirstOrDefault(x => x.ISBN == isbn && x.UserId == userId); if (model == null) { return false; } else { return true; } } }
public JournalRepository(LibraryContext db) : base(db) { }
//ManageMessageId? message // // GET: /Account/Manage public ActionResult Manage() { ViewBag.IsLibrarian = User.IsInRole("Librarian"); var model = new AccountRoomModel(); using (var con = new LibraryContext()) { model.LibraryUser = con.LibraryUsers.Include("UserBookCollection") .SingleOrDefault(la => la.LibraryUserId == WebSecurity.CurrentUserId); model.AllBooks = con.Books.Take(10).ToList(); model.PasswordModel = new LocalPasswordModel(); model.EditBook = new CrudBookModel(); } return View(model); }
public DotNetCompiler(LibraryContext context) { Context = context; }
public BookModule() { Get("/books", args => { var db = new LibraryContext(); var bookz = from b in db.Books select b; string searchQ = (string)Request.Query["searchquery"]; if (Request.Query["searchquery"]) { bookz = bookz.Where(b => b.Title.ToLower().Contains(searchQ.ToLower())); } string sortOrder = (string)Request.Query["sortorder"]; switch (sortOrder) { case "id": bookz = bookz.OrderBy(b => b.BookID); break; case "id_desc": bookz = bookz.OrderByDescending(b => b.BookID); break; case "title": bookz = bookz.OrderBy(b => b.Title); break; case "title_desc": bookz = bookz.OrderByDescending(b => b.Title); break; case "author": bookz = bookz.OrderBy(b => b.Author); break; case "author_desc": bookz = bookz.OrderByDescending(b => b.Author); break; default: bookz = bookz.OrderBy(b => b.Title); break; } return(View["BookIndex", bookz.ToList()]); }); Get("/books/page/{size}/{pg}", args => { var db = new LibraryContext(); var numbooks = db.Books.Count(); var bookz = db.Books.ToArray(); ArrayList subset = new ArrayList(); if (args.size * (args.pg - 1) < numbooks) { if (args.size * args.pg < numbooks) { for (var i = args.size * (args.pg - 1); i < args.size * args.pg; i++) { subset.Add(bookz[i]); } } else { for (var i = args.size * (args.pg - 1); i < numbooks; i++) { subset.Add(bookz[i]); } } } else { subset.Add(new Book { Title = null, Author = null }); } return(View["BookIndex", subset]); }); Get("/books/new", args => View["NewBookForm"]); Get("/books/new/confirmnewbook/{ttl}/{aut}", args => { Book newB = new Book() { Title = args.ttl, Author = args.aut, }; return(View["NewBook", newB]); }); Get("/books/{id}", args => { var db = new LibraryContext(); int id = args.id; var book = db.Books.Include(b => b.Copies).ThenInclude(c => c.Loan).SingleOrDefault(b => b.BookID == id); Context.ViewBag.avCopies = book.Copies.Count(c => c.Loan == null); return(View["SingleBook", book]); }); Get("/books/{id}/confirmDelete", args => { var db = new LibraryContext(); int id = args.id; var book = db.Books.Find(id); return(View["DeleteBook", book]); }); Get("/deletebook/{id}", args => { var db = new LibraryContext(); int id = args.id; Book bookToBeDeleted = db.Books.Find(id); db.Books.Remove(bookToBeDeleted); db.SaveChanges(); var bookz = db.Books.ToList(); return(View["BookIndex", bookz]); }); Delete("/books/{id}", args => { var db = new LibraryContext(); int id = args.id; Book bookToBeDeleted = db.Books.Find(id); db.Books.Remove(bookToBeDeleted); db.SaveChanges(); return(this.Context.GetRedirect("/books/")); }); Post("/books", args => { var db = new LibraryContext(); Book newB = new Book() { Title = this.Request.Form.newTitle, Author = this.Request.Form.newAuthor, YearPublished = this.Request.Form.newYearPublished, }; db.Books.Add(newB); db.SaveChanges(); return(this.Context.GetRedirect("/books/" + newB.BookID)); }); Get("/addtestbook", args => { var db = new LibraryContext(); Book newB = new Book { Title = "testTitle_" + new Random().Next(1000, 9999), Author = "testAuthor_" + new Random().Next(1000, 9999), YearPublished = 3333 }; db.Books.Add(newB); db.SaveChanges(); var bookz = db.Books.ToList(); bookz.Reverse(); return(this.Context.GetRedirect("/books/" + newB.BookID)); }); Get("/addbook/{ttl}/{aut}", args => { var db = new LibraryContext(); Book newB = new Book() { Title = args.ttl, Author = args.aut, }; db.Books.Add(newB); db.SaveChanges(); return(View["singlebook", newB]); }); Get("/books/{id}/edit", args => { var db = new LibraryContext(); int id = args.id; Book bookToBeEdited = db.Books.Find(id); return(View["EditBookForm", bookToBeEdited]); }); Put("/books/{id}", args => { var db = new LibraryContext(); int id = args.id; var book = db.Books.Find(id); book.Title = this.Request.Form.newTitle; book.Author = this.Request.Form.newAuthor; book.YearPublished = this.Request.Form.newYearPublished; db.Books.Update(book); db.SaveChanges(); return(this.Context.GetRedirect("/books/" + book.BookID)); }); }
public void RemoveBook(string isbn) { using (var context = new LibraryContext()) { context.Books.Find(isbn).isDeleted = true; context.SaveChanges(); } }
public PersonRepository(LibraryContext db) { this.db = db; }
public void GiveBook(int subscriptionId) { using (var context = new LibraryContext()) { var original = context.InSubscriptions.Find(subscriptionId); original.IsAccepted = true; context.SaveChanges(); } }
public List<Loan> GetMembersWhoHaveTitleOnLoanWithFiltersAndFetchStrategy(string bookTitle) { using (LibraryContext db = new LibraryContext()) { var loans = db.Loans .FetchStrategyForMembersWithTitlesOnLoan() //.Include("Member") .FilterByBookTitle(bookTitle); //.Where(l => l.Copy.Title.TitleName == bookTitle); return loans.ToList<Loan>(); } }
public LibraryCardController(LibraryContext context) { _context = context; }
public ActionResult Register(RegisterModel model) { if (!Roles.RoleExists("Librarian")) { Roles.CreateRole("Librarian"); } if (!Roles.RoleExists("Reader")) { Roles.CreateRole("Reader"); } if (!model.IsLibrarian) { ModelState.Remove("LibrarianPassword"); } if (ModelState.IsValid) { try { if (model.IsLibrarian && model.LibrarianPassword != WebConfigurationManager.AppSettings["LibrarianKey"]) { ModelState.AddModelError("", "Wrong librarian password"); return View(model); } else { using (var con = new LibraryContext()) { if (con.LibraryUsers.Any(usr => usr.Email == model.Email)) { ModelState.AddModelError("", "User with this email already exists"); return View(model); } } WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email }); Roles.AddUsersToRoles(new[] { model.UserName }, new[] { model.IsLibrarian ? "Librarian" : "Reader" }); WebSecurity.Login(model.UserName, model.Password); } return RedirectToAction("Manage", "Account"); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return View(model); }
public void EditBook(Book book) { using (var context = new LibraryContext()) { var original = context.Books.Find(book.ISBN); context.Entry(original).CurrentValues.SetValues(book); context.SaveChanges(); } }
public BreweryController(LibraryContext context) { this.context = context; }
/// <summary> /// ************************************************************************************************* /// USE CASE 4: Display details of all Members who have Loans for a specified Title, and display /// the dates of those Loans /// /// Object type required: Loan /// Repository to be used: Loans /// Query logic: Title.TitlaName == value /// Fetch strategy: Include Member /// Objects materialised: Loans, Member /// ************************************************************************************************* /// </summary> /// <param name="bookTitle"></param> /// <returns></returns> public List<Loan> GetMembersWhoHaveTitleOnLoan(string bookTitle) { using (LibraryContext db = new LibraryContext()) { var loans = db.Loans .Include("Member") .Where(l => l.Copy.Title.TitleName == bookTitle); return loans.ToList<Loan>(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, LibraryContext libraryContext) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ece's API V1"); c.RoutePrefix = string.Empty; // by adding this, swagger is shows up as soon as we type http://localhost:<port>/sss }); loggerFactory.AddConsole(); loggerFactory.AddDebug(LogLevel.Information); //loggerFactory.AddProvider(new NLogLoggerProvider()); loggerFactory.AddNLog(); // middleware if (env.IsDevelopment()) { // use stacktrace to see error in dev env app.UseDeveloperExceptionPage(); } else { // use exception handler to see error in production env app.UseExceptionHandler(appBuilder => { appBuilder.Run(async context => { var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandlerFeature != null) { // catches invalid patch error var logger = loggerFactory.CreateLogger("Global Exception Logger"); logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message); } context.Response.StatusCode = 500; // server error await context.Response.WriteAsync("An unexpected error happened. Try again later"); }); }); } // to use automapper, first download automapper nuget package and then // here in Configure function in Startup.cs add mapping properties // from source to destination // for automapping, it requires property name in the source and destination // to be the same so they can be matched and then be able to mapped AutoMapper.Mapper.Initialize( cfg => { cfg.CreateMap <Author, Models.AuthorDto>() .ForMember(dest => dest.Name, opt => opt.MapFrom(source => $"{source.FirstName} {source.LastName}")) // projection .ForMember(dest => dest.Age, opt => opt.MapFrom(source => source.DateOfBirth.GetCurrentAge())); cfg.CreateMap <Book, Models.BookDto>(); cfg.CreateMap <Models.AuthorForCreationDto, Author>(); cfg.CreateMap <Models.BookForCreationDto, Book>(); cfg.CreateMap <Models.BookForUpdateDto, Book>(); cfg.CreateMap <Book, Models.BookForUpdateDto>(); }); // formember is called projection // since properties in source and destination must be the same for the mapping // but since we need in dto class current age rather than dateofbirth and first+lastname of // author, we used formember for mapping without error libraryContext.EnsureSeedDataForContext(); app.UseMvc(); }
/// <summary> /// ************************************************************************************************* /// USE CASE 2: Display details of all Titles in a Category specified by Description /// /// Object type required: Title /// Repository to be used: Titles, Categories /// Query logic: Category.Description == value /// Fetch strategy: Include Category /// Objects materialised: Title, Category /// /// Note: No navigation possible from Category to Title or vice versa, therefore /// a Join is used to provide the association on the CategoryId foreign key. /// /// ************************************************************************************************* /// </summary> /// <param name="description"></param> /// <returns></returns> public List<Title> GetTitlesforCategoryDescription(string description) { using (LibraryContext db = new LibraryContext()) { IQueryable<Title> result = db.Titles .Include("Shelf") .Join(db.Categories, t => t.CategoryId, c => c.CategoryId, (t, c) => new { t, c }) .Where(c1 => c1.c.Description == description) .Select(t1 => t1.t); // Must force the IQueryable<> to be traversed BEFORE the context is closed. return result.ToList<Title>(); } }
public LibraryBranchService(LibraryContext context) { _context = context; }
/// <summary> /// ************************************************************************************************* /// USE CASE 8: Display details of Titles of which Copies are loaned between 12/1/13 and /// 22/1/13 of Titles located at a Shelf with a specified SiteName to a specified Member, and /// display details of the Member /// /// Object type required: Title /// Repository to be used: Loans /// Query logic: use Filter extension methods on IQueryable(Loan) /// Fetch strategy: Include Member /// Objects materialised: Title, Member /// ************************************************************************************************* /// </summary> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="siteName"></param> /// <param name="memberName"></param> /// <returns></returns> public Dictionary<Title, Member> GetTitlesLoanedByPeriodWithFilters(DateTime fromDate, DateTime toDate, string siteName, string memberName) { using (LibraryContext db = new LibraryContext()) { Dictionary<Title, Member> loanedTitles = new Dictionary<Title, Member>(); var results = db.Loans .FetchStrategy() //.Include("Member") //.Include("Copy.Title") .FilterByAll(fromDate, toDate, siteName, memberName) //.FilterbyLoanDates(fromDate, toDate) //.FilterBySiteName(siteName) //.filterByMemberName(memberName) .Select(l => new { Title = l.Copy.Title, Member = l.Member }); foreach (var a in results) { loanedTitles.Add(a.Title, a.Member); } return loanedTitles; } }
public CheckOutServices(LibraryContext context) { _context = context; }
public BooksController(LibraryContext context) { _context = context; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, LibraryContext libraryContext) { loggerFactory.AddConsole(); loggerFactory.AddDebug(LogLevel.Information); // loggerFactory.AddProvider(new NLog.Extensions.Logging.NLogLoggerProvider()); loggerFactory.AddNLog(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(appBuilder => { appBuilder.Run(async context => { var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandlerFeature != null) { var logger = loggerFactory.CreateLogger("Global exception logger"); logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message); } context.Response.StatusCode = 500; await context.Response.WriteAsync("An unexpected fault happened. Try again later."); }); }); } AutoMapper.Mapper.Initialize(cfg => { cfg.CreateMap <Entities.Author, Models.AuthorDto>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}")) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.GetCurrentAge(src.DateOfDeath))); cfg.CreateMap <Entities.Book, Models.BookDto>(); cfg.CreateMap <Models.AuthorForCreationDto, Entities.Author>(); cfg.CreateMap <Models.AuthorForCreationWithDateOfDeathDto, Entities.Author>(); cfg.CreateMap <Models.BookForCreationDto, Entities.Book>(); cfg.CreateMap <Models.BookForUpdateDto, Entities.Book>(); cfg.CreateMap <Entities.Book, Models.BookForUpdateDto>(); }); libraryContext.EnsureSeedDataForContext(); app.UseMvc(); }
/// <summary> /// ************************************************************************************************* /// USE CASE 1: Display details of all Loans for a Member specified by MemberId, /// and the details of that Member /// /// Object type required: Member /// Repository to be used: Members /// Query logic: MemberId == value /// Fetch strategy: Include Loans /// Objects materialised: Title, Loans /// ************************************************************************************************* /// </summary> /// <param name="memberId"></param> /// <returns></returns> public Member GetMemberDetailsAndLoans(int memberId) { // Use the 'using' construct to ensure the context is disposed. This is required // because other contexts may use the same entities, which result in SQL DataReaders // being used, unless they are closed once finished, exceptions could be thrown when // referencing another context which would use the same reader. This ensures the // data reader is closed. using (LibraryContext db = new LibraryContext()) { var member = db.Members .Include("Loans") .Where(m => m.MemberId == memberId) .FirstOrDefault(); return member; } }
internal Parser(LibraryContext context, Lexer lex) { l = lex; Context = context ?? new LibraryContext(); }