public void EntityStoredProcedure()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();

			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");
			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(emp);

			IQuery namedQuery = s.GetNamedQuery("selectAllEmployments");
			IList list = namedQuery.List();
			Assert.IsTrue(list[0] is Employment);
			s.Delete(emp);
			s.Delete(ifa);
			s.Delete(jboss);
			s.Delete(gavin);

			t.Commit();
			s.Close();
		}
Пример #2
0
        public async Task <StatusData <string> > UpdateEmployment(UpdateEmployeeRequest request, SystemSession session)
        {
            var serviceRequest = new Employment
            {
                Mode = (byte)SystemDbStatus.Updated,
                City = new City {
                    CityId = request.CityId
                },
                PersonEmploymentId = request.PersonEmploymentId,
                // RequestId = request.RequestId != 0 ? request.RequestId : 0,
                UserId       = session.UserId,
                EmployeeInfo = new CompanyEmployeeInfo {
                    CompanyId = request.CompanyId ?? 0, CompanyName = request.CompanyName, Position = request.Position, StartDate = request.StartDate.ToString(), EndDate = request.EndDate != null?request.EndDate.ToString() : null, EmployeeTypeId = (int)request.EmployeeTypeId
                }
            };
            var response = await Task.Factory.StartNew(() => Client.UserService.upsertEmployeementHistory(serviceRequest, session.GetSession())).ConfigureAwait(false);

            var result = new StatusData <string> {
                Status = (SystemDbStatus)response.DbStatus.DbStatusCode, Message = response.DbStatus.DbStatusMsg, SubStatus = response.DbStatus.DbSubStatusCode
            };

            if (!request.EndDate.HasValue && result.Status.IsOperationSuccessful())
            {
                var empSch = new EmployeeWorkScheduleUpdateRequest {
                    PersonEmploymentId = response.PersonEmploymentId, ScheduleType = request.WorkSchedule.ScheduleType, Schedules = request.WorkSchedule.Schedules
                };
                await UpdateEmployeeWorkSchedule(empSch, session).ConfigureAwait(false);
            }

            return(result);
        }
Пример #3
0
        public async Task ResultSetMappingDefinitionAsync()
        {
            ISession     s     = OpenSession();
            ITransaction t     = s.BeginTransaction();
            Organization ifa   = new Organization("IFA");
            Organization jboss = new Organization("JBoss");
            Person       gavin = new Person("Gavin");
            Employment   emp   = new Employment(gavin, jboss, "AU");

            await(s.SaveAsync(ifa));
            await(s.SaveAsync(jboss));
            await(s.SaveAsync(gavin));
            await(s.SaveAsync(emp));

            IList l = await(s.CreateSQLQuery(OrgEmpRegionSQL)
                            .SetResultSetMapping("org-emp-regionCode")
                            .ListAsync());

            Assert.AreEqual(l.Count, 2);

            l = await(s.CreateSQLQuery(OrgEmpPersonSQL)
                      .SetResultSetMapping("org-emp-person")
                      .ListAsync());
            Assert.AreEqual(l.Count, 1);

            await(s.DeleteAsync(emp));
            await(s.DeleteAsync(gavin));
            await(s.DeleteAsync(ifa));
            await(s.DeleteAsync(jboss));

            await(t.CommitAsync());
            s.Close();
        }
Пример #4
0
        public async Task <IActionResult> AddEmployment(Employment item, long oldEmploymentId)
        {
            item.IsActive = true;
            _context.Employments.Add(item);

            //deactivate old employment
            _context.Employments.SingleOrDefault(b => b.Id == oldEmploymentId).IsActive = false;

            //add transfer type promotion
            EmployeePromotion promo = new EmployeePromotion();

            promo.EmploymentId      = item.Id;
            promo.PromotionTypeId   = _lookup.GetLookupItems <PromotionType>().SingleOrDefault(b => b.SysCode == "TRANS").Id;
            promo.BasicSalary       = item.BasicSalary;
            promo.CreatedDate       = DateTime.Now.Date;
            promo.Details           = item.Details;
            promo.EffectiveFromDate = item.FromDate;
            promo.IsActive          = true;
            promo.IsApproved        = false;
            promo.JobGradeId        = item.JobGradeId;
            promo.LastUpdated       = DateTime.Now.Date;
            promo.SalaryStepId      = item.SalaryStepId;
            promo.UpdatedBy         = "user";
            _context.EmployeePromotions.Add(promo);

            await _context.SaveChangesAsync();

            return(RedirectToAction("EmploymentsList", new { id = item.EmployeeId }));
        }
Пример #5
0
        private bool AddEmployeeDapper(Employment e, SqlConnection con)
        {
            long BankAccountId = SelectLastBankAccountNextID(con);
            long ContractId    = SelectLastContractNextID(con);
            long PersonId      = SelectLastPersonNextID(con);

            string queryBankAccount = "INSERT INTO [dbo].[BankAccounts] ( [BankName], [BankAddress], [AccountNumber], [DataState], [CreateDate], [EditDate])" +
                                      " VALUES (@BankName, @BankAddress,@AccountNumber,@DataState,@CreateDate, @EditDate)";
            var su = con.Execute(queryBankAccount, new { e.BankAccount.BankName, e.BankAccount.BankAddress, e.BankAccount.AccountNumber, e.BankAccount.DataState, e.BankAccount.CreateDate, e.BankAccount.EditDate });

            string queryContract = "INSERT INTO [dbo].[Contracts] ( [StartDate], [EndDate], [ContractType], [ContractDimension], [MonthBenefit], [BenefitPerHour], [DataState], [CreateDate], [EditDate])" +
                                   " VALUES ( @StartDate, @EndDate, @ContractType, @ContractDimension, @MonthBenefit, @BenefitPerHour,@DataState, @CreateDate, @EditDate)";

            su = con.Execute(queryContract, new { e.Contract.StartDate, e.Contract.EndDate, e.Contract.ContractType, e.Contract.ContractDimension, e.Contract.MonthBenefit, e.Contract.BenefitPerHour, e.Contract.DataState, e.Contract.CreateDate, e.Contract.EditDate });

            AddPersonDapper(e.Person, con);

            string query = "INSERT INTO [dbo].[Employments] ( [PositionCode], [OrganiziationalUnitCode], [EmploymentType], [StartDate], [EndDate], [DataState], [CreateDate], [EditDate], [BankAccountId], [ContractId], [PersonId])" +
                           " VALUES ( @PositionCode, @OrganiziationalUnitCode, @EmploymentType, @StartDate, @EndDate, @DataState, @CreateDate, @EditDate, @BankAccountId, @ContractId, @PersonId)";

            su = con.Execute(query, new { e.PositionCode, e.OrganiziationalUnitCode, e.EmploymentType, e.StartDate, e.EndDate, e.DataState, e.CreateDate, e.EditDate, BankAccountId, ContractId, PersonId });


            return(true);
        }
Пример #6
0
        public Employment Get(int id)
        {
            Employment employmentObj = new Employment();

            try
            {
                FinancialPlanner.Common.JSONSerialization jsonSerialization = new FinancialPlanner.Common.JSONSerialization();
                string apiurl = Program.WebServiceUrl + "/" + string.Format(GET_EMPLOYMENT_API, id);

                RestAPIExecutor restApiExecutor = new RestAPIExecutor();

                var restResult = restApiExecutor.Execute <Employment>(apiurl, null, "GET");

                if (jsonSerialization.IsValidJson(restResult.ToString()))
                {
                    employmentObj = jsonSerialization.DeserializeFromString <Employment>(restResult.ToString());
                }
                return(employmentObj);
            }
            catch (Exception ex)
            {
                Logger.LogDebug(ex);
                return(null);
            }
        }
Пример #7
0
        public bool DeleteWorker(string pesel)
        {
            Worker worker = db.Workers.FirstOrDefault(w => w.Pesel == pesel);

            if (worker == null)
            {
                return(false);
            }
            int id = worker.IdWorker;

            IQueryable <Software> softwares = db.Softwares.Where(s => s.Workers_IdWorker == id);
            IQueryable <Hardware> hardwares = db.Hardwares.Where(h => h.Workers_IdWorker == id);

            foreach (Software software in softwares)
            {
                software.Worker = null;
            }

            foreach (Hardware hardware in hardwares)
            {
                hardware.Worker = null;
            }

            Employment employment = db.Employments.FirstOrDefault(e => e.Workers_IdWorker == id);
            Account    account    = db.Accounts.FirstOrDefault(a => a.Workers_IdWorker == id);

            db.Employments.Remove(employment);
            db.Accounts.Remove(account);
            db.Workers.Remove(worker);
            db.SaveChanges();
            return(true);
        }
Пример #8
0
        private static void SetElementView(List <ScheduleLesson> LessonsByView, string nameElementProjection,
                                           ScheduleClasses.View view, ScheduleWeeks Shedule, DataGridView table, Employments Employments, bool watchAll)
        {
            for (int Hour = 1; Hour <= Shedule.Setting.CountLessonsOfDay; Hour++)
            {
                DataGridViewRow row = CreateNewRow(table, nameElementProjection, ScheduleTime.GetHourDiscription(Hour));

                for (int Week = 1, CellIndex = 2; Week <= Shedule.Setting.CountWeeksShedule; Week++)
                {
                    for (int Day = 1; Day <= Shedule.Setting.CountDaysEducationWeek; Day++, CellIndex++)
                    {
                        //время занятия на 1-2 недели
                        ScheduleTime Time1 = new ScheduleTime((Week)Week, (ScheduleClasses.Day)Day, Hour);
                        //время занятия на 3-4 недели
                        ScheduleTime Time2 = GetTimeAfterTwoWeek(Time1);

                        //занятие на 1-2 недели
                        ScheduleLesson item1 = Shedule.FindLessonInList(LessonsByView, Time1);
                        //занятие на 3-4 недели
                        ScheduleLesson item2 = Shedule.FindLessonInList(LessonsByView, Time2);

                        string Room1 = item1 != null ? item1.Room : String.Empty;
                        string Room2 = item2 != null ? item2.Room : String.Empty;

                        Employment employmentCell = FindEmployment(view, Employments, nameElementProjection, Time1);

                        string cellContent = item1 == null && item2 == null ? String.Empty : IsLessonsEqualAndNonEmpty(item1, item2) ?
                                             GetCellContentIdenticalLessons(view, item1) : GetCellContentDiffrentLessons(view, item1, item2);

                        // задать значения ячейки в
                        DataGridViewCell cell = row.Cells[CellIndex];
                        cell.Value = cellContent;
                        cell.Tag   = new SchedulePointer(Time1, Time2, Room1, Room2);
                        // задать цвет и стиль ячейке
                        if (cellContent != String.Empty)
                        {
                            cell.Style.BackColor = IsLessonsEqualAndNonEmpty(item1, item2) ? Color.LightGreen : Color.LightGreen;
                        }

                        if (employmentCell != null && employmentCell.Reason == ReasonEmployment.UserBlocked)
                        {
                            SetCellBlockedStyle(cell);
                        }
                    }
                }

                if (watchAll || (!watchAll && Shedule.Lessons.Where(x => x.Hour == Hour && !x.IsEmpty).Count() > 0))
                {
                    table.Rows.Add(row);
                }
            }

            //добавить разделитель
            int index = table.Rows.GetLastRow(DataGridViewElementStates.None);

            if (index >= 0)
            {
                table.Rows[index].DividerHeight = 3;
            }
        }
Пример #9
0
        //[Authorize(Roles = "SuperUser")]
        public async Task <ActionResult <EmploymentDTO> > EmployUser(EmploymentDTO employmentDTO)
        {
            //Use Identity Role to check if logged user is a superuser
            //Can wire up the AUTHORIZE attribute or custom check using the HttpClient object
            //if (currentUser.Role != superUser)
            //{
            //    _logger.LogWarning("Hack Attempt");
            //    return BadRequest();
            //}

            var employment = new Employment
            {
                UserId         = employmentDTO.UserId,
                EmployerId     = employmentDTO.EmployerId,
                IsSuperUser    = employmentDTO.IsSuperUser,
                AssignmentDate = DateTime.UtcNow
            };

            try
            {
                _context.Employments.Add(employment);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                _logger.LogError("Error occurred while Employing a User");
                throw;
            }

            return(CreatedAtAction("EmployUser", new { id = employment.Id }, ConvertEmployment(employment)));
        }
Пример #10
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,EmployerName,Address,City,State,ZipCode,PhoneNum")] Employment employment)
        {
            if (id != employment.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(employment);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmploymentExists(employment.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(employment));
        }
		public void RefCursorOutStoredProcedure()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();

			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Person kevin = new Person("Kevin");
			Employment emp = new Employment(gavin, jboss, "AU");
			Employment emp2 = new Employment(kevin, ifa, "EU");
			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(kevin);
			s.Save(emp);
			s.Save(emp2);

			IQuery namedQuery = s.GetNamedQuery("selectEmploymentsForRegion");
			namedQuery.SetString("regionCode", "EU");
			IList list = namedQuery.List();
			Assert.That(list.Count, Is.EqualTo(1));
			s.Delete(emp2);
			s.Delete(emp);
			s.Delete(ifa);
			s.Delete(jboss);
			s.Delete(kevin);
			s.Delete(gavin);

			t.Commit();
			s.Close();
		}
Пример #12
0
        /// <summary>
        /// Gets a money amount at random based on the age and either the
        /// employment history or location of the opes options
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        protected internal virtual Pecuniam GetRandomExpectedIncomeAmount(AmericanDomusOpesOptions options)
        {
            options = options ?? AmericanDomusOpesOptions.RandomOpesOptions();

            var dt = options.Inception == DateTime.MinValue ? DateTime.Today : options.Inception;

            var age = options.FactorOptions.GetAge();

            var ageAtDt = age <= 0 ? AmericanData.AVG_AGE_AMERICAN : age;

            //get something randome near this value
            var randRate = GetRandomRateFromClassicHook(ageAtDt);

            //its income so it shouldn't be negative by definition
            if (randRate <= 0D)
            {
                return(Pecuniam.Zero);
            }

            //get some base to calc the product
            var someBase = Employment.Any()
                           ? GetAnnualEmplyGrossIncome(dt)
                           : options.GetRandomYearlyIncome(dt);

            var randAmt = someBase.ToDouble() * randRate;

            return(randAmt.ToPecuniam());
        }
 internal void getData()
 {
     allemployes  = eds.intializeEmploy();
     IntroTitle   = allemployes.title;
     Description0 = allemployes.description0;
     Description1 = allemployes.description1;
 }
Пример #14
0
        public async Task <IActionResult> Post([FromBody] Employment employment)
        {
            _db.Add(employment);
            await _db.SaveChangesAsync();

            return(Ok(employment));
        }
        public ActionResult ConfrmDeleteEmployment(Employment employment)
        {
            bool status = false;

            if (Session["employmentLst"] == null)
            {
                Session["employmentLst"] = new List <Employment>();
            }
            var employments = (List <Employment>)Session["employmentLst"];
            var emp         = employments.Where(x => x.Id == employment.Id).FirstOrDefault();

            if (emp != null)
            {
                employments.Remove(emp);
                status = true;
            }
            else
            {
                //education.Id = educations.Count() + 1;
                //educations.Add(education);
                //status = true;
            }
            return(new JsonResult {
                Data = new { status = status }
            });
        }
Пример #16
0
        public async Task <IActionResult> Edit(int id, Employment entry)
        {
            if (id != entry.Id)
            {
                return(NotFound());
            }
            var employment = _context.Employment.FirstOrDefault(s => s.Id == id);

            if (ModelState.IsValid)
            {
                try
                {
                    employment.FinishDate = entry.FinishDate;
                    _context.Update(employment);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmploymentExists(employment.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["EmployeeId"] = new SelectList(_context.Employee, "Id", "FullName", employment.EmployeeId);
            ViewData["ShopId"]     = new SelectList(_context.Shop, "Id", "Name", employment.ShopId);
            return(View(employment));
        }
        public async Task EntityStoredProcedureAsync()
        {
            ISession     s = OpenSession();
            ITransaction t = s.BeginTransaction();

            Organization ifa   = new Organization("IFA");
            Organization jboss = new Organization("JBoss");
            Person       gavin = new Person("Gavin");
            Employment   emp   = new Employment(gavin, jboss, "AU");

            await(s.SaveAsync(ifa));
            await(s.SaveAsync(jboss));
            await(s.SaveAsync(gavin));
            await(s.SaveAsync(emp));

            IQuery namedQuery = s.GetNamedQuery("selectAllEmployments");
            IList  list       = await(namedQuery.ListAsync());

            Assert.IsTrue(list[0] is Employment);
            await(s.DeleteAsync(emp));
            await(s.DeleteAsync(ifa));
            await(s.DeleteAsync(jboss));
            await(s.DeleteAsync(gavin));

            await(t.CommitAsync());
            s.Close();
        }
Пример #18
0
        private PersonalAssistant checkEmployee(PersonalAssistant pa)
        {
            if (pa.EmploymentTimes == null)
            {
                pa.EmploymentTimes = new List <Employment>();
                Employment e = new Employment();
                DateTime   d = DateTime.Now;
                e.EmplBegin = d;
                pa.EmploymentTimes.Add(e);
            }
            else if (pa.EmploymentTimes.Count == 0)
            {
                Employment e = new Employment();
                DateTime   d = DateTime.Now;
                e.EmplBegin = d;
                pa.EmploymentTimes.Add(e);
            }

            if (pa.EmploymentTimes.Last().EmplBegin.Year == 1)
            {
                pa.EmploymentTimes.Last().EmplBegin = DateTime.Now;
            }
            PaDao.update(pa);
            return(pa);
        }
Пример #19
0
        public async Task RefCursorOutStoredProcedureAsync()
        {
            ISession     s = OpenSession();
            ITransaction t = s.BeginTransaction();

            Organization ifa   = new Organization("IFA");
            Organization jboss = new Organization("JBoss");
            Person       gavin = new Person("Gavin");
            Person       kevin = new Person("Kevin");
            Employment   emp   = new Employment(gavin, jboss, "AU");
            Employment   emp2  = new Employment(kevin, ifa, "EU");

            await(s.SaveAsync(ifa));
            await(s.SaveAsync(jboss));
            await(s.SaveAsync(gavin));
            await(s.SaveAsync(kevin));
            await(s.SaveAsync(emp));
            await(s.SaveAsync(emp2));

            IQuery namedQuery = s.GetNamedQuery("selectEmploymentsForRegion");

            namedQuery.SetString("regionCode", "EU");
            IList list = await(namedQuery.ListAsync());

            Assert.That(list.Count, Is.EqualTo(1));
            await(s.DeleteAsync(emp2));
            await(s.DeleteAsync(emp));
            await(s.DeleteAsync(ifa));
            await(s.DeleteAsync(jboss));
            await(s.DeleteAsync(kevin));
            await(s.DeleteAsync(gavin));

            await(t.CommitAsync());
            s.Close();
        }
Пример #20
0
        public async Task <ActionResult <Employment> > PostEmployment(Employment employment)
        {
            _context.Employments.Add(employment);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetEmployment", new { id = employment.Id }, employment));
        }
Пример #21
0
        public void Update(EmploymentSaveDto employment)
        {
            Employment emp = mapper.Map <Employment>(employment);

            repository.Update(emp);
            unitOfWork.Commit();
        }
Пример #22
0
        public void CreateBusinessCard(Person person, Employment employment)
        {
            using (var connection = CreateConnection())
            {
                try
                {
                    _cmd             = new SqlCommand(USP_ADD_PERSON_EMPLOYMENTS, connection);
                    _cmd.CommandType = CommandType.StoredProcedure;

                    // Add the parameters to feed the stored procedure.
                    _cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 20).Value = person.FirstName;
                    _cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 20).Value  = person.LastName;
                    _cmd.Parameters.Add("@ConvenDate", SqlDbType.DateTime).Value   = DateTime.Today;

                    for (int i = 0; i < employment.CompanyIDs.Length; i++)
                    {
                        _cmd.Parameters.Add(String.Format("CompanyID{0}", i), SqlDbType.Int, 4).Value = employment.CompanyIDs[i];
                    }

                    // Open database connection
                    connection.Open();

                    // The stored procedure with (INSERT) does not return any posts -> ExecuteNonQuery is used to execute the stored procedure.
                    _cmd.ExecuteNonQuery();
                }
                catch
                {
                    throw new ApplicationException("An error occured in the data access layer.");
                }
            }
        }
Пример #23
0
        public async Task <IActionResult> PutEmployment(int id, Employment employment)
        {
            if (id != employment.Id)
            {
                return(BadRequest());
            }

            _context.Entry(employment).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmploymentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #24
0
        public List <Child> GetChildren(Employment employment)
        {
            var children = new List <Child>();

#if !DEBUG
            using (var webService = new GetChildren.GetChildren_OS_SIClient("HTTPS_Port2"))
            {
                var certName = ConfigurationManager.AppSettings["PROTECTED_CERTIFICATE_NAME"];
                webService.ClientCredentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, certName);

                var request = new GetChildren.GetChildrenRequest();
                request.PersonnelNumber = employment.EmploymentId.ToString();

                var response = webService.GetChildren_OS_SI(request);

                foreach (var child in response.Child)
                {
                    children.Add(new Child
                    {
                        Id        = int.Parse(child.ChildNumber),
                        FirstName = child.FirstName,
                        LastName  = child.LastName
                    });
                }
            }
#endif
            return(children);
        }
Пример #25
0
        public async Task <ActionResult <Team> > CreateTeam([FromBody] NewTeam newTeam)
        {
            var user = await _timelineContext.Users.Where(x => x.Id == newTeam.UserId)
                       .FirstOrDefaultAsync();

            if (user == null)
            {
                return(BadRequest());
            }

            var team = newTeam.Team;

            team.InviteToken = Guid.NewGuid();
            team.Owner       = user;
            team.Employments = new List <Employment>();
            if (user.Employments == null)
            {
                user.Employments = new List <Employment>();
            }

            var employment = new Employment {
                UserId = user.Id, TeamId = team.Id
            };

            team.Employments.Add(employment);
            user.Employments.Add(employment);

            _timelineContext.Teams.Add(team);
            await _timelineContext.SaveChangesAsync();

            Console.WriteLine("Created Team");

            return(Ok(team));
        }
Пример #26
0
        public Employment Get(int Id)
        {
            try
            {
                Logger.LogInfo("GET: Employment process start.");
                Employment employment = new Employment();

                DataTable dtAppConfig = DataBase.DBService.ExecuteCommand(string.Format(SELECT_CLIENT_EMPLOYMENT_ID, Id));
                foreach (DataRow dr in dtAppConfig.Rows)
                {
                    employment.ClientEmployment = convertToClientEmploymentObject(dr);
                }

                dtAppConfig = DataBase.DBService.ExecuteCommand(string.Format(SELECT_SPOUSE_EMPLOYMENT_ID, Id));
                foreach (DataRow dr in dtAppConfig.Rows)
                {
                    employment.SpouseEmployment = convertToSpouseEmploymentObject(dr);
                }
                return(employment);

                Logger.LogInfo("GET: Employment process completed.");
            }
            catch (Exception ex)
            {
                DebuggerLogInfo debuggerInfo = new DebuggerLogInfo();
                debuggerInfo.ClassName = this.GetType().Name;
                StackTrace st = new StackTrace();
                StackFrame sf = st.GetFrame(0);
                MethodBase currentMethodName = sf.GetMethod();
                debuggerInfo.Method        = currentMethodName.Name;
                debuggerInfo.ExceptionInfo = ex;
                Logger.LogDebug(debuggerInfo);
                return(null);
            }
        }
Пример #27
0
        public void CheckWorkers()
        {
            foreach (Worker worker in db.Workers)
            {
                Employment tmpEmployment = db.Employments.Find(worker.IdWorker);
                if (tmpEmployment.EndDate != null)
                {
                    if (tmpEmployment.EndDate < DateTime.Now.Date)
                    {
                        int id = worker.IdWorker;

                        IQueryable <Software> softwares = db.Softwares.Where(s => s.Workers_IdWorker == id);
                        IQueryable <Hardware> hardwares = db.Hardwares.Where(h => h.Workers_IdWorker == id);

                        foreach (Software software in softwares)
                        {
                            software.Worker = null;
                        }

                        foreach (Hardware hardware in hardwares)
                        {
                            hardware.Worker = null;
                        }

                        Employment employment = db.Employments.FirstOrDefault(e => e.Workers_IdWorker == id);
                        Account    account    = db.Accounts.FirstOrDefault(a => a.Workers_IdWorker == id);
                        db.Employments.Remove(employment);
                        db.Accounts.Remove(account);
                        db.Workers.Remove(worker);
                    }
                }
            }
            db.SaveChanges();
        }
        public void EntityStoredProcedure()
        {
            ISession     s = OpenSession();
            ITransaction t = s.BeginTransaction();

            Organization ifa   = new Organization("IFA");
            Organization jboss = new Organization("JBoss");
            Person       gavin = new Person("Gavin");
            Employment   emp   = new Employment(gavin, jboss, "AU");

            s.Save(ifa);
            s.Save(jboss);
            s.Save(gavin);
            s.Save(emp);

            IQuery namedQuery = s.GetNamedQuery("selectAllEmployments");
            IList  list       = namedQuery.List();

            Assert.IsTrue(list[0] is Employment);
            s.Delete(emp);
            s.Delete(ifa);
            s.Delete(jboss);
            s.Delete(gavin);

            t.Commit();
            s.Close();
        }
Пример #29
0
        public void UpdateEmploymentTest()
        {
            Employee employee = new Employee
            {
                FirstName = "Olga",
                LastName  = "Petersen"
            };

            repository.AddEmployee(employee);
            List <Employee> employees = repository.GetEmployees();

            employee = employees.FirstOrDefault(e => e.FirstName == "Olga");

            Employment employment = new Employment
            {
                EmployeeId = employee.EmployeeId,
                HireDate   = DateTime.Now,
                Title      = "Test"
            };

            repository.AddEmployment(employment, employee);
            employment = employee.Employments.FirstOrDefault(e => e.Title == "Test");

            employment.Title = "NotTest";
            repository.UpdateEmployment(employment);

            Assert.True(employee.Employments.First().Title == "NotTest");
        }
Пример #30
0
        public ActionResult AddEmploymentInformationSend(EmploymentViewModel eVM)
        {
            if (ModelState.IsValid)
            {
                Person     p = Session["Person"] as Person;
                Employment e = hrServices.CreateEmployment(eVM, p);
                if (e != null)
                {
                    return(RedirectToAction("AddContactPerson"));
                }
                else
                {
                    ModelState.AddModelError("", "Nieznany blad");
                    return(View("AddEmploymentInformation", eVM));
                }
            }
            else
            {
                eVM.Positions      = hrServices.PositionsSelectListItem();
                eVM.Organizations  = hrServices.OrganizationalUnitSelectListItem();
                eVM.ListOfManagers = hrServices.GetAllManagersSelectList();

                return(View("AddEmploymentInformation", eVM));
            }
        }
Пример #31
0
        public PersonEmploymentEditTest(TestFixture fixture)
            : base(fixture)
        {
            var allors = new Organisations(this.Session).FindBy(M.Organisation.Name, "Allors BVBA");

            this.employee = new PersonBuilder(this.Session).WithLastName("employee").Build();

            // Delete all existing for the new one to be in the first page of the list.
            foreach (PartyRelationship partyRelationship in allors.PartyRelationshipsWhereParty)
            {
                partyRelationship.Delete();
            }

            this.editPartyRelationship = new EmploymentBuilder(this.Session)
                                         .WithEmployee(this.employee)
                                         .WithEmployer(allors)
                                         .Build();

            this.Session.Derive();
            this.Session.Commit();

            var dashboard = this.Login();

            this.people = dashboard.Sidenav.NavigateToPersonList();
        }
        public async Task <IActionResult> Edit(int id, [Bind("EmploymentId,StartDate,EndDate,CompanyName,Position,Summary,ProfileId")] Employment employment)
        {
            if (id != employment.EmploymentId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(employment);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmploymentExists(employment.EmploymentId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index", "Employments", new { id = employment.ProfileId }));
            }
            ViewData["ProfileId"] = new SelectList(_context.Profiles, "ProfileId", "ProfileId", employment.ProfileId);
            return(View(employment));
        }
		public void SQLQueryInterface()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");

			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(emp);

			IList l = s.CreateSQLQuery(OrgEmpRegionSQL)
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.AddScalar("regionCode", NHibernateUtil.String)
				.List();
			Assert.AreEqual(2, l.Count);

			l = s.CreateSQLQuery(OrgEmpPersonSQL)
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.AddJoin("pers", "emp.employee")
				.List();
			Assert.AreEqual(l.Count, 1);

			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();

			l = s.CreateSQLQuery("select {org.*}, {emp.*} " +
			                     "from ORGANIZATION org " +
			                     "     left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER, ORGANIZATION org2")
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.SetResultTransformer(new DistinctRootEntityResultTransformer())
				.List();
			Assert.AreEqual(l.Count, 2);

			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();

			s.Delete(emp);
			s.Delete(gavin);
			s.Delete(ifa);
			s.Delete(jboss);

			t.Commit();
			s.Close();
		}
Пример #34
0
        /// <summary>
        /// Contient des Informations d'un Employement
        /// </summary>
        /// <param name="employ"></param>
        public EmploymentCard(Employment employ)
        {
            EmploymentGuid = employ.EmploymentGuid;
            Position = employ.Position;

            Job = !string.IsNullOrEmpty(employ.Project)
                ? employ.Departement + " - " + employ.Project
                : employ.Departement;

            Description = employ.StartDate.GetValueOrDefault().ToShortDateString() + " -> " +
                          employ.EndDate.GetValueOrDefault().ToShortDateString();

            IsExpiredColor = employ.EndDate.GetValueOrDefault() < DateTime.Today ? "Beige" : "LightGray";
        }
Пример #35
0
        public override void Init()
        {
            base.Init();

            this.employee = new PersonBuilder(this.DatabaseSession).WithLastName("slave").Build();
            this.internalOrganisation = new InternalOrganisations(this.DatabaseSession).FindBy(InternalOrganisations.Meta.Name, "internalOrganisation");

            this.employment = new EmploymentBuilder(this.DatabaseSession)
                .WithEmployee(this.employee)
                .WithEmployer(this.internalOrganisation)
                .WithFromDate(DateTime.UtcNow)
                .Build();

            this.DatabaseSession.Derive(true);
            this.DatabaseSession.Commit();
        }
Пример #36
0
        internal static HashSet<Payroll> GeneratePayRolls(Employment employ)
        {
            var payrollsList = new HashSet<Payroll>();
            if (employ.SalaryRecurrence == InstallmentRecurrence.Once)
            {
                payrollsList.Add(new Payroll
                {
                    EmploymentGuid = employ.EmploymentGuid,
                    Designation    = "Salaire",
                    PaycheckDate   = employ.EndDate
                });
                return payrollsList;
            }                 

            var debutJob       = employ.StartDate.GetValueOrDefault();
            var finJob         = employ.EndDate.GetValueOrDefault();
            var jobTotalMonths = DateTimeHelper.MonthDifference(debutJob, finJob);
            var periodLenght   = (int)employ.SalaryRecurrence;
            var totalSalaires  = jobTotalMonths / periodLenght;
            if ((jobTotalMonths % periodLenght) != 0) totalSalaires++;
            var nextPayOff     = debutJob;
            var payDay         = employ.StartDate.GetValueOrDefault().Day;

            for (var i = 0; i < totalSalaires; i++)
            {
                nextPayOff=new DateTime(nextPayOff.AddMonths(periodLenght).Year, nextPayOff.AddMonths(periodLenght).Month, payDay); 

                payrollsList.Add(new Payroll
                {
                    EmploymentGuid = employ.EmploymentGuid,
                    Designation = "Salaire " + employ.SalaryRecurrence.GetEnumDescription() + "(" + nextPayOff.ToString("MMM-yy") + ")",
                    PaycheckDate = nextPayOff
                });
            }
            return payrollsList;
        }
Пример #37
0
    public bool presist(EmploymentDTO entity)
    {
        try
        {
            model.Employment obj = new Employment();
            obj.userName = entity.userName;
            obj.startDate = entity.startDate;
            obj.title = entity.title;
            obj.company = entity.company;
            obj.industry = entity.industry;
            obj.town = entity.town;
            obj.province = entity.province;
            obj.country = entity.country;
            obj.empType = entity.empType;
            obj.currentEmployer = entity.currentEmployer;
            obj.gross = Decimal.Parse(entity.gross.ToString() );
            obj.startDate = entity.startDate;
            obj.endDate = entity.endDate;
            obj.responsibilities = entity.responsibilities;

            ctx.Employments.InsertOnSubmit(obj);
            ctx.SubmitChanges();
            return true;
        }
        catch (Exception)
        {
            ctx.Dispose();
            ctx = new ModelDataContext();
            return false;
        }
    }
Пример #38
0
        /// <summary>
        /// Ajouter Un Employement Pour un Staff
        /// </summary>
        /// <param name="employ"></param>
        /// <returns>True pour Success</returns>
        public bool AddEmployment(Employment employ)
        {
            if (string.IsNullOrEmpty(employ.Position)) throw new InvalidOperationException("POSITION_CAN_NOT_BE_EMPTY");
            if (employ.StartDate > employ.EndDate)     throw new InvalidOperationException("START_DATE_SUPERIOR_TO_END_DATE");
            using (var db = new StationContext()) if (db.Staffs.Find(employ.StaffGuid) == null) throw new InvalidOperationException("STAFF_REFERENCE_NOT_FOUND");

            using (var db = new StationContext())
            {
                if (employ.EmploymentGuid == Guid.Empty) employ.EmploymentGuid = Guid.NewGuid();

                employ.DateAdded        = DateTime.Now;
                employ.AddUserGuid      = Guid.Empty;
                employ.LastEditDate     = DateTime.Now;
                employ.LastEditUserGuid = Guid.Empty;
                
                db.Employments.Add(employ);

                if (db.SaveChanges() <= 0)
                    return false;

                foreach (var payRoll in PayRollHelper.GeneratePayRolls(employ))
                    StaticAddPayRoll(payRoll);
                return true;
            }
        }
Пример #39
0
        //New Employment
        protected void CreateEmployment(PartyRelationship PartyRelationship, string EmploymentStatus, string Salary)
        {
            Employment NewEmployment = new Employment();
            NewEmployment.PartyRelationship = PartyRelationship;
            NewEmployment.EmploymentStatus = EmploymentStatus;
            NewEmployment.Salary = Salary;

            ObjectContext.Employments.AddObject(NewEmployment);
        }
Пример #40
0
        /// <summary>
        /// Ajouter Un Employement Pour Un Staff
        /// </summary>
        /// <param name="staffGuid"></param>
        /// <param name="employToModGuid"></param>
        public AddEmploy(Guid staffGuid, Guid employToModGuid)
        {
            InitializeComponent();

            new Task(() =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (staffGuid == Guid.Empty)
                    {
                        ModernDialog.ShowMessage("Staff Not Found", "ERREUR", MessageBoxButton.OK);
                        Close();
                        return;
                    }

                    _CATEGORIE.ItemsSource     = App.Store.HumanResource.AllCategories();
                    _GRADE.ItemsSource         = App.Store.HumanResource.AllGrades();
                    _DEPARTEMENT.ItemsSource   = App.Store.HumanResource.AllDepartements();
                    //_DIVISION.ItemsSource      = App.DataS.HumanResource.AllDivisions();
                    //_PROJET.ItemsSource        = App.DataS.HumanResource.AllProjets();
                    _REPORT_TO.ItemsSource     = App.Store.HumanResource.AllStaffsNames();
                    _PAY_TYPE.ItemsSource      = EnumsHelper.GetAllValuesAndDescriptions<PayType>();
                    _SALARY_REC.ItemsSource    = EnumsHelper.GetAllValuesAndDescriptions<InstallmentRecurrence>();

                    if (employToModGuid == Guid.Empty)
                    {
                        //_MATIERE_NAME_VALIDATOR.ClasseGuid = classGuid;
                        _isAdd = true;

                        var data = new Employment
                        {
                            EmploymentGuid   = Guid.NewGuid(),
                            StaffGuid        = staffGuid,
                            Position         = "",
                            Category         = _CATEGORIE.Items.GetItemAt(0)   as string,
                            Grade            = _GRADE.Items.GetItemAt(0)       as string,
                            Departement      = _DEPARTEMENT.Items.GetItemAt(0) as string,
                            //Division         = _DIVISION.Items.GetItemAt(0)    as string,
                            //Project          = _PROJET.Items.GetItemAt(0)      as string,
                            ReportTo         = _REPORT_TO.Items.GetItemAt(0)   as string,
                            PayType          = PayType.SalaryOnly,
                            HourlyPay        = 0,
                            SalaryRecurrence = InstallmentRecurrence.Monthly,
                            StartDate        = DateTime.Today,
                            EndDate          = DateTime.Today.AddYears(1),
                            Description      = ""                            
                        };
                        _GRID.DataContext    = data;
                    }
                    else
                    {
                        var data = App.Store.Economat.PayRoll.GetEmployment(employToModGuid);
                        //_MATIERE_NAME_VALIDATOR.ClasseGuid = data.ClasseGuid;
                        //_MATIERE_NAME_VALIDATOR.IsAdd = false;
                        _TITLE_TEXT.Text = "MODIFICATION";
                        _GRID.DataContext = data;

                        _SALARY_REC.IsEnabled = false;
                        _NUM_REC.IsEnabled    = false;
                        _PAY_TYPE.IsEnabled   = false;
                        _HOURLY_PAY.IsEnabled = false;
                        _DEBUT_EMP.IsEnabled  = false;
                    }
                }));
            }).Start();
        }
		public void AutoDetectAliasing()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");
			s.Save(jboss);
			s.Save(ifa);
			s.Save(gavin);
			s.Save(emp);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			IList list = s.CreateSQLQuery(EmploymentSQL)
				.AddEntity(typeof(Employment).FullName)
				.List();
			Assert.AreEqual(1, list.Count);

			Employment emp2 = (Employment) list[0];
			Assert.AreEqual(emp2.EmploymentId, emp.EmploymentId);
			Assert.AreEqual(emp2.StartDate.Date, emp.StartDate.Date);
			Assert.AreEqual(emp2.EndDate, emp.EndDate);

			s.Clear();

			list = s.CreateSQLQuery(EmploymentSQL)
				.AddEntity(typeof(Employment).FullName)
				.SetResultTransformer(CriteriaSpecification.AliasToEntityMap)
				.List();
			Assert.AreEqual(1, list.Count);
			IDictionary m = (IDictionary) list[0];
			Assert.IsTrue(m.Contains("Employment"));
			Assert.AreEqual(1, m.Count);

			list = s.CreateSQLQuery(EmploymentSQL).List();
			Assert.AreEqual(1, list.Count);
			object[] o = (object[]) list[0];
			Assert.AreEqual(8, o.Length);

			list = s.CreateSQLQuery(EmploymentSQL).SetResultTransformer(CriteriaSpecification.AliasToEntityMap).List();
			Assert.AreEqual(1, list.Count);
			m = (IDictionary) list[0];
			Assert.IsTrue(m.Contains("EMPID") || m.Contains("empid"));
			Assert.IsTrue(m.Contains("AVALUE") || m.Contains("avalue"));
			Assert.IsTrue(m.Contains("ENDDATE") || m.Contains("enddate"));
			Assert.AreEqual(8, m.Count);

			// TODO H3: H3.2 can guess the return column type so they can use just addScalar("employerid"),
			// but NHibernate currently can't do it.
			list =
				s.CreateSQLQuery(EmploymentSQLMixedScalarEntity).AddScalar("employerid", NHibernateUtil.Int64).AddEntity(
					typeof(Employment)).List();
			Assert.AreEqual(1, list.Count);
			o = (object[]) list[0];
			Assert.AreEqual(2, o.Length);
			AssertClassAssignability(o[0].GetType(), typeof(long));
			AssertClassAssignability(o[1].GetType(), typeof(Employment));


			IQuery queryWithCollection = s.GetNamedQuery("organizationEmploymentsExplicitAliases");
			queryWithCollection.SetInt64("id", jboss.Id);
			list = queryWithCollection.List();
			Assert.AreEqual(list.Count, 1);

			s.Clear();

			list = s.CreateSQLQuery(OrganizationJoinEmploymentSQL)
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.List();
			Assert.AreEqual(2, list.Count);

			s.Clear();

			list = s.CreateSQLQuery(OrganizationFetchJoinEmploymentSQL)
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.List();
			Assert.AreEqual(2, list.Count);

			s.Clear();

			// TODO : why twice?
			s.GetNamedQuery("organizationreturnproperty").List();
			list = s.GetNamedQuery("organizationreturnproperty").List();
			Assert.AreEqual(2, list.Count);

			s.Clear();

			list = s.GetNamedQuery("organizationautodetect").List();
			Assert.AreEqual(2, list.Count);

			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			s.Delete(emp2);

			s.Delete(jboss);
			s.Delete(gavin);
			s.Delete(ifa);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			Dimension dim = new Dimension(3, int.MaxValue);
			s.Save(dim);
			//		s.Flush();
			s.CreateSQLQuery("select d_len * d_width as surface, d_len * d_width * 10 as volume from Dimension").List();
			s.Delete(dim);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			SpaceShip enterprise = new SpaceShip();
			enterprise.Model = "USS";
			enterprise.Name = "Entreprise";
			enterprise.Speed = 50d;
			Dimension d = new Dimension(45, 10);
			enterprise.Dimensions = d;
			s.Save(enterprise);
			//		s.Flush();
			object[] result = (object[]) s.GetNamedQuery("spaceship").UniqueResult();
			enterprise = (SpaceShip) result[0];
			Assert.IsTrue(50d == enterprise.Speed);
			Assert.IsTrue(450d == ExtractDoubleValue(result[1]));
			Assert.IsTrue(4500d == ExtractDoubleValue(result[2]));
			s.Delete(enterprise);
			t.Commit();
			s.Close();
		}
		public void MappedAliasStrategy()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");
			s.Save(jboss);
			s.Save(ifa);
			s.Save(gavin);
			s.Save(emp);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			IQuery namedQuery = s.GetNamedQuery("AllEmploymentAsMapped");
			IList list = namedQuery.List();
			Assert.AreEqual(1, list.Count);
			Employment emp2 = (Employment) list[0];
			Assert.AreEqual(emp2.EmploymentId, emp.EmploymentId);
			Assert.AreEqual(emp2.StartDate.Date, emp.StartDate.Date);
			Assert.AreEqual(emp2.EndDate, emp.EndDate);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			IQuery sqlQuery = s.GetNamedQuery("EmploymentAndPerson");
			sqlQuery.SetResultTransformer(CriteriaSpecification.AliasToEntityMap);
			list = sqlQuery.List();
			Assert.AreEqual(1, list.Count);
			object res = list[0];
			AssertClassAssignability(res.GetType(), typeof(IDictionary));
			IDictionary m = (IDictionary) res;
			Assert.AreEqual(2, m.Count);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			sqlQuery = s.GetNamedQuery("organizationreturnproperty");
			sqlQuery.SetResultTransformer(CriteriaSpecification.AliasToEntityMap);
			list = sqlQuery.List();
			Assert.AreEqual(2, list.Count);
			m = (IDictionary) list[0];
			Assert.IsTrue(m.Contains("org"));
			AssertClassAssignability(m["org"].GetType(), typeof(Organization));
			Assert.IsTrue(m.Contains("emp"));
			AssertClassAssignability(m["emp"].GetType(), typeof(Employment));
			Assert.AreEqual(2, m.Count);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			namedQuery = s.GetNamedQuery("EmploymentAndPerson");
			list = namedQuery.List();
			Assert.AreEqual(1, list.Count);
			object[] objs = (object[]) list[0];
			Assert.AreEqual(2, objs.Length);
			emp2 = (Employment) objs[0];
			gavin = (Person) objs[1];
			s.Delete(emp2);
			s.Delete(jboss);
			s.Delete(gavin);
			s.Delete(ifa);
			t.Commit();
			s.Close();
		}
		public void ResultSetMappingDefinition()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");

			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(emp);

			IList l = s.CreateSQLQuery(OrgEmpRegionSQL)
				.SetResultSetMapping("org-emp-regionCode")
				.List();
			Assert.AreEqual(l.Count, 2);

			l = s.CreateSQLQuery(OrgEmpPersonSQL)
				.SetResultSetMapping("org-emp-person")
				.List();
			Assert.AreEqual(l.Count, 1);

			s.Delete(emp);
			s.Delete(gavin);
			s.Delete(ifa);
			s.Delete(jboss);

			t.Commit();
			s.Close();
		}
Пример #44
0
 private void InstantiateObjects(ISession session)
 {
     this.employee = (Person)session.Instantiate(this.employee);
     this.internalOrganisation = (InternalOrganisation)session.Instantiate(this.internalOrganisation);
     this.employment = (Employment)session.Instantiate(this.employment);
 }
		public void HandSQL()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");
			object orgId = s.Save(jboss);
			s.Save(ifa);
			s.Save(gavin);
			s.Save(emp);
			t.Commit();

			t = s.BeginTransaction();
			Person christian = new Person("Christian");
			s.Save(christian);
			Employment emp2 = new Employment(christian, jboss, "EU");
			s.Save(emp2);
			t.Commit();
			s.Close();

			sessions.Evict(typeof(Organization));
			sessions.Evict(typeof(Person));
			sessions.Evict(typeof(Employment));

			s = OpenSession();
			t = s.BeginTransaction();
			jboss = (Organization)s.Get(typeof(Organization), orgId);
			Assert.AreEqual(jboss.Employments.Count, 2);
			emp = (Employment)GetFirstItem(jboss.Employments);
			gavin = emp.Employee;
			Assert.AreEqual(gavin.Name, "GAVIN");
			Assert.AreEqual(s.GetCurrentLockMode(gavin), LockMode.Upgrade);
			emp.EndDate = DateTime.Today;
			Employment emp3 = new Employment(gavin, jboss, "US");
			s.Save(emp3);
			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();
			IEnumerator iter = s.GetNamedQuery("allOrganizationsWithEmployees").List().GetEnumerator();
			Assert.IsTrue(iter.MoveNext());
			Organization o = (Organization)iter.Current;
			Assert.AreEqual(o.Employments.Count, 3);

			foreach (Employment e in o.Employments)
			{
				s.Delete(e);
			}

			foreach (Employment e in o.Employments)
			{
				s.Delete(e.Employee);
			}
			s.Delete(o);
			Assert.IsFalse(iter.MoveNext());
			s.Delete(ifa);
			t.Commit();
			s.Close();
		}
		private void VerifyOrganisationQuery(Func<ISession, IQuery> queryFactory)
		{
			using (ISession s = OpenSession())
			using (ITransaction t = s.BeginTransaction())
			{
				var ifa = new Organization("IFA");
				var jboss = new Organization("JBoss");
				var gavin = new Person("Gavin");
				var emp = new Employment(gavin, jboss, "AU");
				s.Save(jboss);
				s.Save(ifa);
				s.Save(gavin);
				s.Save(emp);

				var list = queryFactory(s).List();
				Assert.AreEqual(2, list.Count);
			}
		}
Пример #47
0
        /// <summary>
        /// Modifier les information d'un employement
        /// </summary>
        /// <param name="employ"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateEmployment(Employment employ)
        {
            if (string.IsNullOrEmpty(employ.Position))                                        throw new InvalidOperationException("POSITION_CAN_NOT_BE_EMPTY");
            if (employ.StartDate > employ.EndDate)                                            throw new InvalidOperationException("START_DATE_SUPERIOR_TO_END_DATE");
            using (var db = new StationContext()) if (db.Staffs.Find(employ.StaffGuid) == null) throw new InvalidOperationException("STAFF_REFERENCE_NOT_FOUND");

            using (var db = new StationContext())
            {
                var newEmploy = db.Employments.Find(employ.EmploymentGuid);
                if (newEmploy == null)                                                        throw new InvalidOperationException("EMPLOYEMENT_REFERENCE_NOT_FOUND");

                //todo cancel Employ 
                newEmploy.Position         = employ.Position;
                newEmploy.Category         = employ.Category;
                newEmploy.Project          = employ.Project;
                newEmploy.Grade            = employ.Grade;
                newEmploy.Departement      = employ.Departement;
                newEmploy.Division         = employ.Division;
                newEmploy.ReportTo         = employ.ReportTo;
                //newEmploy.SalaryRecurrence = employ.SalaryRecurrence;
                //newEmploy.StartDate        = employ.StartDate;
                //newEmploy.EndDate          = employ.EndDate;
                newEmploy.Description      = employ.Description;

                newEmploy.LastEditDate     = DateTime.Now;
                newEmploy.LastEditUserGuid = Guid.Empty;

                db.Employments.Attach(newEmploy);
                db.Entry(newEmploy).State = EntityState.Modified;

                return db.SaveChanges() > 0;
            }
        }