public ActionResult VerifyAccount(string id) { bool Status = false; using (ProjectDbContext db = new ProjectDbContext()) { db.Configuration.ValidateOnSaveEnabled = false; var check = db.Customers.Where(a => a.ActivitionCode == new System.Guid(id)).FirstOrDefault(); if (check != null) { check.IsEmailVarified = true; db.SaveChanges(); Status = true; } else { ViewBag.Message = "Invalid Request"; } } ViewBag.Status = true; return(View(Status)); }
public void importData(string path) { using (var db = new ProjectDbContext()) { StreamReader streamCsv = new StreamReader(path); string csvDataLine = ""; string[] data = null; var lineHeader = streamCsv.ReadLine(); while ((csvDataLine = streamCsv.ReadLine()) != null) { data = csvDataLine.Split(','); var newStatus = new Status { StatusId = data[0], Description = data[1], StatusName = data[2] }; db.Status.Add(newStatus); db.SaveChanges(); } } }
public ActionResult Login(UniversityManagementSystemWebApp.Models.UserAccount user) { using (ProjectDbContext db = new ProjectDbContext()) { var usr = db.UserAccounts.Where(u => u.UserName == user.UserName && u.Password == user.Password).FirstOrDefault(); if (usr == null) { ModelState.AddModelError("", "wrong user name or password"); return(View("Login")); } else { Session["UserId"] = usr.USerId.ToString(); Session["UserName"] = usr.UserName.ToString(); return(RedirectToAction("LoggedIn")); } } return(View()); }
public SubjectsController(ProjectDbContext context) { _context = context; if (context.Subjects.Count() == 0) { var subject1 = new Subject { Name = "Mates" }; subject1.Save(); } else if (context.Subjects.Count() == 1) { var subject1 = new Subject { Name = "Química" }; subject1.Save(); } }
public async Task <HttpResponseMessage> GetDataHistoryByStudentID([FromBody] History history) { HttpResponseMessage res = new HttpResponseMessage(); try { ProjectDbContext db = new ProjectDbContext(); List <History> data = (from ht in db.Historys where ht.day == history.day where ht.month == history.month where ht.year == history.year where ht.studentID == history.studentID select ht ).ToList(); res = Request.CreateResponse(HttpStatusCode.OK, data); } catch (Exception ex) { res = Request.CreateResponse(ex.Message); } return(await Task.FromResult(res)); }
protected override void OnStart(string[] args) { try { // Add code here to start your service. logger.Info($"Starting IntegrationService"); var updateIntervalString = ConfigurationManager.AppSettings["UpdateInterval"]; var updateInterval = 60000; Int32.TryParse(updateIntervalString, out updateInterval); var projectHost = ConfigurationManager.AppSettings["ProjectIntegrationServiceHost"]; var projectIntegrationApiService = new ProjectIntegrationApiService(new Uri(projectHost)); var projectDbContext = new ProjectDbContext(); var projectIntegrationService = new ProjectIntegrationService(projectIntegrationApiService, projectDbContext); timer = new System.Timers.Timer(); timer.AutoReset = true; var integrationProcessor = new IntegrationProcessor(updateInterval, projectIntegrationService, timer); timer.Start(); } catch (Exception e) { logger.Fatal(e); } }
public void Should_Return_Bad_Request_Create_Data() { ProjectDbContext projectDbContext = MemoryDbHelper.GetDB(Helper.GetCurrentMethod(ENTITY)); Mock <IBuyerFacade> mockBuyerFacade = new Mock <IBuyerFacade>(); mockBuyerFacade.Setup(p => p.Create(It.IsAny <Buyer>())) .Returns(0); Mock <IServiceProvider> mockServiceProvider = new Mock <IServiceProvider>(); mockServiceProvider.Setup(p => p.GetService(typeof(IBuyerFacade))).Returns(mockBuyerFacade.Object); mockServiceProvider.Setup(p => p.GetService(typeof(ProjectDbContext))).Returns(projectDbContext); Mock <IMapper> mockMapper = new Mock <IMapper>(); mockMapper.Setup(p => p.Map <Buyer>(It.IsAny <BuyerViewModel>())) .Returns(buyerDataUtil.GetModelData()); BuyersController buyersController = new BuyersController(mockServiceProvider.Object, mockMapper.Object) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() } }; buyersController.ControllerContext.HttpContext.Request.Path = new PathString("/v1/unit-test"); //Add data for make it double projectDbContext.Add(buyerDataUtil.GetModelData()); projectDbContext.SaveChanges(); BuyerViewModel viewModel = buyerDataUtil.GetViewModelData(); IActionResult result = buyersController.Post(viewModel); Assert.Equal(HttpStatusCode.BadRequest, (HttpStatusCode)((BadRequestObjectResult)result).StatusCode); }
/// <summary> /// Hàm cập nhật lịch sử /// </summary> /// <param name="carID"></param> public void UpdateHistory(string carID) { ProjectDbContext db = new ProjectDbContext(); CurrentState currentState = (from cs in db.CurrentStates where cs.carID == carID select cs ).First(); if (currentState != null) { History history = new History { carID = currentState.carID, coordinate = currentState.coordinate, location = currentState.location, speed = currentState.speed, state = currentState.state, studentID = currentState.studentID, studentName = currentState.studentName, exactTime = currentState.currentTime, day = currentState.currentTime.Day, month = currentState.currentTime.Month, year = currentState.currentTime.Year, historyID = Guid.NewGuid() }; db.Historys.Add(history); try { db.SaveChanges(); } catch (Exception ex) { return; } } return; }
public void importData(string path) { using (var db = new ProjectDbContext()) { StreamReader streamCsv = new StreamReader(path); string csvDataLine = ""; string[] data = null; var lineHeader = streamCsv.ReadLine(); while ((csvDataLine = streamCsv.ReadLine()) != null) { data = csvDataLine.Split(','); var newModule = new Module { ModuleId = data[0], Duration = Convert.ToByte(data[1]), ModuleName = data[2], Homework = Convert.ToByte(data[3]) }; db.Modules.Add(newModule); db.SaveChanges(); } } }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { var userId = User.Identity.GetUserId <int>(); var appDbContext = new ApplicationDbContext(); ViewBag.LoggedInUser = appDbContext.Users.Find(userId) != null && appDbContext.Users.Find(userId).UserType == (int)UserType.Customer? appDbContext.Users.Find(userId):null; var db = new ProjectDbContext(); var company = db.Company.FirstOrDefault(); ViewBag.CompanyName = company != null && company.CompanyName != null ? company.CompanyName : "Company Name"; ViewBag.CompanyEmail = company != null && company.EmailAddress != null ? company.EmailAddress : "Company Name"; ViewBag.CompanyAddress = company != null && company.Address != null ? company.Address : ""; ViewBag.Logo = company != null && company.ImageUrl != null ? company.ImageUrl : ""; ViewBag.FacebookUrl = company != null && company.FacebookUrl != null ? company.FacebookUrl : ""; ViewBag.InstagramUrl = company != null && company.InstagramUrl != null ? company.InstagramUrl : ""; ViewBag.TwitterUrl = company != null && company.TwitterUrl != null ? company.TwitterUrl : ""; ViewBag.CategoryList = db.ProductCategory.AsEnumerable(); ViewBag.ProductList = db.Product.AsEnumerable().Select(s => new VmProductList { ProductName = s.ProductName, ProductHeaderId = s.ProductHeaderId, Price = s.Rate.ToString("N2").Replace(",", "") }).ToList(); ViewBag.CompanyMobileNumber = company != null && company.MobileNumber != null ? company.MobileNumber : ""; ViewBag.RegisterdEmails = db.Customer.Select(s => s.EmalAddress).ToList(); base.OnActionExecuting(filterContext); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); // Own Account Table ProjectDbContext db = new ProjectDbContext(); AccountModels newAccount = new AccountModels(); newAccount.Account_email = model.Email; newAccount.AccountData = new AccountData(); newAccount.AccountData.Email = model.Email; db.Users.Add(newAccount); db.SaveChanges(); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // Aby uzyskać więcej informacji o sposobie włączania potwierdzania konta i resetowaniu hasła, odwiedź stronę https://go.microsoft.com/fwlink/?LinkID=320771 // Wyślij wiadomość e-mail z tym łączem // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Potwierdź konto", "Potwierdź konto, klikając <a href=\"" + callbackUrl + "\">tutaj</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Dotarcie do tego miejsca wskazuje, że wystąpił błąd, wyświetl ponownie formularz return(View(model)); }
public ActionResult Login(LoginViewModel lvm) { if (ModelState.IsValid) { var appDbContext = new ProjectDbContext(); var userStore = new ApplicationUserStore(appDbContext); var userManager = new ApplicationUserManager(userStore); var user = userManager.Find(lvm.Username, lvm.Password); if (user != null) { //login var authenticationManager = HttpContext.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties(), userIdentity); return(Redirect("/Home/Index")); } else { ModelState.AddModelError("myerror", "Invalid username or password"); return(View(lvm)); } } return(View(lvm)); }
public bool Update(TEntity entity) { try { using (var _context = new ProjectDbContext()) { _context.Entry(entity).State = EntityState.Modified; int res = _context.SaveChanges(); if (res > 0) { return(true); } return(false); } } catch (DbEntityValidationException e) { throw e; } catch (Exception ex) { throw ex; } }
public static void SendCallBackURL(string Email, string URL, ProjectDbContext db) { var settings = db.Settings.SingleOrDefault(); var webSiteName = settings.WebSiteName; var networkCredentinal_Username = settings.Credentials_Email; var networkCredentinal_Password = settings.Credentials_Password; MailMessage mail = new MailMessage(); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(Email); mail.Subject = webSiteName; mail.Body = "<h2>Şifre yenileme linki</h2><hr/>"; mail.Body += $"<a href='{URL}'> Şifre yenileme linki</a>"; mail.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential(networkCredentinal_Username, networkCredentinal_Password); smtpClient.EnableSsl = true; smtpClient.Send(mail); }
public StudentsController(ProjectDbContext context) { _context = context; if (context.Students.Count() == 0) { var std1 = new Student { Id = Guid.NewGuid(), Name = "Perico" }; var std2 = new Student { Id = Guid.NewGuid(), Name = "Lola" }; context.Students.Add(std1); context.Students.Add(std2); context.SaveChanges(); } }
public MstExpensesRepository(ProjectDbContext context, UserContext userContext) : base(context, userContext) { }
protected void CheckIfAllUsersAreDifferentThanLogged(User loggedUser, User[] selectedusers, ProjectDbContext db) { if (selectedusers.All(u => u.Id != loggedUser.Id)) { return; } Status = ActionStatus.UserIsSameAsLogged; throw new Exception("Nie możesz manipulować kontem na które jesteś zalogowany"); }
public void CheckIfNotAddedToFriends(UserToLoginViewModel loggedUser, User friend, ProjectDbContext db) { var dbLoggedUser = db.Users.Include(u => u.AddedToFriends).Single(u => u.Id == loggedUser.Id); var isAlreadyAddedToFriends = dbLoggedUser.HasAddedToFriends(friend); if (!isAlreadyAddedToFriends) { Status = ActionStatus.IsAlreadyFriend; throw new Exception("Użytkownik nie jest dodany do znajomych"); } }
public void CheckIfUserIsDifferentThanLogged(UserToLoginViewModel loggedUser, User friend, ProjectDbContext db) { var isUserSameAsLogged = friend.Id == loggedUser.Id; if (isUserSameAsLogged) { Status = ActionStatus.UserIsSameAsLogged; throw new Exception("Nie możesz manipulować kontem na które jesteś zalogowany"); } }
public string RenderNotificationsPanel() { var db = new ProjectDbContext(); Status = ActionStatus.None; try { CheckIfAjax(); var loggedUser = CheckIfLogged(); var dbLoggedUser = db.Users.Single(u => u.Id == loggedUser.Id); db.Entry(dbLoggedUser).Collection(u => u.ReceivedNotifications).Load(); var notifications = dbLoggedUser.ReceivedNotifications.ToList(); if (notifications.Count <= 0) { return(JsonConvert.SerializeObject(new { PartialView = RenderPartialView("_NotificationsPanel", notifications), Status = Enum.GetName(typeof(ActionStatus), ActionStatus.NoResults), Message = "Brak Wyników" })); } foreach (var notification in notifications) { var notificationEntry = db.Entry(notification); notificationEntry.Reference(n => n.FromUser).Load(); notificationEntry.Reference(n => n.ToUser).Load(); notificationEntry.Reference(n => n.Message).Load(); } notifications = notifications.OrderByDescending(n => n.Message.CreationTime).ToList(); return(JsonConvert.SerializeObject(new { PartialView = RenderPartialView("_NotificationsPanel", notifications), Status = Enum.GetName(typeof(ActionStatus), ActionStatus.Success), Message = "Poprawnie wczytano [_NotificationsPanel]" })); } catch (MySqlException) { return(JsonConvert.SerializeObject(new { Message = "Baza Danych nie odpowiada", Status = Enum.GetName(typeof(ActionStatus), ActionStatus.DatabaseError), })); } catch (Exception ex) { return(JsonConvert.SerializeObject(new { Message = ex.Message, Status = Enum.GetName(typeof(ActionStatus), Status == ActionStatus.None ? ActionStatus.Failure : Status) })); } }
public string GetFriendsPanel(Search search) { var db = new ProjectDbContext(); Status = ActionStatus.None; try { CheckIfAjax(); var authUser = CheckIfLogged(); CheckModelValidation(); var dbLoggedUser = db.Users.Include(u => u.AddedToFriends).Include(u => u.AddedAsFriendBy) .Single(u => u.Id == authUser.Id); var partialFriendsIds = dbLoggedUser.AddedToFriends.Select(u => u.Id) .Concat(dbLoggedUser.AddedAsFriendBy.Select(u => u.Id)).Distinct().ToArray(); var searchTerm = search.SearchTerm; var queryNotYetPartialFriends = db.Users .Where(u => partialFriendsIds.All(pfid => pfid != u.Id)) .Where(u => u.Id != authUser.Id); //.Include(u => u.Avatar); List <User> notYetPartialFriendsSearched = null; // TODO: Local IIS not stopping on breakpoints in cshtml if (!string.IsNullOrWhiteSpace(searchTerm)) { notYetPartialFriendsSearched = queryNotYetPartialFriends.Where(u => u.UserName.Contains(searchTerm)) .AsEnumerable().OrderBy(u => u?.UserName).ToList(); } var notYetPartialFriends = queryNotYetPartialFriends.ToList(); return(JsonConvert.SerializeObject(new { Status = Enum.GetName(typeof(ActionStatus), ActionStatus.Success), Message = "Poprawnie wyświetlono Panel Znajomych", ResultsCount = notYetPartialFriendsSearched?.Count ?? notYetPartialFriends.Count, PartialView = RenderPartialView("_FriendsPanel", notYetPartialFriendsSearched ?? notYetPartialFriends) })); } catch (ValidationException) { return(JsonConvert.SerializeObject(new { Status = Enum.GetName(typeof(ActionStatus), ActionStatus.ValidationError), Message = "Walidacja zwróciła błędy", ValidationErrors = GetValidationErrorList() })); } catch (MySqlException) { return(JsonConvert.SerializeObject(new { Message = "Baza Danych nie odpowiada", Status = Enum.GetName(typeof(ActionStatus), ActionStatus.DatabaseError), })); } catch (Exception ex) { return(JsonConvert.SerializeObject(new { Message = ex.Message, Status = Enum.GetName(typeof(ActionStatus), Status == ActionStatus.None ? ActionStatus.Failure : Status) })); } }
public QuestionService(ProjectDbContext projectDbContext) { _db = projectDbContext; }
//DI public EfAArticleCommentRepository(ProjectDbContext context) : base(context) { _context = context; }
public SastojiSeRepository(ProjectDbContext context) { dbCtx = context; }
public UploadController(ProjectDbContext context) { _context = context; }
public CommentsRepository() { this.db = new ProjectDbContext(); }
public DefaultTenantBuilder(ProjectDbContext context) { _context = context; }
/// <summary> /// Birden fazla türde nesneye ulaşmak isediğimiz için Repository yerine context'in kendisini alıyoruz. /// </summary> /// <param name="db"></param> public Handler(ProjectDbContext db) { this.db = db; }
public ProjectsController(ProjectDbContext context) { _context = context; }
public UserPermissionsController(ProjectDbContext context) { _context = context; }