/// <summary> /// Adds courses /// </summary> /// <param name="courseIDs"></param> /// <param name="account"></param> public void AddCourses(IList <int> courseIDs, int userId) { using (var dbContext = new CourseDbContext()) { var user = dbContext.Users.FirstOrDefault(p => p.UserID == userId); if (user == null) { throw new Exception("未查找到用户:" + userId); } var courses = dbContext.Courses.Where(p => courseIDs.Contains(p.CourseID)).Distinct(); courses.ToList().ForEach(p => { //DO:检测每节课的最大上课人数是否达到学员上限 var exsitedCourseUsers = dbContext.CourseUsers.Where(p1 => p1.CourseID == p.CourseID).Select(p1 => new { p1.UserID, p1.CourseID }).Distinct(); if (exsitedCourseUsers.Count() >= p.MaxNumber) { //已达课程最大上限 throw new Exception("课程[" + p.CourseID + ":" + p.CourseName + "]" + "已经达到上限"); } dbContext.CourseUsers.Add(new CourseUser { UserID = user.UserID, CourseID = p.CourseID }); }); dbContext.SaveChanges(); } }
private IList <CourseUser> GetAllCourseUser() { using (var dbContext = new CourseDbContext()) { return(dbContext.CourseUsers.ToList()); } }
public SubmissionSuccessfulModel(AssignmentDbContext adb, CourseDbContext cdb, IOptions <Assignment> globalAssignment) { assignmentDbContext = adb; courseDbContext = cdb; CurrentCourse = new Course(); GlobalAssignment = globalAssignment.Value; }
public CourseResourcesModel(CourseResourceDbContext adb, CourseDbContext cdb) { courseResourceDbContext = adb; courseDbContext = cdb; CourseResources = new List <CourseResource>(); CurrentCourse = new Course(); }
public IList <User> GetAll() { using (var dbContext = new CourseDbContext()) { return(dbContext.Users.ToList()); } }
public UserProfilePageController(RoleManager <IdentityRole> roleManager, UserManager <ApplicationUser> userManager, CourseDbContext db, SignInManager <ApplicationUser> signInManager) { _userManager = userManager; _db = db; _signInManager = signInManager; }
public static int Main(string[] args) { var configuration = GetConfiguration(); var requesterConfig = LocationRequesterConfiguration.FromConfiguration(configuration); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .WriteTo .ApplicationInsightsTraces(configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]) .Enrich.WithProperty("Type", "SearchAndCompareGeocoder") .Enrich.WithProperty("WebJob_Identifer", Guid.NewGuid()) .Enrich.WithProperty("WebJob_Triggered_Date", DateTime.UtcNow) .CreateLogger(); var options = new DbContextOptionsBuilder <CourseDbContext>() .UseNpgsql(new EnvConfigConnectionStringBuilder().GetConnectionString(configuration)) .Options; var context = new CourseDbContext(options); logger.Information("Geocoder started."); // Wait() because async Mains are not supported var locationRequester = new LocationRequester(requesterConfig, logger, new WrappedHttpClient(), context); var exitcode = locationRequester.RequestLocations().Result; logger.Information("Geocoder finished."); return(exitcode); }
/// <summary> /// Migrate with inifinte retry. /// </summary> /// <param name="dbContext"></param> private void Migrate(CourseDbContext dbContext) { // If the migration fails and throws then the app ends up in a broken state so don't let that happen. // If the migrations failed and the exception was swallowed then the code could make assumptions that result in corrupt data so don't let execution continue till this has worked. int migrationAttempt = 1; while (true) { try { _logger.LogInformation($"Applying EF migrations. Attempt {migrationAttempt} of ∞"); dbContext.Database.Migrate(); _logger.LogInformation($"Applying EF migrations succeeded. Attempt {migrationAttempt} of ∞"); break; // success! } catch (Exception ex) { const int maxDelayMs = 60 * 1000; int delayMs = 1000 * migrationAttempt; if (delayMs > maxDelayMs) { delayMs = maxDelayMs; } // exception included in message string because app insights isn't showing the messages and kudo log stream only shows the message string. _logger.LogError($"Failed to apply EF migrations. Attempt {migrationAttempt} of ∞. Waiting for {delayMs}ms before trying again.\n{ex}", ex); new TelemetryClient().TrackException(ex); Thread.Sleep(delayMs); migrationAttempt++; } } }
public DeleteCourseModel(CourseDbContext phd, ProfileDbContext pDb) { courseDbContext = phd; course = new Course(); profileDbContext = pDb; CurrentProfile = new Profile(); }
public User GetUserById(int userId) { using (var dbContext = new CourseDbContext()) { var user = dbContext.Users.FirstOrDefault(p => p.UserID == userId); return(user); } }
public ViewAssignmentModel(AssignmentDbContext adb, CourseDbContext cdb) { assignmentDbContext = adb; courseDbContext = cdb; CurrentAssignment = new Assignment(); CurrentCourse = new Course(); IfDue = false; }
public AssignmentsModel(AssignmentDbContext adb, CourseDbContext cdb) { assignmentDbContext = adb; courseDbContext = cdb; PendingAssignments = new List <Assignment>(); OldAssignments = new List <Assignment>(); CurrentCourse = new Course(); }
public AdministrationController(RoleManager <IdentityRole> roleManager, UserManager <ApplicationUser> userManager, CourseDbContext db, SignInManager <ApplicationUser> signInManager) { _roleManager = roleManager; _userManager = userManager; _db = db; _signInManager = signInManager; }
/// <summary> /// gets courses by region /// </summary> public IList <Data.Course> GetCoursesByRegion(string region) { using (var dbContext = new CourseDbContext()) { var result = from oCourse in dbContext.Courses.Where(p => p.Region == region) select oCourse; return(result.ToList()); } }
public SubmitAssignmentModel(SubmissionDbContext sdb, AssignmentDbContext adb, CourseDbContext cdb, IOptions <Assignment> globalAssignment) { submissionDbContext = sdb; assignmentDbContext = adb; courseDbContext = cdb; CurrentCourse = new Course(); CurrentAssignment = new Assignment(); GlobalAssignment = globalAssignment.Value; }
/// <summary> /// gets courses /// </summary> public IList <Data.Course> GetCourses() { using (var dbContext = new CourseDbContext()) { var result = from oCourse in dbContext.Courses select oCourse; return(result.ToList()); } }
public Tuple <int, IList <User> > GetUsers(int pageIndex = 1, int pageSize = 20) { using (var dbContext = new CourseDbContext()) { var allUsers = dbContext.Users; var pagedUsers = allUsers.OrderBy(p => p.UserID).Skip(pageIndex - 1).Take(pageSize).ToList(); return(new Tuple <int, IList <User> >(allUsers.Count(), pagedUsers)); } }
public CourseModel(CourseDbContext cdb, AssignmentDbContext adb, ProfileDbContext pdb) { courseDbContext = cdb; assignmentDbContext = adb; profileDbContext = pdb; CurrentCourse = new Course(); CurrentProfile = new Profile(); AssignmentList = new List <Assignment>(); TAs = new List <string>(); }
/// <summary> /// Gets courses by user /// </summary> public IList <Data.Course> GetCoursesByUserId(int userId) { using (var dbContext = new CourseDbContext()) { var result = from oUser in dbContext.Users.Where(p => p.UserID == userId) join oUserCourse in dbContext.CourseUsers on oUser.UserID equals oUserCourse.UserID join oCourse in dbContext.Courses on oUserCourse.CourseID equals oCourse.CourseID select oCourse; return(result.ToList()); } }
public AddNewResourceModel(CourseResourceDbContext adb, CourseDbContext cdb, ProfileDbContext pdb) { courseResourceDbContext = adb; courseDbContext = cdb; CoursesList = new List <Course>(); newResource = new CourseResource(); profileDbContext = pdb; CurrentProfile = new Profile(); }
public AddNewAssignmentModel(AssignmentDbContext adb, CourseDbContext cdb, ProfileDbContext pdb) { assignmentDbContext = adb; courseDbContext = cdb; CoursesList = new List <Course>(); newAssignment = new Assignment(); profileDbContext = pdb; CurrentProfile = new Profile(); }
/// <summary> /// user Login /// </summary> /// <returns></returns> public int Login(string account) { using (var dbContext = new CourseDbContext()) { var user = dbContext.Users.FirstOrDefault(p => p.Account == account); if (user == null) { return(-1); } return(user.UserID); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, CourseDbContext dbContext) { Migrate(dbContext); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers.Add("Cache-Control", "no-cache"); context.Context.Response.Headers.Add("Expires", "-1"); } }); } else { app.UseExceptionHandler("/Home/Error"); app.UseStaticFiles(); app.SetSecurityHeaders(); } app.UseMvc(routes => { }); // Enable the Swagger UI middleware and the Swagger generator app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings => { settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase; settings.PostProcess = document => { document.Info.Version = "v1"; document.Info.Title = "Search API"; document.Info.Description = "An API for searching course data"; }; settings.GeneratorSettings.DocumentProcessors.Add(new SecurityDefinitionAppender(BearerTokenApiKeyDefaults.AuthenticationScheme, new SwaggerSecurityScheme { Type = SwaggerSecuritySchemeType.ApiKey, Description = "In order to interactive with the api please input `Bearer {code}`", In = SwaggerSecurityApiKeyLocation.Header, Name = "Authorization" })); settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor(BearerTokenApiKeyDefaults.AuthenticationScheme)); }); // for reading ucas site we need 1252 available System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); }
public bool ResetPassword(int userId, string password) { using (var dbContext = new CourseDbContext()) { var user = dbContext.Users.FirstOrDefault(p => p.UserID == userId); if (user == null) { throw new Exception("未查找到用户:" + userId); } user.Password = password; dbContext.SaveChanges(); return(true); } }
/// <summary> /// Adds courses /// </summary> /// <param name="courseIDs"></param> /// <param name="account"></param> public void AddCourses(IList <Data.Course> courseList) { if (courseList == null) { throw new ArgumentNullException("courseList"); } using (var dbContext = new CourseDbContext()) { //courseList.ToList().ForEach(p=>dbContext.Courses.Add(p)); dbContext.Courses.AddRange(courseList); dbContext.SaveChanges(); } }
public IActionResult Registrar(RegistroViewModelInput registroViewModelInput) { var optionsBuilder = new DbContextOptionsBuilder <CourseDbContext>(); optionsBuilder.UseSqlServer("Server=localhost;Database=db_courseapi;user=nei;password=Senha#2020"); CourseDbContext context = new CourseDbContext(optionsBuilder.Options); var aluno = new User(); aluno.name = registroViewModelInput.Login; aluno.email = registroViewModelInput.Email; aluno.password = registroViewModelInput.Senha; context.User.Add(aluno); context.SaveChanges(); return(Created("", registroViewModelInput)); }
public async Task Can_Add_Prerequisite_Course_To_Existing_Course() { // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); try { var options = new DbContextOptionsBuilder <CourseDbContext>() .UseSqlite(connection) .Options; // Create the schema in the database using (var context = new CourseDbContext(options)) { context.Database.EnsureCreated(); } // Run the test against one instance of the context using (var context = new CourseDbContext(options)) { var course1 = await context.Courses.FindAsync(1); var course2 = await context.Courses.FindAsync(50); course2.PrerequisiteCourses.Add(course1); await context.SaveChangesAsync(); } // Use a separate instance of the context to verify correct data was saved to database using (var context = new CourseDbContext(options)) { var course2 = await context.Courses .Include(c => c.PrerequisiteCourses).FirstOrDefaultAsync(i => i.Id == 50); Assert.Equal("4250", course2.CourseNumber); Assert.Equal("1120", course2.PrerequisiteCourses.FirstOrDefault().CourseNumber); } } finally { connection.Close(); } }
public LikeRepository(CourseDbContext appDbContext) { this._appDbContext = appDbContext; }
public CourseRepository(CourseDbContext context) : base(context) { _context = context; }
public CollectionsController(CourseDbContext db, UserManager <ApplicationUser> userManager) { _db = db; _userManager = userManager; }