public static void CreateRole(WebAppContext context) { if (context == null) { throw new ArgumentNullException("context"); } using (var transaction = context.Database.BeginTransaction()) { try { IList <Role> roles = new List <Role>(); var appId = context.Application.Where(x => x.Description.Contains("melhorias")).FirstOrDefault().Id; if (context.Role.Where(i => i.Id == (int)RoleEnum.ADMIN).FirstOrDefault() == null) { roles.Add(new Role() { Code = RoleEnum.ADMIN.ToString(), Id = (int)RoleEnum.ADMIN, Application_Id = appId }); } if (context.Role.Where(i => i.Id == (int)RoleEnum.CONTRIBUTOR).FirstOrDefault() == null) { roles.Add(new Role() { Code = RoleEnum.CONTRIBUTOR.ToString(), Id = (int)RoleEnum.CONTRIBUTOR, Application_Id = appId }); } if (context.Role.Where(i => i.Id == (int)RoleEnum.PUBLIC).FirstOrDefault() == null) { roles.Add(new Role() { Code = RoleEnum.PUBLIC.ToString(), Id = (int)RoleEnum.PUBLIC, Application_Id = appId }); } if (context.Role.Where(i => i.Id == (int)RoleEnum.READER).FirstOrDefault() == null) { roles.Add(new Role() { Code = RoleEnum.READER.ToString(), Id = (int)RoleEnum.READER, Application_Id = appId }); } if (roles.Any()) { context.Role.AddRange(roles); context.SaveChanges(); } transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw; } } }
public void HandlePostBack() { if (WebAppContext.IsPost()) { HandlePostback(WebAppContext.FormData); } }
public IEnumerable <Pizza> GetAll() { using (var db = new WebAppContext()) { return(db.Pizzas.ToArray()); } }
public List <ViewFlight> getFlights(List <int> inList) { var db = new WebAppContext(); List <ViewFlight> list = new List <ViewFlight>(); foreach (var item in inList) { var oneFlight = db.Flight.Find(item); if (oneFlight == null) { return(null); } else { String depName = db.Airport.Where(a => a.ID == oneFlight.Departure).Select(a => a.Name).FirstOrDefault(); String destName = db.Airport.Where(a => a.ID == oneFlight.Destination).Select(a => a.Name).FirstOrDefault(); var returnFlight = new ViewFlight() { id = oneFlight.ID, departure = depName, departureTime = oneFlight.DepartureTime, destination = destName, destinationTime = oneFlight.DestinationTime, classType = oneFlight.ClassType, travelDate = oneFlight.TravelDate, price = oneFlight.Price }; list.Add(returnFlight); } } return(list); }
/// <summary>Create an HttpFS Server to talk to the MiniDFSCluster we created.</summary> /// <exception cref="System.Exception"/> private void CreateHttpFSServer() { FilePath homeDir = TestDirHelper.GetTestDir(); NUnit.Framework.Assert.IsTrue(new FilePath(homeDir, "conf").Mkdir()); NUnit.Framework.Assert.IsTrue(new FilePath(homeDir, "log").Mkdir()); NUnit.Framework.Assert.IsTrue(new FilePath(homeDir, "temp").Mkdir()); HttpFSServerWebApp.SetHomeDirForCurrentThread(homeDir.GetAbsolutePath()); FilePath secretFile = new FilePath(new FilePath(homeDir, "conf"), "secret"); TextWriter w = new FileWriter(secretFile); w.Write("secret"); w.Close(); // HDFS configuration FilePath hadoopConfDir = new FilePath(new FilePath(homeDir, "conf"), "hadoop-conf" ); if (!hadoopConfDir.Mkdirs()) { throw new IOException(); } string fsDefaultName = nnConf.Get(CommonConfigurationKeysPublic.FsDefaultNameKey); Configuration conf = new Configuration(false); conf.Set(CommonConfigurationKeysPublic.FsDefaultNameKey, fsDefaultName); // Explicitly turn off XAttr support conf.SetBoolean(DFSConfigKeys.DfsNamenodeXattrsEnabledKey, false); FilePath hdfsSite = new FilePath(hadoopConfDir, "hdfs-site.xml"); OutputStream os = new FileOutputStream(hdfsSite); conf.WriteXml(os); os.Close(); // HTTPFS configuration conf = new Configuration(false); conf.Set("httpfs.hadoop.config.dir", hadoopConfDir.ToString()); conf.Set("httpfs.proxyuser." + HadoopUsersConfTestHelper.GetHadoopProxyUser() + ".groups" , HadoopUsersConfTestHelper.GetHadoopProxyUserGroups()); conf.Set("httpfs.proxyuser." + HadoopUsersConfTestHelper.GetHadoopProxyUser() + ".hosts" , HadoopUsersConfTestHelper.GetHadoopProxyUserHosts()); conf.Set("httpfs.authentication.signature.secret.file", secretFile.GetAbsolutePath ()); FilePath httpfsSite = new FilePath(new FilePath(homeDir, "conf"), "httpfs-site.xml" ); os = new FileOutputStream(httpfsSite); conf.WriteXml(os); os.Close(); ClassLoader cl = Sharpen.Thread.CurrentThread().GetContextClassLoader(); Uri url = cl.GetResource("webapp"); if (url == null) { throw new IOException(); } WebAppContext context = new WebAppContext(url.AbsolutePath, "/webhdfs"); Org.Mortbay.Jetty.Server server = TestJettyHelper.GetJettyServer(); server.AddHandler(context); server.Start(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, WebAppContext dbcontext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); dbcontext.Database.EnsureDeleted(); dbcontext.Database.EnsureCreated(); new DBSeeder(dbcontext); }
public async Task <ActionResult> DeleteTemplate(long templateId) { try { TemplateViewModel templateViewModel; using (var context = new WebAppContext()) { templateViewModel = await context.TemplateJsons.FirstOrDefaultAsync(x => x.TemplateId == templateId); context.TemplateJsons.Attach(templateViewModel); context.TemplateJsons.Remove(templateViewModel); await context.SaveChangesAsync(); } return(RedirectToAction(templateViewModel.IsManageTemplate ? "ManageView" : "DeployView", "Deployment")); } catch (Exception ex) { ViewBag.ErrorMessage = "Error"; ViewBag.ErrorDetails = ex.Message; Log.Error(ex); return(View("Error")); } }
public GenericCacheRepository( WebAppContext context, IDistributedCache distributedCache ) : base(context) { _distributedCache = distributedCache; }
public Pizza Get(int id) { using (var db = new WebAppContext()) { return(db.Pizzas.FirstOrDefault(d => d.Id == id)); } }
public ActionResult Login(User u) { WebAppContext _db = new WebAppContext(); string message = ""; var rst = (from m in _db.User where m.login == u.login && m.password == u.password select m).FirstOrDefault(); if (rst != null) { Session["login"] = rst.login.ToString(); Session["role"] = rst.role.ToString(); Session["password"] = ""; return(RedirectToAction("PostLogin")); } else { message = "login failed"; } ViewBag.Message = message; // ModelState.AddModelError("", "login ou mot de passe non valide"); return(View()); }
public async Task <IActionResult> Show(string name) { using var _context = new WebAppContext(); var devicesMACList = await _context.UserDevices.Where(ud => ud.UserID == int.Parse(User.Identity.Name) && ud.OwnerID == int.Parse(User.Identity.Name)).Select(ud => ud.DeviceMAC).ToListAsync(); var devices = await _context.Devices.Where(d => devicesMACList.Contains(d.MAC)).ToListAsync(); var dev = devices.SingleOrDefault(d => d.Name == name); if (dev != null) { string MAC = dev.MAC; TempData["rooms"] = devices.Select(d => d.Room).Distinct().ToList(); var deviceShares = from d in _context.Users join ud in _context.UserDevices on d.ID equals ud.UserID where ud.UserID != int.Parse(User.Identity.Name) && ud.OwnerID == int.Parse(User.Identity.Name) && ud.DeviceMAC == MAC select d.Email; TempData["shares"] = deviceShares.ToList(); var device = devices.Single(d => d.Name == name); return(View(device)); } else { return(StatusCode(204)); //do nothing } }
public void ShouldReturnBadRequestIfTheUrlIsinvalidFormatlInRequest(SearchWidgetPageMode mode, string jobProfileUrl, HttpStatusCode expectation) { //Arrange var webAppContext = new WebAppContext(); // OUR SERVICE TYPE var searchQuery = A.Fake <ISearchQueryService <JobProfileIndex> >(); var mapper = A.Fake <IMapper>(); var applicationLogger = A.Fake <IApplicationLogger>(); var spellcheckerServiceFake = A.Fake <ISpellcheckService>(ops => ops.Strict()); var fakeAsyncHelper = new AsyncHelper(); var controller = new JobProfileSearchBoxController(searchQuery, webAppContext, mapper, applicationLogger, fakeAsyncHelper, spellcheckerServiceFake) { CurrentPageMode = mode }; switch (expectation) { case HttpStatusCode.NotFound: controller.WithCallTo(c => c.Search(string.Empty, jobProfileUrl)).ShouldGiveHttpStatus(expectation); break; case HttpStatusCode.Redirect: default: controller.WithCallTo(c => c.Search(string.Empty, jobProfileUrl)).ShouldRedirectTo($"{controller.JobProfileDetailsPage}{jobProfileUrl}"); break; } }
public JsonResult FindAirport(String Prefix) { var db = new WebAppContext(); var FoundAirport = (from f in db.Airport where f.Name.StartsWith(Prefix) select new { f.Name }); return(Json(FoundAirport, JsonRequestBehavior.AllowGet)); }
public async Task <int> UpdateName(string deviceID, string name) { using var _context = new WebAppContext(); var devicesList = await _context.UserDevices.Where(ud => ud.UserID == int.Parse(User.Identity.Name)).Select(ud => ud.DeviceMAC).ToListAsync(); var devices = await _context.Devices.Where(d => devicesList.Contains(d.MAC)).ToListAsync(); if (devices.Select(d => d.Name).ToList().Contains(name)) { return(-2); //name not unique } else { var device = devices.Single(d => d.MAC == deviceID); device.Name = name; try { await _context.SaveChangesAsync(); return(0); //name updated } catch (DbUpdateException ex) { Debug.WriteLine(ex.Message); return(-3); //db error } } }
private static Header PreLoadHeader(WebAppContext context) { Header header = new Header(); ValuePairList insunits = new ValuePairList(); insunits.Add(new ValuePair(9, "$INSUNITS")); insunits.Add(new ValuePair(70, "4")); header.AddVariable(insunits); float minX = float.PositiveInfinity; float minY = float.PositiveInfinity; float maxX = float.NegativeInfinity; float maxY = float.NegativeInfinity; foreach (LayoutData inst in context.sheetLayout) { DXFShape shape = context.shapes[inst.key].dxfBase; float unitScale = context.shapes[inst.key].getUnitScale(); { float x = float.Parse(shape.header.variableList["$EXTMIN"].Get(10).First()) * unitScale + inst.pos.X; float y = float.Parse(shape.header.variableList["$EXTMIN"].Get(20).First()) * unitScale + inst.pos.Y; minX = (x < minX) ? x : minX; minY = (y < minY) ? y : minY; } { float x = float.Parse(shape.header.variableList["$EXTMAX"].Get(10).First()) * unitScale + inst.pos.X; float y = float.Parse(shape.header.variableList["$EXTMAX"].Get(20).First()) * unitScale + inst.pos.Y; maxX = (x > maxX) ? x : maxX; maxY = (y > maxY) ? y : maxY; } } ValuePairList extMin = new ValuePairList(); extMin.Add(new ValuePair(9, "$EXTMIN")); extMin.Add(new ValuePair(10, minX.ToString())); extMin.Add(new ValuePair(20, minY.ToString())); header.AddVariable(extMin); ValuePairList extMax = new ValuePairList(); extMax.Add(new ValuePair(9, "$EXTMAX")); extMax.Add(new ValuePair(10, maxX.ToString())); extMax.Add(new ValuePair(20, maxY.ToString())); header.AddVariable(extMax); return(header); }
public async Task <int> AddDevice(string deviceID, string name, string room) { using var _context = new WebAppContext(); var device = await _context.Devices.SingleOrDefaultAsync(d => d.MAC == deviceID); if (device == null) { return(-1); //invalid ID } var userDevice = await _context.UserDevices.SingleOrDefaultAsync(ud => ud.DeviceMAC == deviceID); if (userDevice != null) { if (userDevice.OwnerID == int.Parse(User.Identity.Name)) { return(0); //already added } else { return(-4); } } var devicesList = await _context.UserDevices.Where(ud => ud.UserID == int.Parse(User.Identity.Name)).Select(ud => ud.DeviceMAC).ToListAsync(); var devicesName = await _context.Devices.Where(d => devicesList.Contains(d.MAC)).Select(d => d.Name).ToListAsync(); if (devicesName.Contains(name)) { return(-2); //name not unique } _context.UserDevices.Add(new UserDevices() { UserID = int.Parse(User.Identity.Name), DeviceMAC = deviceID, OwnerID = int.Parse(User.Identity.Name) }); device.SettingTime = DateTime.Now; device.Name = name; device.Room = room; try { await _context.SaveChangesAsync(); return(0); //added } catch (DbUpdateException ex) { Debug.WriteLine(ex.Message); return(-3); //db error } }
private static void AppendLine(WebAppContext context, ref LinkedList <char> fileStr, string line) { char[] charArray = line.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { fileStr.AddLast(charArray[i]); } }
private void updateSeats(List <Flight> inList, WebAppContext db, int travelers) { foreach (var i in inList) { var update = db.Flight.Find(i.ID); int seats = update.Seats; update.Seats = seats - travelers; } }
public bool IsValid(string username, string password) { using (var db = new WebAppContext()) // use your DbConext { // for the sake of simplicity I use plain text passwords // in real world hashing and salting techniques must be implemented return(db.Users.Any(u => u.UserName == username && u.Password == password)); } }
public async Task <User> AddUser(User user) { using (var appContext = new WebAppContext()) { appContext.Users.Add(user); await appContext.SaveChangesAsync(); } return(user); }
public DbTokenCache(WebAppContext db, IHttpContextAccessor httpContextAccessor) { this.BeforeAccess = BeforeAccessNotification; this.AfterAccess = AfterAccessNotification; this.BeforeWrite = BeforeWriteNotification; _db = db; db.Database.EnsureCreated(); _httpContextAccessor = httpContextAccessor; }
public override void SetUp() { base.SetUp(); mockRepository = MockRepository.GenerateStub<IBlogRepository>(); context = new WebAppContext(mockContext, mockRepository); Under_These_Conditions(); When(); }
private async Task <User> GetUserName(string userName) { User result = null; using (var appContext = new WebAppContext()) { result = await appContext.Users.FirstOrDefaultAsync(f => f.Name.ToLower() == userName.ToLower()); } return(result); }
public void Save(Pizza pizza) { using (var db = new WebAppContext()) { var isNew = pizza.Id == 0; db.Pizzas.Attach(pizza); db.Entry(pizza).State = isNew ? EntityState.Added : EntityState.Modified; db.SaveChanges(); } }
public void GetLoanDataofToday(int loanid) { using (WebAppContext cntxt = new WebAppContext()) { LoanMaster lnmodel = cntxt.LoanMasters.Find(loanid); if (lnmodel != null) { } } }
public async Task <IActionResult> UpdateAccount([Bind("ID, FirstName, LastName, Email, Password")] User user) { if (ModelState.IsValid) { using var _context = new WebAppContext(); var me = await _context.Users.FindAsync(int.Parse(User.Identity.Name)); if (me.Password != MD5Crypt.GetMD5Hash(user.Password)) { ModelState.AddModelError("Password", "Incorrect account password."); return(View(nameof(Update))); } if (me.Email != user.Email) { var userWithEmail = await _context.Users.SingleOrDefaultAsync(u => u.Email == user.Email); if (userWithEmail != null) { ModelState.AddModelError("Email", "Email is already taken."); return(View(nameof(Update))); } } me.FirstName = user.FirstName; me.LastName = user.LastName; me.Email = user.Email; try { await _context.SaveChangesAsync(); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, me.ID.ToString()), new Claim("FirstName", me.FirstName), new Claim("Email", me.Email), new Claim(ClaimTypes.Role, "User") }, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(RedirectToAction("Index")); } catch (DbUpdateException ex) { Debug.WriteLine(ex.Message); ModelState.AddModelError("", "There was an internal server error. Please try again later."); return(View(nameof(Update))); } } return(View(nameof(Update))); }
public static void AddPost(int userid, int categoryid, string content) { using var context = new WebAppContext(); Post post = new Post() { UserID = userid, CategoryID = categoryid, Content = content }; context.Posts.Add(post); context.SaveChanges(); }
public async Task <IActionResult> Update() { using var _context = new WebAppContext(); var user = await _context.Users.FindAsync(int.Parse(User.Identity.Name)); TempData["user"] = user; TempData["userPassword"] = new UserPassword() { ID = user.ID, OldPassword = user.Password }; return(View("Update")); }
public static void AddCategory(string name) { using var context = new WebAppContext(); PostCategory postCategory = new PostCategory() { Category = name }; context.PostCategory.Add(postCategory); context.SaveChanges(); }
public void Delete(int id) { using (var db = new WebAppContext()) { var pizza = db.Pizzas.Single(d => d.Id == id); FileServices.Delete(pizza.FileKey); db.Pizzas.Remove(pizza); db.SaveChanges(); } }
private IWebAppContextRepository GetInMemoryWebAppContextRepository() { DbContextOptions <WebAppContext> options; var builder = new DbContextOptionsBuilder <WebAppContext>(); #pragma warning disable CS0618 // Тип или член устарел builder.UseInMemoryDatabase(); #pragma warning restore CS0618 // Тип или член устарел options = builder.Options; WebAppContext personDataContext = new WebAppContext(options); personDataContext.Database.EnsureDeleted(); personDataContext.Database.EnsureCreated(); return(new WebAppContextRepository(personDataContext)); }