private async Task TestUnsupportedTypes() { InvalidOperationException exception; // Verify that saving objects with invalid properties result in exceptions var employee2 = new Employee2 { Name = "Alan", Age = 31, TimeWithCompany = TimeSpan.FromDays(300) }; exception = await Assert.ThrowsAsync <InvalidOperationException>(() => SharedTestFixture.Context.SaveAsync(employee2)); Assert.Equal(exception.Message, "Type System.TimeSpan is unsupported, it cannot be instantiated"); var employee3 = new Employee3 { Name = "Alan", Age = 31, EmptyProperty = new EmptyType() }; exception = await Assert.ThrowsAsync <InvalidOperationException>(() => SharedTestFixture.Context.SaveAsync(employee3)); Assert.Equal(exception.Message, "Type Amazon.DNXCore.IntegrationTests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members"); // Verify that objects that are invalid result in exceptions exception = await Assert.ThrowsAsync <InvalidOperationException>(() => SharedTestFixture.Context.ScanAsync <TimeSpan>(new List <ScanCondition>(), null).GetNextSetAsync()); Assert.Equal(exception.Message, "Type System.TimeSpan is unsupported, it cannot be instantiated"); exception = await Assert.ThrowsAsync <InvalidOperationException>(() => SharedTestFixture.Context.ScanAsync <EmptyType>(new List <ScanCondition>(), null).GetNextSetAsync()); Assert.Equal(exception.Message, "Type Amazon.DNXCore.IntegrationTests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members"); }
public ActionResult RadioList_get() { // EmployeeContext emp = new EmployeeContext(); Employee2 emp = new Employee2("Sunil"); return(View(emp)); }
public int Save(Employee2 aEmployee) { SqlConnection con = new SqlConnection(connectionString); con.Open(); string sqlQuery = "insert into Employee2 (EmpID, EName,EFName, EMname, MAdd1, DisId, ThaID, DOb, ConNum1, ENID, PosID, JDate) values(@EmpID, @EmpName, @EmpEFName, @EMName, @MAdd1, @disId, @ThaID, @Dob, @ConNum1, @NID, @PID, @JDate) "; SqlCommand cmd = new SqlCommand(sqlQuery, con); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("EmpID", aEmployee.EmpID); cmd.Parameters.AddWithValue("EmpName", aEmployee.EName); cmd.Parameters.AddWithValue("EmpEFName", aEmployee.EFName); cmd.Parameters.AddWithValue("EMName", aEmployee.EMName); cmd.Parameters.AddWithValue("MAdd1", aEmployee.MAdd1); cmd.Parameters.AddWithValue("disId", aEmployee.DisID); cmd.Parameters.AddWithValue("ThaID", aEmployee.ThaID); cmd.Parameters.AddWithValue("Dob", aEmployee.DOB); cmd.Parameters.AddWithValue("ConNum1", aEmployee.ENID); cmd.Parameters.AddWithValue("NID", aEmployee.PosID); cmd.Parameters.AddWithValue("PID", aEmployee.PID); cmd.Parameters.AddWithValue("JDate", aEmployee.JDate); int rowCount = cmd.ExecuteNonQuery(); con.Close(); return(rowCount); }
public static void Run2() { Employee2 employee2 = new Employee2() { new Employee() { Name = "张三" }, new Employee() { Name = "李四" } }; ICollection <Employee> employees = employee2; employees.Add(new Employee() { Name = "王五" }); foreach (var item in employee2) { Console.WriteLine(item.Name); } // OutPut: // 张三Changed // 李四Changed // 王五Changed Console.ReadLine(); }
//strongly typed cpde: code iw written in view so that errors can be easily detected public ActionResult Index1() { // EmployeeContext emp = new EmployeeContext(); Employee2 emp = new Employee2("Sunil"); return(View(emp)); }
private static void TestUnsupportedTypes() { // Verify that saving objects with invalid properties result in exceptions var employee2 = new Employee2 { Name = "Alan", Age = 31, TimeWithCompany = TimeSpan.FromDays(300) }; AssertExtensions.ExpectException(() => Context.Save(employee2), typeof(InvalidOperationException), "Type System.TimeSpan is unsupported, it cannot be instantiated"); var employee3 = new Employee3 { Name = "Alan", Age = 31, EmptyProperty = new EmptyType() }; AssertExtensions.ExpectException(() => Context.Save(employee3), typeof(InvalidOperationException), "Type AWSSDK_DotNet.IntegrationTests.Tests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members"); // Verify that objects that are invalid result in exceptions AssertExtensions.ExpectException(() => Context.Scan <TimeSpan>(), typeof(InvalidOperationException), "Type System.TimeSpan is unsupported, it cannot be instantiated"); AssertExtensions.ExpectException(() => Context.Scan <EmptyType>(), typeof(InvalidOperationException), "Type AWSSDK_DotNet.IntegrationTests.Tests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members"); }
// GET: Employee public ActionResult Index(int p) { IEnumerable <Employee2> emp2 = new List <Employee2>(); Employee2 emp3 = new Employee2(); if (p == 0) { Employee emp = new Employee(); ViewBag.NameList = (from n in _stateRepo.GetNameList() select new SelectListItem { Text = n.Name, Value = n.Id.ToString() }).ToList(); emp2 = _stateRepo.GetList(); ViewBag.first = 0; return(View(emp2)); } else { ViewBag.NameList = (from n in _stateRepo.GetNameList() select new SelectListItem { Text = n.Name, Value = n.Id.ToString() }).ToList(); emp2 = _stateRepo.GetListSingle(p); ViewBag.first = 1; return(View(emp2)); } }
private static async Task TestUnsupportedTypes() { // Verify that saving objects with invalid properties result in exceptions var employee2 = new Employee2 { Name = "Alan", Age = 31, TimeWithCompany = TimeSpan.FromDays(300) }; await AssertExtensions.ExpectExceptionAsync <InvalidOperationException>(Context.SaveAsync(employee2), "Type System.TimeSpan is unsupported, it cannot be instantiated"); var employee3 = new Employee3 { Name = "Alan", Age = 31, EmptyProperty = new EmptyType() }; await AssertExtensions.ExpectExceptionAsync <InvalidOperationException>(Context.SaveAsync(employee3), "Type CommonTests.IntegrationTests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members"); // Verify that objects that are invalid result in exceptions AssertExtensions.ExpectException <InvalidOperationException>(() => Context.ScanAsync <TimeSpan>(new ScanCondition[] {}), "Type System.TimeSpan is unsupported, it cannot be instantiated"); AssertExtensions.ExpectException <InvalidOperationException>(() => Context.ScanAsync <EmptyType>(new ScanCondition[] { }), "Type CommonTests.IntegrationTests.DynamoDB.DynamoDBTests+EmptyType is unsupported, it has no supported members"); }
public static void Main() { /* Show that count is 0 before creating employees */ Console.WriteLine("Employees before instantiation: {0}", Employee2.Count); /* Create 2 Employees */ Employee2 e1 = new Employee2("Nordine", "Sebkhi"); Employee2 e2 = new Employee2("Marwan", "Chawqi"); /* Show count after creating employees */ Console.WriteLine("\nEmployees after instantiation: {0}", Employee2.Count); /* Get names of employees */ Console.WriteLine("\nEmployee 1: {0} {1}\nEmployee 2; {2} {3}\n", e1.FirstName, e1.LastName, e2.FirstName, e2.LastName); /* In this exple, there is only 1 reference to each Employee2, * So the following statement cause the CLR to mark each Employee2 object as being eligible for destruction */ e1 = null; e2 = null; /* Garbage Collector */ GC.Collect(); // Force Garbage Collection to occur now GC.WaitForPendingFinalizers(); // Wait until destructors finish writing to the console /* Show employee count after destruction occurred */ Console.WriteLine("\nEmployees after destruction: {0}", Employee2.Count); Console.ReadLine(); } // end method Main
// GET: Employee/Edit/5 public ActionResult Edit(int p) { Employee2 employee2 = new Employee2(); employee2 = _stateRepo.GetMethod(p).SingleOrDefault(); return(View(employee2)); }
private static void MultipleSourceCached(System.Random Rand) { foreach (Employee2 Employee2 in 100.Times(x => Rand.NextClass <Employee2>())) { using (Utilities.Profiler.Profiler Profiler = new Utilities.Profiler.Profiler("Multiple Source Cached Save")) { Employee2.Save(); } } for (int x = 0; x < 100; ++x) { using (Utilities.Profiler.Profiler Profiler = new Utilities.Profiler.Profiler("Multiple Source Cached All")) { Employee2.All(); } } for (int x = 0; x < 100; ++x) { using (Utilities.Profiler.Profiler Profiler = new Utilities.Profiler.Profiler("Multiple Source Cached Any")) { Employee2.Any(); } } for (int x = 0; x < 100; ++x) { using (Utilities.Profiler.Profiler Profiler = new Utilities.Profiler.Profiler("Multiple Source Cached Paged")) { Employee2.Paged(); } } }
public ActionResult DeleteConfirmed(int id) { Employee2 employee2 = db.Employee2.Find(id); db.Employee2.Remove(employee2); db.SaveChanges(); return(RedirectToAction("Index")); }
static void Main(string[] args) { Employee1 e1 = new Employee1(201, "mICHA", 20); Employee2 e2 = new Employee2(202, "mICHAl", 20); e1.display(); e2.display(); }
public JsonResult NameList(int NameCode) { Employee2 emp2 = new Employee2(); emp2 = _stateRepo.GetListSingle(NameCode).SingleOrDefault(); //return RedirectToAction("Index", new { p = NameCode }); return(Json(emp2, JsonRequestBehavior.AllowGet)); }
public ActionResult Edit([Bind(Include = "Id,Name,Designation,Salary")] Employee2 employee2) { if (ModelState.IsValid) { db.Entry(employee2).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(employee2)); }
public ActionResult Create([Bind(Include = "Id,Name,Designation,Salary")] Employee2 employee2) { if (ModelState.IsValid) { db.Employee2.Add(employee2); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(employee2)); }
public static void Demo1() { #region Dictionary <int, Employee> eDictionary1 = Employee.GetEmployeesArray().ToDictionary(k => k.id); eDictionary1.PrintArray(); Employee e1 = eDictionary1[2]; //Console.WriteLine("Employee whose id == 2 is {0} {1}", e1.firstName, e1.lastName); #endregion #region //--------------------------------------------------------------------------- Dictionary <string, Employee2> eDictionary2 = Employee2.GetEmployeesArray() .ToDictionary(k => k.id, new MyStringifiedNumberComparer()); Employee2 e2 = eDictionary2["2"]; //Console.WriteLine("Employee whose id == \"2\" : {0} {1}", // e2.firstName, e2.lastName); e2 = eDictionary2["000002"]; //Console.WriteLine("Employee whose id == \"000002\" : {0} {1}", // e2.firstName, e2.lastName); //---------------------------------------------------------------------------- #endregion #region Dictionary <int, string> eDictionary3 = Employee.GetEmployeesArray() .ToDictionary(k => k.id, i => string.Format("{0} {1}", // elementSelector i.firstName, i.lastName)); string name3 = eDictionary3[2]; //Console.WriteLine("Employee whose id == 2 is {0}", name3); //---------------------------------------------------------------------------- #endregion #region Dictionary <string, string> eDictionary4 = Employee2.GetEmployeesArray() .ToDictionary(k => k.id, // keySelector i => string.Format("{0} {1}", // elementSelector i.firstName, i.lastName), new MyStringifiedNumberComparer()); // comparer string name4 = eDictionary4["2"]; //Console.WriteLine("Employee whose id == \"2\" : {0}", name4); name4 = eDictionary4["000002"]; //Console.WriteLine("Employee whose id == \"000002\" : {0}", name4); #endregion }
public ActionResult Edit(int id, Employee2 employee2) { try { Int64 res = _stateRepo.UpdateMethod(employee2, id); return(RedirectToAction("Index", new { p = 0 })); } catch { return(View()); } }
// GET: Employee2/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Employee2 employee2 = db.Employee2.Find(id); if (employee2 == null) { return(HttpNotFound()); } return(View(employee2)); }
public string RadioList_post() { Employee2 employee = new Employee2("AA"); TryUpdateModel(employee); if (string.IsNullOrEmpty(employee.SelectedDept)) { return("No dept Selected"); } else { return("Dept Selected With ID:" + employee.SelectedDept); } }
public void Example() { Mapper.CreateMap <MyEnum1, MyEnum2>().ConvertUsing(new Enum1to2TypeConverter()); Mapper.CreateMap <Employee1, Employee2>(); Mapper.AssertConfigurationIsValid(); var source = new Employee1 { Id = 1, Name = "Employee1-Name", TestEnum = MyEnum1.yellow }; Employee2 result = Mapper.Map <Employee1, Employee2>(source); //Check content of result here! }
static void Main() { Employee2 e = new Employee2(); // The data members are inaccessible (private), so // they can't be accessed like this: // string n = e.name; // double s = e.salary; // 'name' is indirectly accessed via method: string n = e.GetName(); // 'salary' is indirectly accessed via property double s = e.Salary; }
public Int64 UpdateMethod(Employee2 employee2, int id) { var p = new DynamicParameters(); p.Add("Name", employee2.Name); p.Add("RegisterId", employee2.RegisterId); p.Add("Mobile", employee2.Mobile); p.Add("Id", id); p.Add("Result", dbType: DbType.Int64, direction: ParameterDirection.Output); const string storedProcedure = "Emp_Update"; var ret = con.Query <Employee2>(storedProcedure, p, commandType: CommandType.StoredProcedure); long Result = p.Get <long>("Result"); return(Result); }
public string saveEmployee(Employee2 aEmployee) { if (!EmpGetway.isExistEmpCode(aEmployee.EmpID)) { if (EmpGetway.Save(aEmployee) > 0) { return("Save Successfully"); } return("Error!! Not Save......."); } else { return("This Employee Id Already Exist"); } }
static void Main() { Employee2 e = new Employee2(); // The data members are inaccessible (private), so // they can't be accessed like this: // string n = e.name; // double s = e.salary; // 'name' is indirectly accessed via method: string n = e.GetName(); // 'salary' is indirectly accessed via property double s = e.Salary; }
public ActionResult Save(Employee2 aEmployee) { if (!ModelState.IsValid) { ViewBag.GetRole = aUserBll.GetUserRole(); ViewBag.District = aEmployeeBll.GetDistricts(); return(View()); } ViewBag.GetRole = aEmployeeBll.GetUserRole(); ViewBag.District = aEmployeeBll.GetDistricts(); ViewBag.Message = aEmployeeBll.saveEmployee(aEmployee); ModelState.Clear(); return(View()); }
public void Initialize() { main = new Main(); scrambled = new List <Employee2>(); sorted = new List <Employee2>(); em1 = new Employee2(3000); em2 = new Employee2(4000); em3 = new Employee2(7890); em4 = new Employee2(7890); em5 = new Employee2(10000); em6 = new Employee2(12345); em7 = new Employee2(14000); em8 = new Employee2(14000); em9 = new Employee2(15000); }
//[ValidateAntiForgeryToken] public async Task <IActionResult> EditPost(int id, [Bind("BusinessEntityID, LoginID, JobTitle, BirthDate, Gender, HireDate, ModifiedDate")] Employee2 employee) //moze bez binda przejdzie po wszystkich { if (ModelState.IsValid) { try { db.Employee2s.Update(employee); await db.SaveChangesAsync(); } catch (DbUpdateException) { ModelState.AddModelError("", _localizer["Data editing error"]); } } TempData["Info"] = _localizer["Employee edited:"] + " " + employee.LoginID; return(View(employee)); //dostajemy edytowanego pracownika, a nie niezmienionego }
static void Main(string[] args) { Employee2 myEmployee2 = new Employee2("Jose Jefferson"); Console.WriteLine("Employee Name: " + myEmployee2.Name); Console.WriteLine("Position: " + myEmployee2.Position); Console.WriteLine("Gross Pay: " + myEmployee2.GetGrossPay()); Console.WriteLine("Clothing Allowance: " + myEmployee2.GetClothing()); Console.WriteLine("Quarter Allowance: " + myEmployee2.GetQuarter()); Console.WriteLine("Laundry Allowance: " + myEmployee2.GetLaundry()); Console.WriteLine("PERA: " + myEmployee2.GetPera()); Console.WriteLine("Hazard Pay: " + myEmployee2.GetHazardPay()); Console.WriteLine("Long Pay: " + myEmployee2.GetLongPay()); Console.WriteLine("SGTI: " + myEmployee2.GetSGTI()); Console.WriteLine("Phil Health: " + myEmployee2.GetPhilHealth()); Console.WriteLine("Pag-ibig: " + myEmployee2.GetPagibig()); Console.WriteLine("Tax: " + myEmployee2.GetTax()); Console.WriteLine("Total Salary: " + myEmployee2.GetTotalSalary()); Console.WriteLine(); //NOTICE a lot will change, just by changing the Position and HireDate myEmployee2.Position = "INSP"; myEmployee2.HireDate = Convert.ToDateTime("01/08/1990"); Console.WriteLine("Employee Name: " + myEmployee2.Name); Console.WriteLine("Position: " + myEmployee2.Position); Console.WriteLine("Gross Pay: " + myEmployee2.GetGrossPay()); Console.WriteLine("Clothing Allowance: " + myEmployee2.GetClothing()); Console.WriteLine("Quarter Allowance: " + myEmployee2.GetQuarter()); Console.WriteLine("Laundry Allowance: " + myEmployee2.GetLaundry()); Console.WriteLine("PERA: " + myEmployee2.GetPera()); Console.WriteLine("Hazard Pay: " + myEmployee2.GetHazardPay()); Console.WriteLine("Long Pay: " + myEmployee2.GetLongPay()); Console.WriteLine("SGTI: " + myEmployee2.GetSGTI()); Console.WriteLine("PhilHealth: " + myEmployee2.GetPhilHealth()); Console.WriteLine("Pag-ibig: " + myEmployee2.GetPagibig()); Console.WriteLine("Tax: " + myEmployee2.GetTax()); Console.WriteLine("Total Salary: " + myEmployee2.GetTotalSalary()); Console.WriteLine("Press Any Key to exit"); Console.Read(); }
// Демонстрация работы с полями и свойствами /* Среда Visual Studio предлагает фрагмент кода prop. * Если вы наберете слово prop и два раза нажмете клавишу <ТаЬ>, * то IDE-среда сгенерирует начальный код для нового автоматического свойства. * Затем с помощью клавиши <ТаЬ> можно циклически проходить по всем частям * определения и заполнять необходимые детали. Испытайте описанный прием.*/ public static void Demo() { // первый способ Employee1 emp1 = new Employee1(); emp1.Name = "Bob"; emp1.Id = 1; // второй способ Employee2 emp2 = new Employee2(); emp2.Name = "Jane"; emp2.Id = 2; // третий способ (делает тоже, что и первый) - с версии C# 3.0 Employee3 emp3 = new Employee3 { Name = "Ohhh...", Id = 666 }; }
//[ValidateAntiForgeryToken] //AntiForgeryToken, zabezpiecza przed Cross-Site Request Forgery //zabezpieczenie na forumlarzach, żeby ktoś nie posiadając tokena nie puścił żądania w naszym kontekście bezpieczeństwa, //np. spreparowanym linkiem. Bez tokena nic nie zrobi //Cross-Site, czyli próby z innego serwisu wykonania akcji w naszym serwisie. public async Task <IActionResult> Create(Employee2 employee) { if (ModelState.IsValid) { try { db.Employee2s.Add(employee); await db.SaveChangesAsync(); } catch (DbUpdateException ex) { throw ex; } TempData["Info"] = _localizer["Employee added:"] + " " + employee.LoginID; return(RedirectToAction(nameof(Create))); } return(View(employee)); }
private static void TestUnsupportedTypes() { // Verify that saving objects with invalid properties result in exceptions var employee2 = new Employee2 { Name = "Alan", Age = 31, TimeWithCompany = TimeSpan.FromDays(300) }; AutoResetEvent ars = new AutoResetEvent(false); Context.SaveAsync <Employee2>(employee2, (result) => { var exception = result.Exception; Assert.AreEqual(typeof(InvalidOperationException), exception.GetType()); ars.Set(); }, options); ars.WaitOne(); var employee3 = new Employee3 { Name = "Alan", Age = 31, EmptyProperty = new EmptyType() }; Context.SaveAsync <Employee3>(employee3, (result) => { var exception = result.Exception; Assert.AreEqual(typeof(InvalidOperationException), exception.GetType()); ars.Set(); }, options); ars.WaitOne(); // Verify that objects that are invalid result in exceptions ExpectException <InvalidOperationException>(() => Context.ScanAsync <TimeSpan>(new ScanCondition[] { })); ExpectException <InvalidOperationException>(() => Context.ScanAsync <EmptyType>(new ScanCondition[] { })); }
private static void test_properties_without_parameters() { Employee e = new Employee(); e.Name = "Jeffrey Richter"; // Задаем имя сотрудника e.Age = 48; // Задаем возраст сотрудника Console.WriteLine(e.Name); // Выводим на экран "Jeffrey Richter" Employee1 e1 = new Employee1(); e1.SetName("Jeffrey Richter"); // Обновление имени сотрудника String EmployeeName = e1.GetName(); // Получение возраста сотрудника e1.SetAge(41); // Обновление возраста сотрудника e1.SetAge(-5); // Выдача исключения // ArgumentOutOfRangeException Int32 EmployeeAge = e1.GetAge(); // Получение возраста сотрудника Employee2 e2 = new Employee2(); e2.Name = "Jeffrey Richter"; // "Задать" имя сотрудника String EmployeeName2 = e2.Name; // "Получить" имя сотрудника e2.Age = 41; // "Задать" возраст сотрудника e2.Age = -5; // Вброс исключения // ArgumentOutOfRangeException Int32 EmployeeAge2 = e2.Age; // "Получить" возраст сотрудника Employee e3 = new Employee() { Name = "Jeff", Age = 45 }; String s = new Employee { Name = "Jeff", Age = 45 }.ToString().ToUpper(); Classroom classroom = new Classroom { Students = { "Jeff", "Kristin", "Aidan", "Grant" } }; // Вывести имена 4 студентов, находящихся в классе foreach (var student in classroom.Students) Console.WriteLine(student); var table = new Dictionary<String, Int32> {{ "Jeffrey", 1 }, { "Kristin", 2 }, { "Aidan", 3 }, { "Grant", 4 }}; // Определение типа, создание сущности и инициализация свойств var o1 = new { Name = "Jeff", Year = 1964 }; // Вывод свойств на консоль Console.WriteLine("Name={0}, Year={1}", o1.Name, o1.Year); // Выводит: // Name=Jeff, Year=1964 String Name = "Grant"; DateTime dt = DateTime.Now; // Анонимный тип с двумя свойствами // 1. Строковому свойству Name назначено значение Grant // 2. Свойству Year типа Int32 Year назначен год из dt var o2 = new { Name, dt.Year }; // Совпадение типов позволяет осуществлять операции сравнения и присваивания Console.WriteLine("Objects are equal: " + o1.Equals(o2)); o1 = o2; // Присваивание // Это работает, так как все объекты имею один анонимный тип var people = new[] { o1, // См. ранее в этом разделе new { Name = "Kristin", Year = 1970 }, new { Name = "Aidan", Year = 2003 }, new { Name = "Grant", Year = 2008 } }; // Организация перебора массива анонимных типов // (ключевое слово var обязательно). foreach (var person in people) Console.WriteLine("Person={0}, Year={1}", person.Name, person.Year); // String myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // var query = // from pathname in Directory.GetFiles(myDocuments) // let LastWriteTime = File.GetLastWriteTime(pathname) // where LastWriteTime > (DateTime.Now - TimeSpan.FromDays(7)) // orderby LastWriteTime // select new { Path = pathname, LastWriteTime }; // foreach (var file in query) // Console.WriteLine("LastWriteTime={0}, Path={1}", // file.LastWriteTime, file.Path); }