public JsonResult SaveCustomerData(Customer customer) { bool status = false; string message = ""; if (ModelState.IsValid) { using (TestDBEntities dc = new TestDBEntities()) { var query = dc.Customers.Where(a => a.Id == customer.Id).FirstOrDefault(); if (query == null) { customer.CreateDate = DateTime.Now; dc.Customers.Add(customer); } else { query.Name = customer.Name; query.Email = customer.Email; query.Country = customer.Country; query.ZipCode = customer.ZipCode; } dc.SaveChanges(); status = true; message = "Save Complete"; } } else { message = "Failed! Please try again"; } return(new JsonResult { Data = new { status = status, message = message } }); }
public JsonResult DeleteCustomer(Customer customer) { bool status = false; string message = ""; if (ModelState.IsValid) { using (TestDBEntities dc = new TestDBEntities()) { var query = dc.Customers.Where(a => a.Id == customer.Id).FirstOrDefault(); if (query != null) { dc.Customers.Remove(query); } dc.SaveChanges(); status = true; message = "Deleted Complete"; } } else { message = "Failed! Please try again"; } return(new JsonResult { Data = new { status = status, message = message } }); }
public int AddEmployee(Employee model) { using (var context = new TestDBEntities()) { if (model.Address != null) { Address objadd = new Address() { Details = model.Address.Details, Country = model.Address.Country, State = model.Address.State }; context.Addresses.Add(objadd); context.SaveChanges(); model.AddressId = objadd.Id; } Employee emp = new Employee() { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Code = model.Code, AddressId = model.AddressId //AddressId=_add.Id }; context.Employees.Add(emp); context.SaveChanges(); return(emp.Id); } }
public Guid AddDepartment(Department_dto department, string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var entity = mapper.Map <Department>(department); entity.ID = Guid.NewGuid(); db.Set <Department>().Add(entity); db.SaveChanges(); _loger.Info("Добавлено подразделение " + entity.ID + ". Строка подключения: " + db.Database.Connection.ConnectionString); return(entity.ID); } } catch (DataException ex) { _loger.Warn(ex, "Проблема добавления подразделения " + department.ToJson()); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время добавления подразделения что-то пошло совсем не так."); throw; } }
public void InstantiateIn(System.Web.UI.Control container) { ASPxListBox listbox = new ASPxListBox(); listbox.ClientInstanceName = "listbox"; listbox.Width = Unit.Parse("100%"); listbox.ID = "listBox"; listbox.SelectionMode = ListEditSelectionMode.CheckColumn; List <DictionaryItem> itemslist = new List <DictionaryItem>(); using (TestDBEntities entity = new TestDBEntities()) { itemslist = entity.DictionaryItem.Where(oo => oo.DictionaryItemCode.StartsWith(CodeCat) && oo.DictionaryItemCode.Length == 7).ToList(); } StringBuilder allitem = new StringBuilder(); foreach (DictionaryItem item in itemslist) { allitem.Append(item.DictionaryItemValue + ";"); } allitem.Remove(allitem.Length - 1, 1); listbox.Items.Add("(全选)", allitem.ToString()); foreach (DictionaryItem item in itemslist) { listbox.Items.Add(item.DictionaryItemName, item.DictionaryItemValue); } listbox.ClientSideEvents.SelectedIndexChanged = "OnListBoxSelectionChanged"; container.Controls.Add(listbox); }
public HttpResponseMessage LoadAllEmployees(string gender = "all") { try { using (TestDBEntities entities = new TestDBEntities()) { switch (gender.ToLower()) { case "all": return(Request.CreateResponse(HttpStatusCode.OK, entities.employees.ToList())); case "female": return(Request.CreateResponse(HttpStatusCode.OK, entities.employees.Where(e => e.Gender.ToLower() == "female").ToList())); case "male": return(Request.CreateResponse(HttpStatusCode.OK, entities.employees.Where(e => e.Gender.ToLower() == "male").ToList())); default: return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Value for gender must all, female, or male. '" + gender.ToLower() + "' is invaild.")); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public async Task <IHttpActionResult> EditHotel(int id, HotelViewModel hotel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } TestDBEntities db = new TestDBEntities(); var existingHotel = await db.Hotels.Where(h => h.ID == id).SingleOrDefaultAsync(); if (existingHotel == null) { return(BadRequest("Object not found")); } existingHotel.Name = hotel.Name; existingHotel.LastUpdate = DateTime.Now; db.Hotels.Attach(existingHotel); var entry = db.Entry(existingHotel); entry.Property(h => h.Name).IsModified = true; entry.Property(h => h.LastUpdate).IsModified = true; await db.SaveChangesAsync(); return(Ok()); }
public HttpResponseMessage UpdateEmployee([FromUri] int id, [FromBody] employee employee) { try { using (TestDBEntities entities = new TestDBEntities()) { var entity = entities.employees.FirstOrDefault(e => e.ID == id); if (entity == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with ID: " + id + " does not exist")); } else { entity.Name = employee.Name; entity.Department = employee.Department; entity.Salary = employee.Salary; entity.Gender = employee.Gender; entities.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, entity)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public async Task <IHttpActionResult> CreateHotel(HotelViewModel hotel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } TestDBEntities db = new TestDBEntities(); var exist = await db.Hotels .AnyAsync(h => h.Name.Equals(hotel.Name, StringComparison.InvariantCultureIgnoreCase)); if (exist) { return(BadRequest("Object already exist")); } var newHotel = new Hotel { Name = hotel.Name, Date = DateTime.Now, LastUpdate = DateTime.Now }; db.Hotels.Add(newHotel); await db.SaveChangesAsync(); var location = Request.RequestUri + newHotel.ID.ToString(); return(Created(location, newHotel)); }
public async Task <IHttpActionResult> GatAllHotels() { TestDBEntities db = new TestDBEntities(); var hotels = await db.Hotels.Select(h => new { h.ID, h.Name, h.Date, h.LastUpdate }).ToListAsync(); return(Ok(hotels)); }
public ActionResult Index(LoginModel model) { TestDBEntities dbContext = new TestDBEntities(); if (!ModelState.IsValid) { ModelState.AddModelError("", "Enter login Information please"); return(View()); } if (!IsUserExist(model.UserName, model.Password)) { // ModelState.AddModelError("","Not a Valid user"); return(View("Registration")); } else { int id = dbContext.LoginInfoes.Where(x => x.UserName == model.UserName).Select(x => x.UserId).FirstOrDefault(); return(RedirectToAction("UserDetails", "Home", new { id = id })); } return(View("Index")); }
public void DBNotEmptyTest() { using (var db = new TestDBEntities()) { Assert.IsTrue(db.Department.Any() && db.Employee.Any()); } }
public void EditDepartment(Department_dto department, string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var entity = mapper.Map <Department>(department); var originalEntity = db.Set <Department>().Where(el => el.ID == entity.ID).SingleOrDefault(); if (originalEntity == null) { throw new InvalidOperationException("Record is not found in storage"); } db.Entry(originalEntity).CurrentValues.SetValues(entity); db.SaveChanges(); _loger.Info("Отредактировано подразделение " + department.ID + ". Строка подключения: " + db.Database.Connection.ConnectionString); } } catch (DataException ex) { _loger.Warn(ex, "Проблема редактирования подразделения " + department.ToJson()); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время редактирования подразделения что-то пошло совсем не так."); throw; } }
public UserDataView GetUserDataView(string loginName) { UserDataView UDV = new UserDataView(); List <UserProfileView> profiles = GetAllUserProfiles(); List <LOOKUPAvailableRole> roles = GetAllRoles(); int? userAssignedRoleID = 0, userID = 0; string userGender = string.Empty; userID = GetUserID(loginName); using (TestDBEntities db = new TestDBEntities()) { userAssignedRoleID = db.SYSUserRoles.Where(o => o.SYSUserID == userID).FirstOrDefault().LOOKUPRoleID; userGender = db.SYSUserProfiles.Where(o => o.SYSUserID == userID).FirstOrDefault().Gender; } List <Gender> genders = new List <Gender>(); genders.Add(new Gender { Text = "Male", Value = "M" }); genders.Add(new Gender { Text = "Female", Value = "F" }); UDV.UserProfile = profiles; UDV.UserRoles = new UserRoles { SelectedRoleID = userAssignedRoleID, UserRoleList = roles }; UDV.UserGender = new UserGender { SelectedGender = userGender, Gender = genders }; return(UDV); }
public void DeleteDepartment(Department_dto department, string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var entity = db.Set <Department>().Where(el => el.ID == department.ID).SingleOrDefault(); var t = db.Set <Department>().Remove(entity); db.SaveChanges(); _loger.Info("Удалено подразделение " + department.ToJson() + ". Строка подключения: " + db.Database.Connection.ConnectionString); } } catch (DataException ex) { _loger.Warn(ex, "Проблема удаления подразделения " + department.ToJson()); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время удаления подразделения что-то пошло совсем не так."); throw; } }
public IHttpActionResult Get(string lastName = null, string firstName = null, int?departmentID = null, int?subDepartmentID = null) { TestDBEntities _entity = new TestDBEntities(); return(Ok(_entity.SelectEmployee(lastName, firstName, departmentID, subDepartmentID))); }
public bool IsLoginNameExist(string loginName) { using (TestDBEntities db = new TestDBEntities()) { return(db.SYSUsers.Where(o => o.LoginName.Equals(loginName)).Any()); } }
public int AddEmployee(Employee_dto employee, string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var entity = mapper.Map <Employee>(employee); db.Set <Employee>().Add(entity); db.SaveChanges(); _loger.Info("Добавлен сотрудник " + entity.ID + " в подразделение " + employee.DepartmentID + ". Строка подключения: " + db.Database.Connection.ConnectionString); return(entity.ID); } } catch (DataException ex) { _loger.Warn(ex, "Проблема добавления сотрудника " + employee.ToJson()); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время добавления сотрудника что-то пошло совсем не так."); throw; } }
public async Task <IHttpActionResult> GetAllFacilities() { TestDBEntities db = new TestDBEntities(); var facilities = await db.Facilities.Select(f => new { f.ID, f.Name }).ToListAsync(); return(Ok(facilities)); }
public static RedisMultiKeyBaseCache <Product> .RedisCacheItem ReadProductInfo(string KeyClass, Object Key) { using (var db = new TestDBEntities()) { int Id = Convert.ToInt32(Key); Product product = new Product(); if (KeyClass.ToLower().Equals("id")) { product = db.Products.Where(p => p.Id == Id).FirstOrDefault(); } else { product = db.Products.Where(p => p.ObjectId == Id).FirstOrDefault(); } var lKeys = new Dictionary <string, object> { { "Id", product.Id }, { "ObjectId", product.ObjectId } }; return(new RedisMultiKeyBaseCache <Product> .RedisCacheItem( lKeys, product, DateTime.MinValue)); } }
public IEnumerable <Department_dto> GetDepartmentStructureWithEmployees(string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var t = db.Department.Include(el => el.Employee).Where(d => !(d.ParentDepartmentID.HasValue)).AsNoTracking().ToList(); var result = mapper.Map <IEnumerable <Department_dto> >(t); _loger.Info("Запрошена структура предприятий. Строка подключения: " + db.Database.Connection.ConnectionString); return(result); } } catch (DataException ex) { _loger.Warn(ex, "Проблема запроса структуры подразделений."); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время запроса структуры подразделений произошла ошибка."); throw; } }
public IEnumerable <Employee_dto> GetEmployeesByDepartment(Guid departmentID, string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var t = db.Set <Employee>().Where(e => e.DepartmentID == departmentID).AsNoTracking() .ProjectTo <Employee_dto>(new MapperConfiguration(cfg => cfg.AddProfile <MapperProfile>())) .ToArray(); _loger.Info("Запрошен список сотрудников подразделения " + departmentID + ". Строка подключения: " + db.Database.Connection.ConnectionString); return(t); } } catch (DataException ex) { _loger.Warn(ex, "Проблема при получении списка сотрудников по GUID подразделения: " + departmentID); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время получения сотрудников подразделения произошла ошибка."); throw; } }
//******************************************************* public override string[] GetRolesForUser(string username) { TestDBEntities db = new TestDBEntities(); var kullanici = db.kullanici.FirstOrDefault(x => x.KullaniciAdi == username); return(new string[] { kullanici.Yetki }); }
public void DeleteEmployee(Employee_dto employee, string connectionString) { try { using (var db = TestDBEntities.FactoryMethod(connectionString)) { var entity = mapper.Map <Employee>(employee); db.Set <Employee>().Attach(entity); var t = db.Set <Employee>().Remove(entity); db.SaveChanges(); _loger.Info("Удален сотрудник " + employee.ToJson() + ". Строка подключения: " + db.Database.Connection.ConnectionString);; } } catch (DataException ex) { _loger.Warn(ex, "Проблема удаления сотрудника " + employee.ToJson()); var fault = GetExceptionMessage(ex); throw new FaultException <DefaultFault>(fault); } catch (Exception ex) { _loger.Error(ex, "Во время удаления сотрудника что-то пошло совсем не так."); throw; } }
public static Product ReadProductInfoFromId(int Key) { using (var db = new TestDBEntities()) { return(db.Products.Where(p => p.Id == Key).FirstOrDefault()); } }
public void DelStudentFromClass() { Console.WriteLine("Исключение ученика из класса"); Console.WriteLine("Введите id ученика: "); int idStudent = InsertNumber(); Console.WriteLine("Введите id класса: "); int idClass = InsertNumber(); if (IsHaveStudents(idStudent) && IsHaveClass(idClass)) { if (IsHaveStudentInClass(idStudent, idClass)) { using (TestDBEntities context = new TestDBEntities()) { Students selectStudent = context.Students .Where(s => s.StudentsId == idStudent && s.IsDelete == false) .FirstOrDefault(); selectStudent.ClassId = null; context.SaveChanges(); } Console.WriteLine("Ученик исключен из класса"); } } else { Console.WriteLine("Не существует указанного ученика или класса."); } }
/// <summary> /// Updates an employee with a new data /// </summary> /// <param name="employee"></param> public void EditEmployee(Empoyee employee) { using (TestDBEntities entities = new TestDBEntities()) { entities.Entry(employee).State = EntityState.Modified; entities.SaveChanges(); } }
/// <summary> /// 用一个foreach的函数填入相关信息 /// </summary> /// <returns></returns> public override System.Web.UI.Control Build() { base.Build(); ASPxPanel panel = new ASPxPanel(); ASPxCheckBox checkbox; ASPxHiddenField CBhiddenfield = new ASPxHiddenField(); ASPxHiddenField CBhiddenfieldc = new ASPxHiddenField(); ASPxHiddenField CBhiddenfieldall = new ASPxHiddenField(); CBhiddenfield.ClientInstanceName = "CBhiddenfield"; CBhiddenfield.Clear(); CBhiddenfieldc.ClientInstanceName = "CBhiddenfieldc"; CBhiddenfieldc.Clear(); CBhiddenfieldall.ClientInstanceName = "CBhiddenfieldall"; CBhiddenfieldall.Clear(); //先添加隐藏控件 panel.Controls.Add(CBhiddenfield); panel.Controls.Add(CBhiddenfieldc); panel.Controls.Add(CBhiddenfieldall); string selected = ModuleField.CurrentValue == null ? ModuleField.DefaultValue == null ? null : ModuleField.DefaultValue.ToString() : ModuleField.CurrentValue.ToString(); List <string> selectedlist = new List <string>(); if (selected != null) { string[] selectedarray = selected.Split(';'); selectedlist = selectedarray.ToList <string>(); } List <DictionaryItem> itemslist = new List <DictionaryItem>(); using (TestDBEntities entity = new TestDBEntities()) { itemslist = entity.DictionaryItem.Where(oo => oo.DictionaryItemCode.StartsWith(ModuleField.CodeCat) && oo.DictionaryItemCode.Length == 7).ToList(); } foreach (DictionaryItem item in itemslist) { checkbox = new ASPxCheckBox(); checkbox.Text = item.DictionaryItemName; checkbox.Value = item.DictionaryItemValue; CBhiddenfieldall.Add(item.DictionaryItemName, item.DictionaryItemValue); checkbox.ClientSideEvents.CheckedChanged = "function (s,e) {CBchange(s,e);}"; if (selected != null) { foreach (string defaultchecked in selectedlist) { if (item.DictionaryItemName == defaultchecked) { checkbox.Checked = true; CBhiddenfield.Add(item.DictionaryItemName, ""); CBhiddenfield.Add(item.DictionaryItemValue, ""); } } } panel.Controls.Add(checkbox); } //排列方式 return(panel); }
public ActionResult GetData() { using (TestDBEntities db = new TestDBEntities()) { List <tbl_Student> studentList = db.tbl_Student.ToList <tbl_Student>(); return(Json(new { data = studentList }, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// Returns a list of employees in a database /// </summary> /// <returns></returns> public List <Empoyee> GetEmployees() { IEnumerable <Empoyee> employees; using (TestDBEntities entities = new TestDBEntities()) { employees = entities.Empoyee; return(employees.ToList()); } }
public ActionResult ListItems() { List<MyItem> data = new List<MyItem>(); using ( var db = new TestDBEntities()) { var temp = db.Items.ToList(); foreach(Item itm in temp) { MyItem newitem = new MyItem(); newitem.ID = itm.ID; newitem.Value = itm.Value; data.Add(newitem); } } return View(data); }