public bool endreAnsattADMDetaljer(DBModel.Admin ansatt) { if (ansatt.AnsattId == null) { return false; } return true; }
protected void showIamgeByItemId(object sender, EventArgs e) { string searchKey = Request.Form[""]; getItemImagePath = DBModel.sharedDBModel().getImagePathWithItemId(searchKey); }
protected void SearchByItemId(string id) { searchResult = DBModel.sharedDBModel().getItemByItemId(id); }
public override void Commit() { DBModel.SubmitChanges(); }
public List <QResLessonDistribution> LessonInStudentStats(int classGroupId, int studentId, int lessonNum) { try { LoginController.checkOnAccess(this.Request.Headers); } catch (Exception ex) { throw ex; }; var db = new DBModel(); List <QResLessonDistribution> qDist = new List <QResLessonDistribution>(); try { int lessonId = GetLessonId(lessonNum, classGroupId); var results = from rq in db.ResultInQuestions where rq.LessonId == lessonId && rq.StudentId == studentId group rq by rq.QuestionNum into qRes select qRes; if (results.Any()) { foreach (var lesson in results) { qDist.Add(new QResLessonDistribution { QNum = lesson.Key, RightCount = 0, WrongCount = 0 }); foreach (var res in lesson) { if (res.Result == true) { qDist.Last().RightCount++; } else { qDist.Last().WrongCount++; }; } } ; //Adding empty question objects to fill up the list to 10 for (int i = qDist.Count; i < NUM_OF_QUESTIONS_IN_LESSON; i++) { qDist.Add(new QResLessonDistribution() { QNum = i + 1, RightCount = 0, WrongCount = 0 }); } ; } ; return(qDist); } catch (Exception ex) { throw ex; }; }
public ActionResult endreProdukt(DBModel.Product item, HttpPostedFileBase productBilde) { if (ModelState.IsValid) { if (Request.IsAuthenticated) { if (_adminBLL.erAnsatt(User.Identity.Name)) { if (productBilde != null && productBilde.ContentLength > 0) { using (MemoryStream ms = new MemoryStream()) { productBilde.InputStream.CopyTo(ms); item.Picture = ms.GetBuffer(); WebImage t = new WebImage(item.Picture); t.Resize(150, 113, true, false); item.Picture = t.GetBytes(); } } if (_produktBLL.endreProdukt(item)) return RedirectToAction("Produkt", "Admin"); return View(item); } return View(item); } } return View(item); }
public bool endreAnsattADMDetaljer(DBModel.Admin admin) { return _repository.endreAnsattADMDetaljer(admin); }
public bool endreProdukt(DBModel.Product item) { if (item.Title == "") return false; return true; }
// GET: Product public ActionResult Index() { using (DBModel dbmodel = new DBModel()) return(View(dbmodel.Products.ToList())); }
protected void Page_Load(object sender, EventArgs e) { theStaff = (staff)Session["Staff"]; allShop = DBModel.sharedDBModel().getAllShop(); }
private IJoinQuery <TResult> Join <TR, TKey, TResult>(string type, IQuery <TR> rightQuery, Expression <Func <T, TKey> > leftKeySelector, Expression <Func <TR, TKey> > rightKeySelector, Expression <Func <T, TR, TResult> > resultSelector) where TR : BaseDBModel, new() { var rightTableAlias = "t" + (JoinTableCount + 1); var dynamicParameters = new DynamicParameters(); dynamicParameters.AddDynamicParams(Param); var left = new JoinExpression(leftKeySelector, Map, dynamicParameters, DBModel.GetDBModel_SqlProvider()); var right = new JoinExpression(rightKeySelector, new Dictionary <string, string> { { "", rightTableAlias } }, dynamicParameters, DBModel.GetDBModel_SqlProvider()); StringBuilder sqlJoin = new StringBuilder(); foreach (var v in left.JoinDic) { if (sqlJoin.Length > 0) { sqlJoin.Append(" AND "); } sqlJoin.Append("("); sqlJoin.Append(v.Value); sqlJoin.Append("="); sqlJoin.Append(right.JoinDic[v.Key]); sqlJoin.Append(")"); } var joinStr = $"{JoinStr} {type} JOIN {DBTool.GetTableName(rightQuery.DBModel)} {rightTableAlias} ON {sqlJoin}"; var sel = new JoinResultMapExpression(resultSelector, Map, rightTableAlias, dynamicParameters, DBModel.GetDBModel_SqlProvider()); StringBuilder sqlWhere = new StringBuilder(Where); var where = new WhereExpression(rightQuery.WhereExpression, rightTableAlias, dynamicParameters, DBModel.GetDBModel_SqlProvider()); if (!string.IsNullOrEmpty(where.SqlCmd)) { if (sqlWhere.Length > 0) { sqlWhere.Append(" AND "); } sqlWhere.Append(where.SqlCmd); } return(new JoinQueryInfo <TResult>(DBModel, joinStr, JoinTableCount + 1, sel.MapList, sqlWhere.ToString(), dynamicParameters)); }
// Export Kenh 6 public ActionResult ExportDPSNACK3Report(DateTime?fromDate, DateTime?toDate) { using (DBModel db = new DBModel()) { var recoders = new List <Recoder_DongHo6>(); if (fromDate.HasValue && toDate.HasValue) { toDate = toDate.GetValueOrDefault(DateTime.Now.Date).Date.AddHours(23).AddMinutes(59); recoders = db.recoder_kenh6.Where(x => x.Thoigian <= toDate && x.Thoigian >= fromDate).ToList(); ViewBag.Recoders = recoders; ViewBag.fromDate = fromDate; ViewBag.toDate = toDate; } else { if (!fromDate.HasValue) { fromDate = DateTime.Now.Date; } if (!toDate.HasValue) { toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1); } if (toDate < fromDate) { toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1); } recoders = db.recoder_kenh6.Where(x => x.Thoigian <= toDate && x.Thoigian >= fromDate).ToList(); ViewBag.Recoders = recoders; ViewBag.fromDate = fromDate; ViewBag.toDate = toDate; } ExcelPackage.LicenseContext = LicenseContext.NonCommercial; ExcelPackage Ep = new ExcelPackage(); ExcelWorksheet Sheet = Ep.Workbook.Worksheets.Add("DP-SNACK-3 Report"); Sheet.Cells["A1"].Value = "Thời gian"; Sheet.Cells["B1"].Value = "Kwh"; int row = 2; foreach (var item in recoders) { Sheet.Cells[string.Format("A{0}", row)].Style.Numberformat.Format = "dd/MM/yyyy HH:mm:ss"; Sheet.Cells[string.Format("A{0}", row)].Value = item.Thoigian; Sheet.Cells[string.Format("B{0}", row)].Value = float.Parse(item.Kwh); row++; } Sheet.Column(1).Width = 50; Sheet.Column(2).Width = 40; Sheet.Cells["A1:B1"].Style.Font.Size = 12; Sheet.Cells["A1:B1"].Style.Font.Bold = true; Sheet.Column(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; Sheet.Cells["A:AZ"].AutoFitColumns(); Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AppendHeader("content-disposition", "attachment: filename=\"ReportDPSNACK3.xlsx\""); Response.BinaryWrite(Ep.GetAsByteArray()); Response.End(); } return(RedirectToAction("Kenh6", "Report")); }
public ProductCategoryDao() { db = new DBModel(); }
public bool leggTilNyttProdukt(DBModel.Product prod) { try { if (prod == null) { return false; } var nProd = db.Products.Create(); nProd.Productcategorynumber = prod.Productcategorynumber; nProd.Title = prod.Title; nProd.Productdescription = prod.Productdescription; nProd.Price = prod.Price; nProd.antall = prod.antall; nProd.Picture = prod.Picture; db.Products.Add(nProd); db.SaveChanges(); return true; } catch (System.Data.SqlClient.SqlException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (InvalidOperationException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (ArgumentException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (NullReferenceException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (SystemException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (Exception ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } return false; }
public HomeController(DBModel context) { _context = context; }
//metode for at ansatt kan endre detaljer public bool endreAnsatt(DBModel.Admin admin) { if (admin.AnsattId == null) return false; return true; }
public UnitOfWork() { _context = new DBModel(); }
public bool endreProdukt(DBModel.Product item) { return _repository.endreProdukt(item); }
public BrandDao() { db = new DBModel(); }
public ActionResult endreAnsattAdmDetaljer(DBModel.Admin ansatt,string stilling) { if (ModelState.IsValid) { if (!Request.IsAuthenticated) { return RedirectToAction("logginn", "Admin"); } ansatt.Stilling = stilling; var email = User.Identity.Name; if (_adminBLL.erAnsatt(email)) { if (_adminBLL.endreAnsattADMDetaljer(ansatt)) return RedirectToAction("Ansatte", "Admin"); } return RedirectToAction("Index", "Admin"); } return View(); }
public static int GetLastID(string tblName) { int id = 0; DBModel db = new DBModel(); switch (tblName.ToLower().Trim()) { case "language": var obj = db.languages.OrderByDescending(x => x.languages_pk).FirstOrDefault(); id = obj.languages_pk; id++; break; case "country": var obj_country = db.countries.OrderByDescending(x => x.country_pk).FirstOrDefault(); id = obj_country.country_pk; id++; break; case "subject_group": var obj_subject_group = db.subject_group.OrderByDescending(x => x.subject_group_pk).FirstOrDefault(); id = obj_subject_group.subject_group_pk; id++; break; case "degree_type": var obj_degree_type = db.degree_type.OrderByDescending(x => x.degree_type_pk).FirstOrDefault(); id = obj_degree_type.degree_type_pk; id++; break; case "sub_degree_type": var obj_sub_degree_type = db.sub_degree_type.OrderByDescending(x => x.sub_degree_type_pk).FirstOrDefault(); id = obj_sub_degree_type.sub_degree_type_pk; id++; break; case "study_area": var obj_study_area = db.study_areas.OrderByDescending(x => x.study_areas_pk).FirstOrDefault(); id = obj_study_area.study_areas_pk; id++; break; case "field_of_study": var obj_field_of_study = db.field_of_study.OrderByDescending(x => x.field_of_study_pk).FirstOrDefault(); id = obj_field_of_study.field_of_study_pk; id++; break; case "university_name": var obj_university_name = db.university_name.OrderByDescending(x => x.uni_pk).FirstOrDefault(); id = obj_university_name.uni_pk; id++; break; case "degree_data": var obj_degree_data = db.degree_data.OrderByDescending(x => x.degree_pk).FirstOrDefault(); id = obj_degree_data.degree_pk; id++; break; } return(id); }
public bool endreProdukt(DBModel.Product item) { try { if (item.Productid == 0 || item == null) { return false; } var prod = db.Products.Where(u => u.Productid == item.Productid).FirstOrDefault(); if (item != null) { prod.antall = +item.antallBestilt; prod.Picture = item.Picture; prod.Price = item.Price; prod.Title = item.Title; prod.Productdescription = item.Productdescription; prod.Productcategorynumber = item.Productcategorynumber; prod.Productid = item.Productid; db.SaveChanges(); return true; } return false; } catch (System.Data.SqlClient.SqlException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (InvalidOperationException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (ArgumentException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (NullReferenceException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (SystemException ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (Exception ex) { SWKP.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKP.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } return false; }
public RoomService(DBModel context) { _context = context; }
public override void DeleteEntity(T entity) { DBModel.GetTable <T>().DeleteOnSubmit(entity); }
public ProductDAO() { this.dBModel = new DBModel(); }
protected void Page_Load(object sender, EventArgs e) { theStaff = (staff)Session["Staff"]; searchResult = DBModel.sharedDBModel().getAllItems(); }
public UserRepository() { _userContext = new DBModel(); }
protected void SearchByItemName(string name) { searchResult = DBModel.sharedDBModel().getItemByItemName(name); }
public MainWindowViewModel() { model = new DBModel(this); TargetPressure = 40; }
public LoginDAO() { db = new DBModel(); }
public async Task CreateJsonFromDBFiles() { if (!File.Exists($"{_dbDirectory}/{_citiesDBName}")) { Console.WriteLine("Cities DB file not found!!!"); return; } //подготовим промежуточные данные Dictionary <string, Country> countryMap = new Dictionary <string, Country>(); Dictionary <string, State> stateMap = new Dictionary <string, State>(); Dictionary <string, District> districtMap = new Dictionary <string, District>(); int primaryIndex = 0; using (var file = new FileStream($"{_dbDirectory}/countryInfo.txt", FileMode.Open, FileAccess.Read)) { using (var reader = new StreamReader(file)) { string currentCountry = ""; do { currentCountry = await reader.ReadLineAsync(); if (!string.IsNullOrEmpty(currentCountry) && currentCountry[0] != '#') { var tables = currentCountry.Split('\t'); countryMap.Add(tables[0], new Country { CountryISOCode = tables[0], CountryName = tables[4], //States = new List<State>(), //Cities = new List<City>() }); } } while (!string.IsNullOrEmpty(currentCountry)); } } using (var file = new FileStream($"{_dbDirectory}/admin1CodesASCII.txt", FileMode.Open, FileAccess.Read)) { using (var reader = new StreamReader(file)) { string currentState = ""; do { currentState = await reader.ReadLineAsync(); if (!string.IsNullOrEmpty(currentState) && currentState[0] != '#') { var tables = currentState.Split('\t'); stateMap.Add(tables[0], new State { StateCode = tables[0].Split('.')[1], StateName = tables[2], StateAsciiName = tables[2], //Districts = new List<District>(), //Cities = new List<City>() }); } } while (!string.IsNullOrEmpty(currentState)); } } using (var file = new FileStream($"{_dbDirectory}/admin2Codes.txt", FileMode.Open, FileAccess.Read)) { using (var reader = new StreamReader(file)) { string currentDistrict = ""; do { currentDistrict = await reader.ReadLineAsync(); if (!string.IsNullOrEmpty(currentDistrict) && currentDistrict[0] != '#') { var tables = currentDistrict.Split('\t'); districtMap.Add(tables[0], new District { DistrictCode = tables[0].Split('.')[2], DistrictName = tables[2], DistrictAsciiName = tables[2], //Cities = new List<City>() }); } } while (!string.IsNullOrEmpty(currentDistrict)); } } //далее читаем основной файл с городами и заполняем класс DBModel DBModel dBModel = new DBModel(); dBModel.Countries = new List <Country>(); var separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0]; using (var file = new FileStream($"{_dbDirectory}/{_citiesDBName}", FileMode.Open, FileAccess.Read)) { using (var reader = new StreamReader(file)) { string currentCity = ""; do { currentCity = await reader.ReadLineAsync(); if (!string.IsNullOrEmpty(currentCity) && currentCity[0] != '#') { var tables = currentCity.Split('\t'); //получили данные о городе, заполним try { City newCity = new City { CityName = tables[2], CityAsciiName = tables[2], Latitude = Convert.ToDouble(tables[4].Replace('.', separator)), Longitude = Convert.ToDouble(tables[5].Replace('.', separator)), CountryCode = tables[8], AdminCode1 = tables[10], AdminCode2 = tables[11], TimeZone = tables[17] }; //ищем страну if (countryMap.ContainsKey(newCity.CountryCode)) { var country = dBModel.Countries.Where(c => c.CountryISOCode == newCity.CountryCode).FirstOrDefault(); if (country == null) { //добавим страну в список dBModel.Countries.Add(countryMap[newCity.CountryCode]); country = countryMap[newCity.CountryCode]; } if (!string.IsNullOrEmpty(newCity.AdminCode1)) { //город относится к области или штату //ищем область или штат if (stateMap.ContainsKey($"{newCity.CountryCode}.{newCity.AdminCode1}")) { if (country.States == null) { country.States = new List <State>(); } var state = country.States.Where(c => c.StateCode == newCity.AdminCode1).FirstOrDefault(); if (state == null) { //добавим штат или область в список country.States.Add(stateMap[$"{newCity.CountryCode}.{newCity.AdminCode1}"]); state = stateMap[$"{newCity.CountryCode}.{newCity.AdminCode1}"]; } if (!string.IsNullOrEmpty(newCity.AdminCode2)) { //город относится к району, найдем район if (districtMap.ContainsKey($"{newCity.CountryCode}.{newCity.AdminCode1}.{newCity.AdminCode2}")) { if (state.Districts == null) { state.Districts = new List <District>(); } var district = state.Districts.Where(c => c.DistrictCode == newCity.AdminCode2).FirstOrDefault(); if (district == null) { //добавим район в список state.Districts.Add(districtMap[$"{newCity.CountryCode}.{newCity.AdminCode1}.{newCity.AdminCode2}"]); district = districtMap[$"{newCity.CountryCode}.{newCity.AdminCode1}.{newCity.AdminCode2}"]; } //добавим город в район if (district.Cities == null) { district.Cities = new List <City>(); } district.Cities.Add(newCity); } } else { //город относится к области просто добавим в область if (state.Cities == null) { state.Cities = new List <City>(); } state.Cities.Add(newCity); } } } else { //город не относится к штату или области //просто добавим в список страны if (country.Cities == null) { country.Cities = new List <City>(); } country.Cities.Add(newCity); } } } catch (Exception ex) { ////TODO вставить логирование!!! Console.WriteLine($"ERROR! {ex.Message} ({ex.StackTrace})"); } } } while (!string.IsNullOrEmpty(currentCity)); } } using (FileStream fs = new FileStream("resultDB.json", FileMode.Create)) { //sorting dBModel.Countries.Sort((c, f) => c.CountryName.CompareTo(f.CountryName)); foreach (var country in dBModel.Countries) { country.States?.Sort((c, f) => c.StateName.CompareTo(f.StateName)); country.Cities?.Sort((c, f) => c.CityName.CompareTo(f.CityName)); country.States?.ForEach(c => { c.Districts?.Sort((f, g) => f.DistrictName.CompareTo(g.DistrictName)); c.Cities?.Sort((f, g) => f.CityName.CompareTo(g.CityName)); c.Districts?.ForEach(x => { x.Cities?.Sort((f, g) => f.CityName.CompareTo(g.CityName)); }); }); } await JsonSerializer.SerializeAsync <List <Country> >(fs, dBModel.Countries, new JsonSerializerOptions { WriteIndented = true, IgnoreNullValues = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); Console.WriteLine("Data has been saved to file"); } }
public List <memory> getAllMemory() { DBModel dBModel = new DBModel(); return(dBModel.memories.OrderBy(x => x.MEMORY1).ToList()); }
public LoginController(DBModel context) { _context = context; }
// //POST: //AddNewUser public async Task <ActionResult> AddNewUser(PostUsersViewModel model) { if (ModelState.IsValid) { using (DBModel db = new DBModel()) { //Check if Email or Username provided Exists var CheckEmailExists = db.AspNetUsers.Any(i => i.Email == model.Email || i.UserName == model.Email); var _action = "AddNewUser"; if (CheckEmailExists) { //Return error return(Json("User exists! Unable to create new user", JsonRequestBehavior.AllowGet)); } else { //Create User var PasswordResetCode = OTPGenerator.GetUniqueKey(6); string mixedOriginal = Shuffle.StringMixer(PasswordResetCode); var user = new ApplicationUser { UserName = model.Email, Email = model.Email, CompanyName = model.CompanyName, PhoneNumber = model.PhoneNumber, StaffNumber = model.StaffNumber, PasswordResetCode = Functions.GenerateMD5Hash(mixedOriginal), LastPasswordChangedDate = DateTime.Now }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //Add EMT user role UserManager.AddToRole(user.Id, model.UserRole); //Send Success Email to reset password with OTP string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", null, Request.Url.Scheme); var PasswordResetMessageBody = "Dear " + model.CompanyName + ", <br/><br/> You have been created as a user at Global Markets Onboarding Portal." + "<a href=" + callbackUrl + "> Click here to reset your password. </a> Your Reset Code is: " + mixedOriginal + " <br/><br/>" + "Kind Regards,<br/><img src=\"https://e-documents.stanbicbank.co.ke/Content/images/EmailSignature.png\"/>"; var PasswordResetEmail = MailHelper.SendMailMessage(MailHelper.EmailFrom, model.Email, "New User: Password Reset", PasswordResetMessageBody); if (PasswordResetEmail == true) { //Log email sent notification LogNotification.AddSucsessNotification(MailHelper.EmailFrom, PasswordResetMessageBody, model.Email, _action); } else { //Log Email failed notification LogNotification.AddFailureNotification(MailHelper.EmailFrom, PasswordResetMessageBody, model.Email, _action); } return(Json("success", JsonRequestBehavior.AllowGet)); } else { return(Json("Unable to create new user", JsonRequestBehavior.AllowGet)); } } } } else { return(Json("Invalid form input. Unable to create new user", JsonRequestBehavior.AllowGet)); } }
// //GET /Get Notifications List public List <UserListViewModel> GetInternalUsersList(string searchMessage, int jtStartIndex, int jtPageSize, int count, string jtSorting) { // Instance of DatabaseContext using (var db = new DBModel()) { var UserId = User.Identity.GetUserId(); IEnumerable <UserListViewModel> query = db.Database.SqlQuery <UserListViewModel>("SELECT u.Id, u.Email, u.PhoneNumber, u.CompanyName, u.DateCreated, u.UserName, s.StatusName, r.Name AS RoleName FROM AspNetUsers u LEFT JOIN AspNetUserRoles ur ON ur.UserId = u.Id LEFT JOIN AspNetRoles r ON r.Id = ur.RoleId INNER JOIN tblStatus s ON s.Id = u.Status WHERE u.Id <> '3c162824-045d-429a-b530-173adecb7585' AND r.Id NOT IN ('8f70018b-22c2-4ef8-b465-ceefc7df3afb','aa145382-378e-49df-bf06-c96e081d2466','d97260b8-3879-403e-9f08-b388e91c0a25', '4796025b-6669-4b61-88eb-23662e0aab58') ORDER BY u.DateCreated DESC OFFSET " + jtStartIndex + " ROWS FETCH NEXT " + jtPageSize + " ROWS ONLY;"); //Search if (!string.IsNullOrEmpty(searchMessage)) { query = db.Database.SqlQuery <UserListViewModel>("SELECT u.Id, u.Email, u.PhoneNumber, u.CompanyName, u.DateCreated, u.UserName, s.StatusName, r.Name AS RoleName FROM AspNetUsers u LEFT JOIN AspNetUserRoles ur ON ur.UserId = u.Id LEFT JOIN AspNetRoles r ON r.Id = ur.RoleId INNER JOIN tblStatus s ON s.Id = u.Status WHERE u.Email LIKE '%" + searchMessage + "%' OR u.UserName LIKE '%" + searchMessage + "%' OR u.CompanyName LIKE '%" + searchMessage + "%' ORDER BY u.DateCreated DESC OFFSET " + jtStartIndex + " ROWS FETCH NEXT " + jtPageSize + " ROWS ONLY;"); } else { query = query.OrderByDescending(p => p.Id); } //Sorting Ascending and Descending if (string.IsNullOrEmpty(jtSorting) || jtSorting.Equals("DateCreated ASC")) { query = query.OrderBy(p => p.DateCreated); } else if (jtSorting.Equals("DateCreated DESC")) { query = query.OrderByDescending(p => p.DateCreated); } else if (jtSorting.Equals("Email ASC")) { query = query.OrderBy(p => p.Email); } else if (jtSorting.Equals("Email DESC")) { query = query.OrderByDescending(p => p.Email); } else if (jtSorting.Equals("RoleName ASC")) { query = query.OrderBy(p => p.RoleName); } else if (jtSorting.Equals("RoleName DESC")) { query = query.OrderByDescending(p => p.RoleName); } else if (jtSorting.Equals("UserName ASC")) { query = query.OrderBy(p => p.UserName); } else if (jtSorting.Equals("UserName DESC")) { query = query.OrderByDescending(p => p.UserName); } else if (jtSorting.Equals("PhoneNumber ASC")) { query = query.OrderBy(p => p.PhoneNumber); } else if (jtSorting.Equals("PhoneNumber DESC")) { query = query.OrderByDescending(p => p.PhoneNumber); } else { query = query.OrderByDescending(p => p.Id); //Default! } return(count > 0 ? query.Skip(jtStartIndex).Take(count).ToList() //Paging : query.ToList()); //No paging } }
public bool leggTilNyttProdukt(DBModel.Product prod) { if (prod.Title == "") { return false; } return true; }
public string GenerarCodTicket(int codtipo) { string codticket = ""; int numero = 0; string numerodes = ""; switch (codtipo) { case 1: codticket = "QU"; break; case 2: codticket = "IN"; break; case 3: codticket = "WO"; break; case 4: codticket = "AC"; break; case 5: codticket = "QA"; break; case 6: codticket = "CL"; break; default: codticket = "RE"; break; } using (DBModel d = new DBModel()) { numero = d.Ticket.Where(x => x.codequipo == codtipo).Count(); numero = numero + 1; } if (numero < 10) { numerodes = "000000000" + numero.ToString(); } else if (numero >= 10 && numero < 100) { numerodes = "00000000" + numero.ToString(); } else if (numero >= 100 && numero < 1000) { numerodes = "0000000" + numero.ToString(); } else if (numero >= 1000 && numero < 10000) { numerodes = "000000" + numero.ToString(); } else if (numero >= 10000 && numero < 100000) { numerodes = "00000" + numero.ToString(); } else if (numero >= 100000 && numero < 1000000) { numerodes = "0000" + numero.ToString(); } else if (numero >= 1000000 && numero < 10000000) { numerodes = "000" + numero.ToString(); } else if (numero >= 10000000 && numero < 100000000) { numerodes = "00" + numero.ToString(); } else if (numero >= 100000000 && numero < 1000000000) { numerodes = "0" + numero.ToString(); } else { numerodes = numero.ToString(); } codticket = codticket + numerodes; return(codticket); }
public bool leggTilNyttProdukt(DBModel.Product prod ) { return _repository.leggTilNyttProdukt(prod); }
public ClassStats ClassStats(int classGroupId) { try { LoginController.checkOnAccess(this.Request.Headers); } catch (Exception ex) { throw ex; }; var db = new DBModel(); ClassStats cStats = new ClassStats { RDist = new List <LessonResDistribution>(), ADist = new List <LessonAttempts>() }; try { //Get all the records of the results in the class grouped by lesson, then grouped by student var results = from lc in db.LessonsToClasses where lc.ClassId == classGroupId join l in db.Lessons on lc.LessonId equals l.Id join rl in db.ResultInLessons on l.Id equals rl.LessonId join sc in db.StudentsToClasses on lc.ClassId equals sc.ClassId where sc.StudentId == rl.StudentId group rl by l.SeqNum into lRes select new { lRes.Key, studentsRes = from lrg in lRes group lrg by lrg.StudentId into studRes select studRes }; if (results.Any()) { List <double> avgRes; List <double> avgBestRes; /*------------------------------------------------------------------------------------------ * Lesson Results Distribution *------------------------------------------------------------------------------------------*/ //Loop through each lesson foreach (var lesson in results) { avgRes = new List <double>(); avgBestRes = new List <double>(); //Create lesson object cStats.RDist.Add(new LessonResDistribution { LNum = lesson.Key }); //Loop through each student's results in the lesson and calc his average and max results foreach (var res in lesson.studentsRes) { avgRes.Add(res.Average(x => x.Result)); avgBestRes.Add(res.Max(x => x.Result)); } ; //Calc overall 'average' and 'average best' results cStats.RDist.Last().AvgRes = avgRes.Average(); cStats.RDist.Last().AvgBestRes = avgBestRes.Average(); } ; //Adding empty lessons objects to fill up the list to 10 for (int i = cStats.RDist.Count; i < NUM_OF_LESSONS_IN_CLASS; i++) { cStats.RDist.Add(new LessonResDistribution() { LNum = i + 1, AvgRes = 0, AvgBestRes = 0 }); } ; /*------------------------------------------------------------------------------------------ * Lesson attempts and completion distribution *------------------------------------------------------------------------------------------*/ int passed; //Loop through each lesson foreach (var lesson in results) { passed = 0; //Create lesson object cStats.ADist.Add(new LessonAttempts { LNum = lesson.Key }); //Check each student's results to see if he passed the lesson foreach (var res in lesson.studentsRes) { if (res.Max(x => x.Result >= StudyController.MIN_RES_TO_PASS)) { passed++; } ; } ; cStats.ADist.Last().StFinished = passed; cStats.ADist.Last().StTried = lesson.studentsRes.Count(); } ; //Adding empty lessons objects to fill up the list to 4 for (int i = cStats.ADist.Count; i < NUM_OF_LESSONS_IN_CLASS; i++) { cStats.ADist.Add(new LessonAttempts() { LNum = i + 1, StFinished = 0, StTried = 0 }); } ; /*------------------------------------------------------------------------------------------- * Course average result *------------------------------------------------------------------------------------------*/ var query = from pc in db.ProgressInClasses where pc.ClassId == classGroupId select pc.Result; if (query.Any()) { cStats.AvgRes = (double)query.Average(); } else { cStats.AvgRes = 0; }; } else { cStats.AvgRes = 0; }; return(cStats); } catch (Exception ex) { throw ex; }; }
public bool endreAnsattDetaljer(DBModel.Admin Admin) { return _repository.endreAnsatt(Admin); }
public LessonStats LessonStats(int classGroupId, int lessonNum) { try { LoginController.checkOnAccess(this.Request.Headers); } catch (Exception ex) { throw ex; }; var db = new DBModel(); LessonStats lStats = new LessonStats { QLDist = new List <QResLessonDistribution>(), Students = new List <PersonDTO>() }; try { //Get all the records of the results in the lesson var results = from lc in db.LessonsToClasses where lc.ClassId == classGroupId join l in db.Lessons on lc.LessonId equals l.Id where l.SeqNum == lessonNum join rl in db.ResultInLessons on l.Id equals rl.LessonId join sc in db.StudentsToClasses on lc.ClassId equals sc.ClassId where sc.StudentId == rl.StudentId select rl; if (results.Any()) { //Get max result by student var studentsBestResults = from r in results group r by r.StudentId into stdRes select stdRes.Max(x => x.Result); //Count how many students achieved PASS result lStats.StFinished = 0; foreach (var stdRes in studentsBestResults) { if (stdRes >= StudyController.MIN_RES_TO_PASS) { lStats.StFinished++; } ; } ; //Getting questions results int lessonId = GetLessonId(lessonNum, classGroupId); var query = from rq in db.ResultInQuestions where rq.LessonId == lessonId group rq by rq.QuestionNum into qRes select qRes; foreach (var question in query) { lStats.QLDist.Add(new QResLessonDistribution { QNum = question.Key, RightCount = 0, WrongCount = 0 }); foreach (var res in question) { if (res.Result == true) { lStats.QLDist.Last().RightCount++; } else { lStats.QLDist.Last().WrongCount++; }; } ; } ; //Adding empty question objects to fill up the list to 10 for (int i = lStats.QLDist.Count; i < NUM_OF_QUESTIONS_IN_LESSON; i++) { lStats.QLDist.Add(new QResLessonDistribution() { QNum = i + 1, RightCount = 0, WrongCount = 0 }); } ; lStats.StTried = studentsBestResults.Count(); lStats.FinishedOfTriedPercent = (double)lStats.StFinished / (double)lStats.StTried; lStats.AvgBestRes = studentsBestResults.Average(); lStats.AvgRes = results.Average(x => x.Result); } else { lStats.SetDefaults(); }; //Build students list lStats.Students = GetStudentsList(classGroupId); return(lStats); } catch (Exception ex) { throw ex; }; }
public ActionResult endreAnsattDetaljer(DBModel.Admin admin) { if (ModelState.IsValid) { if (_adminBLL.endreAnsattDetaljer(admin)) return RedirectToAction("Index", "Admin"); } return View(admin); }
public StudentStats StudentStats(int classGroupId, int studentId) { try { LoginController.checkOnAccess(this.Request.Headers); } catch (Exception ex) { throw ex; }; var db = new DBModel(); StudentStats sStats = new StudentStats { RDist = new List <LessonResDistribution>() }; try { //Get all the records of the results in the class grouped by lesson, then grouped by student var results = from lc in db.LessonsToClasses where lc.ClassId == classGroupId join l in db.Lessons on lc.LessonId equals l.Id join rl in db.ResultInLessons on l.Id equals rl.LessonId where rl.StudentId == studentId group rl by l.SeqNum into lRes select lRes; if (results.Any()) { /*------------------------------------------------------------------------------------------ * Lesson Results Distribution *------------------------------------------------------------------------------------------*/ //Loop through each lesson and assign results foreach (var lesson in results) { sStats.RDist.Add(new LessonResDistribution { LNum = lesson.Key, AvgRes = lesson.Average(x => x.Result), BestRes = lesson.Max(x => x.Result) }); } ; //Adding empty lessons objects to fill up the list to 4 for (int i = sStats.RDist.Count; i < NUM_OF_LESSONS_IN_CLASS; i++) { sStats.RDist.Add(new LessonResDistribution() { LNum = i + 1, AvgRes = 0, BestRes = 0 }); } ; /*------------------------------------------------------------------------------------------- * Course average result *------------------------------------------------------------------------------------------*/ sStats.AvgRes = (from pc in db.ProgressInClasses where pc.ClassId == classGroupId && pc.StudentId == studentId select pc.Result).FirstOrDefault(); } else { sStats.AvgRes = 0; }; return(sStats); } catch (Exception ex) { throw ex; }; }
public ActionResult leggNyttProdukt(DBModel.Product prod,HttpPostedFileBase productBilde) { if (ModelState.IsValid) { if (productBilde != null && productBilde.ContentLength > 0) { using (MemoryStream ms = new MemoryStream()) { productBilde.InputStream.CopyTo(ms); prod.Picture = ms.GetBuffer(); WebImage t = new WebImage(prod.Picture); t.Resize(150, 113, true, false); prod.Picture = t.GetBytes(); } if (_produktBLL.leggTilNyttProdukt(prod)) return View(); } } return View(prod); }
public bool endreAnsattADMDetaljer(DBModel.Admin ansatt) { try { if (ansatt == null || ansatt.AnsattId == "") return false; var adm = db.Admins.FirstOrDefault(u => u.AnsattId == ansatt.AnsattId); adm.Epost = ansatt.Epost; adm.Firstname = ansatt.Firstname; adm.Lastname = ansatt.Lastname; adm.Stilling = ansatt.Stilling; db.SaveChanges(); return true; } catch (System.Data.SqlClient.SqlException ex) { SWKA.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKA.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (InvalidOperationException ex) { SWKA.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKA.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (ArgumentException ex) { SWKA.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKA.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (NullReferenceException ex) { SWKA.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKA.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (SystemException ex) { SWKA.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKA.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } catch (Exception ex) { SWKA.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); SWKA.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } return false; }