public async Task <ActionResult> Create([Bind(Include = "Id,Item1,Item2,Item3,Item4,Item4Bis,IdClass1,Class1sIds")] Class2 class2) { if (ModelState.IsValid) { foreach (var item in class2.Class1sIds) { class2.Class1s.Add(db.Class1.Find(item)); } db.Class2.Add(class2); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.IdClass1 = new SelectList(db.Class1, "Id", "Data", class2.IdClass1); List <SelectListItem> items = new List <SelectListItem>(); using (WebApplication1Context db = new WebApplication1Context()) { foreach (var item in db.Class1.ToList()) { items.Add(new SelectListItem() { Text = item.Data, Value = item.Id.Value.ToString() }); } ViewBag.Class1s = items; } return(View(class2)); }
public IHttpActionResult PlaceholderOrgCreate(OrganizationModel newOrganization) { WebApplication1Context context = new WebApplication1Context(); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(newOrganization.containerName); container.CreateIfNotExists(); // Create the container if it doesn't already exist. context.OrganizationsModel.Add( new OrganizationModel { name = newOrganization.name, description = newOrganization.description, containerName = newOrganization.containerName, }); context.SaveChangesAsync(); return(Ok()); }
// // GET: /Home/ public async Task <IActionResult> Index( [FromServices] WebApplication1Context dbContext, [FromServices] IMemoryCache cache) { // Get most popular albums var cacheKey = "topselling"; List <Album> albums; if (!cache.TryGetValue(cacheKey, out albums)) { albums = await GetTopSellingAlbumsAsync(dbContext, 6); if (albums != null && albums.Count > 0) { if (_appSettings.CacheDbResults) { // Refresh it every 10 minutes. // Let this be the last item to be removed by cache if cache GC kicks in. cache.Set( cacheKey, albums, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(10)) .SetPriority(CacheItemPriority.High)); } } } return(View(albums)); }
public ActionResult Contact() { ViewBag.Message = "Your contact page."; using (WebApplication1Context db = new WebApplication1Context()) { List <Class1> class1s = new List <Class1>(); for (int i = 0; i < 5; i++) { class1s.Add(new Class1() { Data = "data" + i }); db.Class1.Add(class1s.ElementAt(i)); } db.SaveChanges(); db.Class2.Add(new Class2() { Item1 = "test", Item2 = true, Item3 = DateTime.Now, Item4 = 20.20, Class1s = class1s }); db.SaveChanges(); } return(View()); }
public IHttpActionResult GetProjects(ProjectModel projectModel) { bool loggedIn = false; string inputRequest = projectModel.token; loggedIn = LoginUtils.ValidateToken(projectModel.token, projectModel.userId); if (loggedIn == true) { int orgId = LoginUtils.GetUserOrganization(projectModel.userId); if (orgId == -1) { return(NotFound()); // organisation not found! } else { WebApplication1Context context = new WebApplication1Context(); IQueryable <ProjectModel> projects = context.ProjectsModel.Where(a => a.ownerId == orgId); return(Ok(projects)); // Hopefully this will return a content negotiated list of projects. TODO /*foreach(ProjectModel rowData in projects) * { * * }*/ } } else { return(NotFound()); // token not found! } }
public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context) { WebApplication1Context db = context.Get <WebApplication1Context>(); ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(db)); return(manager); }
public ClienteValidator() { this.db = new WebApplication1Context(); RuleFor(cliente => cliente.Email).EmailAddress().WithMessage("E-mail inválido!"); RuleFor(cliente => cliente.Email).Equal(cliente => cliente.ConfirmacaoEmail).WithMessage("Os E-mails precisam ser iguais!"); RuleFor(cliente => cliente.DataAniversario).Must(ValidarData).WithMessage("Data inválida!."); RuleFor(cliente => cliente.Email).Must((tipo, nome) => { return(UniqueEmail(tipo.ID, tipo.Email)); }).WithMessage("E-mail já cadastrado."); }
public IHttpActionResult PostLogin(LoginModel loginModel) { WebApplication1Context context = new WebApplication1Context(); string error = "Invalid Username or Password"; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } AccountsModel account = context.AccountsModel.Where(a => a.username == loginModel.username).FirstOrDefault(); if (account.username == loginModel.username) { byte[] saltInput = LoginUtils.hash(loginModel.password, account.Salt); bool slowHashCheck = LoginUtils.slowEquals(saltInput, account.SaltedAndHashedPassword); if (slowHashCheck == true) { // Success! string rawToken = LoginUtils.makeSimpleToken(); string timeStamp = DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss"); string obfuscatedToken = LoginUtils.encryptToken(rawToken, timeStamp); byte[] hashedToken = LoginUtils.hashNoSalt(rawToken); context.TokensModel.Add( new TokenModel { tokenHash = hashedToken, tokenDate = timeStamp, userid = account.primaryKey }); context.SaveChangesAsync(); //return Ok(obfuscatedToken); // return the obfuscated token! return(Ok(new { token = obfuscatedToken, userId = account.primaryKey, })); } else { //return BadRequest("i failed here!"); return(BadRequest(error)); } } else { //return BadRequest("i failed there!"); return(BadRequest(error)); } }
private Task <List <Album> > GetTopSellingAlbumsAsync(WebApplication1Context dbContext, int count) { // Group the order details by album and return // the albums with the highest count return(dbContext.Albums .OrderByDescending(a => a.OrderDetails.Count) .Take(count) .ToListAsync()); }
public TipoDespesaValidator(int id) { this.db = new WebApplication1Context(); RuleFor(tipoDespesa => tipoDespesa.Nome).MaximumLength(255).WithMessage("Máximo de 255 caracteres"); // if (this.db.TipoDespesas.Where(x => x.Id == id).Count() == 0) //{ RuleFor(tipoDespesa => tipoDespesa.Nome).Must((tipo, nome) => { return(UniqueName(tipo.Id, tipo.Nome)); }).WithMessage("Tipo de Categoria de Despesa Cadastrada"); //} }
public static int GetUserOrganization(int userId) { WebApplication1Context context = new WebApplication1Context(); AccountsModel account = context.AccountsModel.Where(a => a.primaryKey == userId).FirstOrDefault(); if (account.primaryKey == userId) { return(account.organizationId); } else { return(-1); // fail } }
public async Task Edit_method_in_CompanyController_should_throw_exception_when_id_is_null() { var options = new DbContextOptionsBuilder <WebApplication1Context>().UseInMemoryDatabase(databaseName: "Test4").Options; using (var context = new WebApplication1Context(options)) { context.Companies.Add(new Company() { Id = 1, Name = "my company" }); context.SaveChanges(); var controller = new CompanyController(context); await Assert.ThrowsAsync <InvalidOperationException>(() => controller.Edit(null)); } }
public async Task Details_method_in_jobOffersController_should_throw_exception_when_id_is_null() { var options = new DbContextOptionsBuilder <WebApplication1Context>().UseInMemoryDatabase(databaseName: "Test1").Options; using (var context = new WebApplication1Context(options)) { context.JobOffer.Add(new JobOffer() { Id = 1, JobTitle = "job1" }); context.SaveChanges(); var controller = new JobOffersController(context); await Assert.ThrowsAsync <InvalidOperationException>(() => controller.Details(null)); } }
public static void Initialize(IServiceProvider serviceProvider) { using (var context = new WebApplication1Context( serviceProvider.GetRequiredService < DbContextOptions <WebApplication1Context> >())) { // Look for any movies. if (context.Movie.Any()) { return; // DB has been seeded } context.Movie.AddRange( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M }, new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M } ); context.SaveChanges(); } }
public static void Seed(WebApplication1Context context) { context.Database.EnsureCreated(); if (context.Users.Any()) { return; } byte[] passwordHash, passwordSalt; // Seed admin UserService.CreatePasswordHash("admin@pw", out passwordHash, out passwordSalt); context.Users.Add(new User { UserName = "******", FullName = "Administrator", Role = Role.Admin, PasswordHash = passwordHash, PasswordSalt = passwordSalt }); // Seed user UserService.CreatePasswordHash("guest@pw", out passwordHash, out passwordSalt); context.Users.Add(new User { UserName = "******", FullName = "Guest", Role = Role.User, PasswordHash = passwordHash, PasswordSalt = passwordSalt }); UserService.CreatePasswordHash("test@pw", out passwordHash, out passwordSalt); context.Users.Add(new User { UserName = "******", FullName = "Test", Role = Role.User, PasswordHash = passwordHash, PasswordSalt = passwordSalt }); context.SaveChanges(); }
public async Task Details_method_in_jobOffersController() { var options = new DbContextOptionsBuilder <WebApplication1Context>().UseInMemoryDatabase(databaseName: "Test").Options; using (var context = new WebApplication1Context(options)) { context.JobOffer.Add(new JobOffer() { Id = 1, JobTitle = "job1" }); context.SaveChanges(); var controller = new JobOffersController(context); var result = await controller.Details(1); var viewResult = Assert.IsType <ViewResult>(result); Assert.Equal(1, ((JobOffer)viewResult.Model).Id); Assert.Equal("job1", ((JobOffer)viewResult.Model).JobTitle); } }
public async Task When_Edit_ReturnsEditView_in_CompanyController() { var options = new DbContextOptionsBuilder <WebApplication1Context>().UseInMemoryDatabase(databaseName: "Test3").Options; using (var context = new WebApplication1Context(options)) { context.Companies.Add(new Company() { Id = 1, Name = "my company" }); context.SaveChanges(); var controller = new CompanyController(context); var result = await controller.Edit(1); var viewResult = Assert.IsType <ViewResult>(result); Assert.Equal(1, ((Company)viewResult.Model).Id); Assert.Equal("my company", ((Company)viewResult.Model).Name); } }
// GET: Class2/Create public ActionResult Create() { ViewBag.IdClass1 = new SelectList(db.Class1, "Id", "Data"); List <SelectListItem> items = new List <SelectListItem>(); using (WebApplication1Context db = new WebApplication1Context()) { foreach (var item in db.Class1.ToList()) { items.Add(new SelectListItem() { Text = item.Data, Value = item.Id.Value.ToString() }); } ViewBag.Class1s = items; } return(View()); }
public async Task When_deleteConfirmed_jobOffer_should_be_deleted() { var options = new DbContextOptionsBuilder <WebApplication1Context>().UseInMemoryDatabase(databaseName: "Test2").Options; using (var context = new WebApplication1Context(options)) { context.JobOffer.Add(new JobOffer() { Id = 1, JobTitle = "job1" }); context.JobOffer.Add(new JobOffer() { Id = 2, JobTitle = "job2" }); context.SaveChanges(); var controller = new JobOffersController(context); var result = await controller.DeleteConfirmed(1); Assert.Equal(1, context.JobOffer.Count()); } }
public IHttpActionResult PostRegister(LoginModel loginModel) { WebApplication1Context context = new WebApplication1Context(); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (loginModel.password != loginModel.password_validator) { string error = "Uhhhhh. I can't believe you've done this."; return(BadRequest(error)); } byte[] salt = LoginUtils.generateSalt(); byte[] saltPass = LoginUtils.hash(loginModel.password, salt); // Add validations! //WebApplication1Context context = new WebApplication1Context(); context.AccountsModel.Add( new AccountsModel { username = loginModel.username, email = loginModel.email, organizationId = loginModel.organization, Salt = salt, SaltedAndHashedPassword = saltPass, }); context.SaveChangesAsync(); return(Ok()); }
public static bool ValidateToken(string tokenInput, int idInput) { decryptTokenData data = LoginUtils.decryptToken(tokenInput); WebApplication1Context context = new WebApplication1Context(); byte[] checkHash = LoginUtils.hashNoSalt(data.token); TokenModel token = context.TokensModel.Where(a => a.tokenHash == checkHash).FirstOrDefault(); if (idInput == token.userid) { bool byteCheck = LoginUtils.SafeEquals(token.tokenHash, checkHash); if (byteCheck == true) { if (data.utcDateTime == token.tokenDate) // TODO -- Add expiry system! { return(true); } else { // TODO - Log the possiblilty of tampering with the user tokens. // This would mean the token had been decrypted and then had the date stamp edited. Suspicious activity! return(false); } } else { return(false); } } else { // if the given id is not the same as the one connected to the token fail! // saves on doing a byte check too! :) return(false); } }
public AddDataController(WebApplication1Context context) { _context = context; }
public MoviesController(WebApplication1Context context) { _context = context; }
public PokemonsController(WebApplication1Context context) { _context = context; }
public CommentsController(WebApplication1Context _context) { context = _context; }
public AccountsController(WebApplication1Context db) { this.db = db; }
public AccountsController() { db = new WebApplication1Context(); }
public ProductService(WebApplication1Context context) { _context = context; }
public DepartmentService(WebApplication1Context context) { _context = context; }
public SellerService(WebApplication1Context context) { _context = context; }