private void DoPunchIn(string enrollmentId) { PunchManager punchManager = new PunchManager(); UserVoiceManager mgr = new UserVoiceManager(); EmployeeEnrollment enrollment = mgr.GetEmployeeEnrollment(enrollmentId); if (enrollment != null) { Punch p = new Punch { ClientId = enrollment.ClientId, EmployeeUid = enrollment.EmployeeUid, DepartmentUid = enrollment.DepartmentUid, PunchDateTime = DateTime.Now, PunchSourceTypeId = (byte)1, //manual PunchActivityTypeId = (byte)1, //work PunchStatusTypeId = (byte)1, //auto LaborAssociations = new System.Collections.Generic.List <LaborPunchAssociation>(), IsActive = true, CanBeProcessed = true, UserKey = Guid.Parse("C00E2729-9FFA-E511-8893-005056BD7869") }; punchManager.InsertPunch(p); } else { throw new Exception("Enrollment record could not be read from cosmosdb"); } }
// Start is called before the first frame update void Start() { rb = GetComponent <Rigidbody2D>(); animator = GetComponent <Animator>(); punch = GetComponent <Punch>(); health = GetComponent <PlayerHealth>(); }
// Start is called before the first frame update void Start() { if (Punch.Instance == null) { Punch.Instance = this; } }
/// <summary> /// 取得異常時間、提醒訊息 /// </summary> /// <returns></returns> private bool getPunchPara(out ParaModel paraData, out MsgParaModel paraMsgData) { bool result = false; var msg = ""; paraData = new ParaModel(); paraMsgData = new MsgParaModel(); var datas = new PunchParaBean(); var viewData = new PunchParaModel() { CompID = UserInfo.getUserInfo().CompID, }; result = Punch.GetPunchPara(viewData, out datas, out msg); if (result && datas != null) { paraData = Punch.paraFormat(datas.Para); paraMsgData = Punch.paraMsgFormat(datas.MsgPara); } else { throw new Exception("".Equals(msg) ? "查無資料" : msg); } return(result); }
// // GET: /Punch/Edit/5 public ActionResult Edit(int id) { Punch punch = db.Punches.Find(id); ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName", punch.EmployeeID); return(PartialView(punch)); }
//+++++++++++++++++++++++++++++New Code++++++++++++++++++++++++++++++++++ /// <summary> /// Create an action node which is Punch attack type. /// modified Do (action) Node. /// </summary> /// <param name="context">The context.</param> /// <param name="AI">The ai.</param> /// <param name="NAI">The nai.</param> /// <returns></returns> /// <exception cref="System.ApplicationException">Can't create an unnested ActionNode, it must be a leaf node.</exception> public MyTreeBuilder Punch(GameWorld context, AIFighter AI, NonAIFighter NAI) { if (parentNodeStack.Count <= 0) { throw new ApplicationException("Can't create an unnested ActionNode, it must be a leaf node."); } Func <MyTimeData, MyBehaviourTreeStatus> fr; fr = t => { // A Punch Attack Punch punch = new Punch(); GameWorld gw = context; gw.wAttack(AI, NAI, punch); gw.ListOfEvents.Add("Punch non AI player"); return(MyBehaviourTreeStatus.Success); }; var actionNone = new ActionNode("Punch", fr); parentNodeStack.Peek().AddChild(actionNone); return(this); }/// <summary>
//-------------------------------------------------------------主要邏輯區 /// <summary> /// 確定打卡邏輯 /// </summary> private void DoDefine() { bool result = false; long seccessCount = 0; string msg = ""; try { PunchModel model = _PunchModel; string abnormalFlag = rbtAbnormal.Checked ? "1" : "2"; model.AbnormalFlag = StringIIF(abnormalFlag); model.AbnormalReasonID = StringIIF(ddlAbnormalReason.SelectedValue); model.AbnormalReasonCN = StringIIF("".Equals(ddlAbnormalReason.SelectedValue)?"":ddlAbnormalReason.SelectedItem.Text); model.AbnormalDesc = StringIIF(AbnormalDesc.Text); result = Punch.InsertPunchLog(model, out seccessCount, out msg); if (!result) { throw new Exception(msg); } if (seccessCount == 0) { throw new Exception("無資料被新增!!"); } _SessionPunchModel = model; Response.Redirect("~/Punch/PO1000_Finish.aspx" + "?id=" + _SessionID); } catch (Exception ex) { Util.MsgBox(ex.Message); } }
public static void EncryptFile(Punch punch, string inputFile, string outputFile) { string key = GenerateKey(punch); byte[] keyBytes; keyBytes = Encoding.Unicode.GetBytes(key); Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(key, keyBytes); RijndaelManaged rijndaelCSP = new RijndaelManaged(); rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8); rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8); ICryptoTransform encryptor = rijndaelCSP.CreateEncryptor(); FileStream inputFileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read); byte[] inputFileData = new byte[(int)inputFileStream.Length]; inputFileStream.Read(inputFileData, 0, (int)inputFileStream.Length); FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write); CryptoStream encryptStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write); encryptStream.Write(inputFileData, 0, (int)inputFileStream.Length); encryptStream.FlushFinalBlock(); rijndaelCSP.Clear(); encryptStream.Close(); inputFileStream.Close(); outputFileStream.Close(); }
/* * this split up the punch to the different days that it happen, this is done recursively, and call allLinesHelper on the corresponding days * */ private static bool addLinesDaily(TimeClockContext db, Punch punch, Timecard tc, DateTime splitStart, DateTime splitEnd, double weeklyWorked, DateTime dayStartTime) { // Split on days if (splitStart.Subtract(dayStartTime).TotalMinutes < 0) // the punch started on the previous day, split and call recursively { addLinesDaily(db, punch, tc, splitStart, dayStartTime, weeklyWorked, dayStartTime.AddDays(-1)); splitStart = dayStartTime; // To continue adding the rest of the punch } if (splitEnd.Subtract(dayStartTime.AddDays(1)).TotalMinutes < 0) // the punch ended today, we can safely add it { double dailyworked = punch.employee.minutsWorkedDate(db, dayStartTime); bool seventhDay = punch.employee.workedSixPreviousDays(db); addLinesHelper(db, punch, tc, punch.employee.department.DefaultPayType, weeklyWorked, dailyworked, splitStart, splitEnd, seventhDay); } else // The punch ends on the next day { double dailyworked = punch.employee.minutsWorkedDate(db, dayStartTime); bool seventhDay = punch.employee.workedSixPreviousDays(db); addLinesHelper(db, punch, tc, punch.employee.department.DefaultPayType, weeklyWorked, dailyworked, splitStart, dayStartTime.AddDays(1), seventhDay); addLinesDaily(db, punch, tc, dayStartTime.AddDays(1), splitEnd, weeklyWorked, dayStartTime.AddDays(1)); } return(true); }
public static PlayerClass FighterClass() { var fighter = new PlayerClass { Name = "Fighter", IsBaseClass = true, ExperienceModifier = 1500, HelpText = new Help(), Skills = new List <Skill>(), ReclassOptions = new List <PlayerClass>(), MaxHpGain = 15, MinHpGain = 11, MaxManaGain = 8, MinManaGain = 4, MaxEnduranceGain = 15, MinEnduranceGain = 11, StatBonusStr = 1, StatBonusCon = 1 }; #region Give fighter punch skill var punch = Punch.PunchAb(); punch.LevelObtained = 2; punch.Proficiency = 0.1; punch.MaxProficiency = 0.95; fighter.Skills.Add(punch); #endregion fighter.ReclassOptions.Add(Ranger.RangerClass()); return(fighter); }
public void Delete(int id) { Punch punch = db.Punches.Find(id); db.Punches.Remove(punch); db.SaveChanges(); }
// Start is called before the first frame update void Start() { punch = GetComponent <Punch>(); startingPosition = transform.localPosition; punch.startingPosition = startingPosition; player = GetComponentInParent <PlayerController>(); }
void Start( ) { pTrans = transform; pRig = gameObject.GetComponent <Rigidbody> ( ); punchBox = pTrans.GetChild(0).GetComponent <BoxCollider>(); sphereChocWave = pTrans.GetChild(0).GetComponent <SphereCollider>(); punch = pTrans.GetChild(0).GetComponent <Punch>(); canPunch = true; punchRight = true; getPunch = GetComponentInChildren <Punch> ( ); thisCam = GetComponentInChildren <Camera> ( ); SliderSlow = GlobalManager.Ui.MotionSlider; SliderContent = 10; SliderSlow.maxValue = 10; lastPos = pTrans.position; textDist = GlobalManager.Ui.ScorePoints; textCoin = GlobalManager.Ui.MoneyPoints; nextIncrease = DistIncMaxSpeed; maxSpeed = MaxSpeed; maxSpeedCL = MaxSpeedCL; accelerationCL = AccelerationCL; acceleration = Acceleration; impulsionCL = ImpulsionCL; decelerationCL = DecelerationCL; playAnimator = GetComponentInChildren <Animator> ( ); camMad = GetComponentInChildren <CameraFilterPack_Color_YUV>(); saveCamMad = new Vector3(camMad._Y, camMad._U, camMad._V); /* punchLeft = true; preparRight = false; preparLeft = false; defense = false; * preparPunch = null;*/ Plafond.GetComponent <MeshRenderer>().enabled = true; }
public static PlayerClass RangerClass() { var ranger = new PlayerClass { Name = "Ranger", IsBaseClass = false, ExperienceModifier = 2000, HelpText = new Help(), Skills = new List <Skill>(), ReclassOptions = new List <PlayerClass>(), MaxHpGain = 20, MinHpGain = 13, MaxManaGain = 15, MinManaGain = 5, MaxEnduranceGain = 40, MinEnduranceGain = 15, StatBonusCon = 1, StatBonusDex = 2 }; #region Give fighter punch skill var punch = Punch.PunchAb(); punch.LevelObtained = 2; punch.Proficiency = 1; punch.MaxProficiency = 95; ranger.Skills.Add(punch); #endregion return(ranger); }
public async Task <IActionResult> OnPost() { var flag = false; var EmployeeId = Request.Form["EmployeeId"]; using var client = new HttpClient(); if (Punch.Equals("break")) { flag = true; } StringContent timeStampHttp = new StringContent(System.Text.Json.JsonSerializer.Serialize <TimeStamp>(new TimeStamp(DateTime.Now, Int32.Parse(EmployeeId), flag))); HttpResponseMessage response = await client.PostAsync("http://127.0.0.1:1127/api/thehappypig/punchin", timeStampHttp); var responseContent = await response.Content.ReadAsStringAsync(); responseAPI = JsonConvert.DeserializeObject <API_Response>(responseContent); if (String.IsNullOrEmpty(responseAPI.attribute)) { timeStamp = null; } else { timeStamp = JsonConvert.DeserializeObject <TimeStamp>(responseAPI.attribute); } return(Page()); }
void Start() { // Fail-safes added here since AI can't punch yet but this is still called. Transform punchParent = transform.Find("Punch"); if (punchParent) { Transform punchPivot = punchParent.Find("PunchPivot"); aimPunch = punchPivot.GetComponent <Aim>(); aimPunch.HorizontalStick = GameInput.RightHorizontal; aimPunch.VerticalStick = GameInput.RightVertical; punchArc = punchPivot.Find("PunchArc").gameObject; punchArc.SetActive(false); swipeTrailRenderer = punchParent.GetComponentInChildren <TrailRenderer>(); swipeTrailRenderer.enabled = false; } playerInfo = GetComponent <PlayerInfo> (); punch = GetComponentInChildren <Punch>(); if (punch) { punch.Owner = playerInfo; initPunchLocalPos = punch.transform.localPosition; punchRB2D = punch.GetComponent <Rigidbody2D>(); punchRenderer = punch.GetComponent <SpriteRenderer>(); punchRenderer.color = playerInfo.color; } }
public Task Register(PunchViewModel punchViewModel) { var punch = new Punch(punchViewModel); punch.DateTime = DateTime.UtcNow; var lastPunchToday = _punchRepository.GetLastPunchForToday(punchViewModel.EmployeeId).Result; if (lastPunchToday == null) { punch.PunchType = PunchType.PunchIn; } else { punch.PunchType = lastPunchToday.PunchType == PunchType.PunchIn ? PunchType.PunchOut : PunchType.PunchIn; } var validator = new PunchValidator(); var result = validator.Validate(punch); if (!result.IsValid) { var errorsMsg = string.Join(',', result.Errors.Select(x => x.ErrorMessage)); throw new ValidationException(errorsMsg); } return(_punchRepository.Save(punch)); }
public static int BuildPunch(Punch punch) { DateTime now = DateTime.Now; string buildDate = String.Format("{0:MMMM dd yyyy} at {0:hh:mm:ss tt}", now); using (StreamWriter buildDateFile = new StreamWriter(Path.Combine(punch.resources_dir, "attackDate.txt"))) { buildDateFile.Write(buildDate); } string dotNetDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); string msbuildPath = Path.Combine(dotNetDir, "msbuild.exe"); if (File.Exists(msbuildPath)) { Process msbuild = new Process(); msbuild.StartInfo.FileName = msbuildPath; msbuild.StartInfo.Arguments = punch.build_args; msbuild.StartInfo.UseShellExecute = false; msbuild.StartInfo.RedirectStandardOutput = true; msbuild.StartInfo.RedirectStandardError = true; Console.WriteLine("Running build with this command: {0} {1}", msbuild.StartInfo.FileName, msbuild.StartInfo.Arguments); msbuild.Start(); string output = msbuild.StandardOutput.ReadToEnd(); Console.WriteLine(output); string err = msbuild.StandardError.ReadToEnd(); Console.WriteLine(err); msbuild.WaitForExit(); int exitCode = msbuild.ExitCode; msbuild.Close(); return(exitCode); } return(999); }
/// <summary> /// Loads the animation values of all Punch Presets that are set to load at runtime. /// </summary> void LoadRuntimePunchPresets() { if (loadOnPointerEnterPunchPresetAtRuntime) { Punch presetPunch = UIAnimatorUtil.GetPunch(onPointerEnterPunchPresetCategory, onPointerEnterPunchPresetName); if (presetPunch != null) { onPointerEnterPunch = presetPunch.Copy(); } } if (loadOnPointerExitPunchPresetAtRuntime) { Punch presetPunch = UIAnimatorUtil.GetPunch(onPointerExitPunchPresetCategory, onPointerExitPunchPresetName); if (presetPunch != null) { onPointerExitPunch = presetPunch.Copy(); } } if (loadOnClickPunchPresetAtRuntime) { Punch presetPunch = UIAnimatorUtil.GetPunch(onClickPunchPresetCategory, onClickPunchPresetName); if (presetPunch != null) { onClickPunch = presetPunch.Copy(); } } }
/// <summary> /// 取得執勤、個人、公司班表 /// </summary> /// <returns></returns> private bool getReport(string regStr, out PunchModel viewData) { bool result = false; string NowTime = DateTime.Now.ToString("HH:mm:ss.fff"); var msg = ""; var datas = new PunchBean(); viewData = new PunchModel() { CompID = UserInfo.getUserInfo().CompID, EmpID = UserInfo.getUserInfo().UserID, EmpName = UserInfo.getUserInfo().UserName, DeptID = UserInfo.getUserInfo().DeptID, DeptName = UserInfo.getUserInfo().DeptName, OrganID = UserInfo.getUserInfo().OrganID, OrganName = UserInfo.getUserInfo().OrganName, WorkTypeID = UserInfo.getUserInfo().WorkTypeID, WorkType = UserInfo.getUserInfo().WorkTypeName, Sex = UserInfo.getUserInfo().Sex, PunchFlag = "0", MAFT10_FLAG = "0", PunchDate = DateTime.Now.ToString("yyyy/MM/dd"), //PunchDate = "2017/05/02", PunchTime = NowTime, PunchTime4Count = NowTime.Replace(":", "").Substring(0, 4), LastChgComp = UserInfo.getUserInfo().CompID, LastChgID = UserInfo.getUserInfo().UserID }; switch (regStr) { case "Duty": { result = Punch.GetDutyReport(viewData, out datas, out msg); break; } case "EmpWork": { result = Punch.GetEmpWorkReport(viewData, out datas, out msg); break; } case "PersonOther": { result = Punch.GetPersonalOtherReport(viewData, out datas, out msg); break; } } if (result && datas != null) { viewData.BeginTime = datas.BeginTime; viewData.EndTime = datas.EndTime; viewData.RestBeginTime = datas.RestBeginTime; viewData.RestEndTime = datas.RestEndTime; } return(result); }
/// <summary> /// Generates the attack of the fighter. /// </summary> /// <returns> /// Attack type /// </returns> public virtual Attack GenAttack() { //Fighter opponent //int a = 10; Attack attk; Random rnd = new Random(); if (rnd.Next(0, 3) == 0) { attk = new Punch(); } else if (rnd.Next(0, 3) == 1) { attk = new Kick(); } else { attk = new Special(); } //return attack Attack = attk; return(attk); }
private void Start() { _walk = new Walk(); _jump = new Jump(); _kick = new Kick(); _punch = new Punch(); _animator = player.GetComponent <Animator>(); }
public ActionResult DeleteConfirmed(int id) { Punch punch = db.Punch.Find(id); db.Punch.Remove(punch); db.SaveChanges(); return(RedirectToAction("Index")); }
public void Add(Punch punch) { using (PunchClockDbContext context = new PunchClockDbContext()) { context.Punches.Add(punch); context.SaveChanges(); } }
public async Task <int> SavePunchInDatabase(Punch punchToSave) { using (IDbConnection connection = new SqlConnection(SiloConfigurationProvider.GetConfig().ConnectionString)) { connection.Open(); return(await connection.InsertAsync(punchToSave)); } }
public static PlayerClass MageClass() { var mage = new PlayerClass { Name = "Mage", IsBaseClass = true, ExperienceModifier = 3000, HelpText = new Help(), Skills = new List <Skill>(), ReclassOptions = new List <PlayerClass>(), MaxHpGain = 8, MinHpGain = 3, MaxManaGain = 15, MinManaGain = 10, MaxEnduranceGain = 15, MinEnduranceGain = 11, StatBonusInt = 2, StatBonusWis = 1 }; #region Give fighter punch skill var punch = Punch.PunchAb(); punch.LevelObtained = 2; punch.Proficiency = 1; punch.MaxProficiency = 95; mage.Skills.Add(punch); #endregion #region Give mage magic missile skill var magicMissile = MagicMissile.MagicMissileAb(); magicMissile.LevelObtained = 1; magicMissile.Proficiency = 50; magicMissile.MaxProficiency = 95; mage.Skills.Add(magicMissile); #endregion #region Give mage armor skill var armour = Armour.ArmourAb(); armour.LevelObtained = 1; armour.Proficiency = 50; armour.MaxProficiency = 95; mage.Skills.Add(armour); #endregion mage.ReclassOptions.Add(Ranger.RangerClass()); return(mage); }
public void punchMaker() { GameObject punch = Instantiate(Resources.Load("Prefabs/Punch", typeof(GameObject)), transform.position, Quaternion.identity) as GameObject; Punch p = punch.GetComponent("Punch") as Punch; p.prepPunch(this, punch); p.GetComponent<BoxCollider>().enabled=false; //slash.transform.Translate(s.cast(),Space.World); spells [3] = punch; // Debug.Log("-.-"); }
public static void SetPunch(this PunchDto punchDto, Punch punch) { punchDto.Created = punch.Created; punchDto.Direction = punch.Direction; punchDto.Punchid = punch.Id; punchDto.Time = punch.PunchTime; punchDto.Timedec = (double)punch.TimeDec; punchDto.Updated = punch.Updated; }
public static BattleAction getAction() { if (instance == null) { instance = new Punch(); } return(instance); }
public ActionResult Delete([DataSourceRequest] DataSourceRequest request, Punch punch) { if (punch != null && ModelState.IsValid) { _punchService.Delete(punch); } return(Json(new[] { punch }.ToDataSourceResult(request, ModelState))); }
public ActionResult Create(Punch punch) { if (ModelState.IsValid) { db.Punches.Add(punch); db.SaveChanges(); return PartialView("GridData", new Punch[] { punch }); } ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName", punch.EmployeeID); return PartialView("Edit", punch); }
public static bool addLines(TimeClockContext db, Punch punch) { // determine payperiod PayPeriod currentPayP = PayPeriodTools.LookupPayPeriod(db, punch.employee.department.DepartmentID, punch.OutTime.Value); Timecard currentTC = db.Timecards.SingleOrDefault(tc => tc.EmployeeID == punch.EmployeeID && tc.PayPeriod.Equals(currentPayP.Start)); // check if we reach over payperiods if (punch.InTime.Subtract(currentPayP.Start).TotalMinutes < 0) // We started in the previous payperiod , solit the punch into two. { PayPeriod previousPayP = new PayPeriod() { Start = currentPayP.Start.Subtract(TimeSpan.FromDays(punch.employee.department.PayPeriodInterval)), End = currentPayP.Start }; Timecard previousTC = db.Timecards.SingleOrDefault(tc => tc.EmployeeID == punch.EmployeeID && tc.PayPeriod.Equals(previousPayP.Start)); bool first = addLinesTimecard(db, punch, previousTC, punch.InTime, previousPayP.End); bool second = addLinesTimecard(db, punch, currentTC, currentPayP.Start, punch.OutTime.Value); return first && second; } else if (punch.OutTime.Value.Subtract(currentPayP.End).TotalMinutes > 0) // We ended in the next payperiod - Not sure this will ever happen { PayPeriod nextPayP = new PayPeriod() { Start = currentPayP.End, End = currentPayP.End.Add(TimeSpan.FromDays(punch.employee.department.PayPeriodInterval)) }; Timecard nextTC = db.Timecards.SingleOrDefault(tc => tc.EmployeeID == punch.EmployeeID && tc.PayPeriod.Equals(nextPayP.Start)); bool first = addLinesTimecard(db, punch, currentTC, punch.InTime, currentPayP.End); bool second = addLinesTimecard(db, punch, nextTC, nextPayP.Start, punch.OutTime.Value); return first && second; } else // No over lap, we just add the whole punch to the current Time card { return addLinesTimecard(db, punch, currentTC, punch.InTime, punch.OutTime.Value); } }
static void Main(string[] args) { try { var options = new Options(); if (!CommandLine.Parser.Default.ParseArgumentsStrict(args, options)) { Environment.Exit(1); } var punch = new Punch(AppSettings.Username, AppSettings.Password, AppSettings.Browser); if (options.In) { if (options.Delay > 0) { WaitRandomly(options.Delay); } punch.In(); } else if (options.Out) { if (options.Delay > 0) { WaitRandomly(options.Delay); } punch.Out(); } } catch (Exception ex) { Console.WriteLine("[error] {0}", ex.Message); Environment.Exit(1); } Environment.Exit(0); }
// Use this for initialization void Awake() { if (!Effects && GetComponent<Effects> ()) Effects = GetComponent<Effects> (); else if (!Effects) Effects = (Effects) gameObject.AddComponent<Effects> (); EnemyGC2 = enemyGC2; DontDestroyOnLoad (gameObject); PlayerManager.Players.Add (this); Walk = GetComponent<Walk> (); Punch = GetComponent<Punch> (); Health = GetComponent<Health> (); Mana = GetComponent<Mana> (); TurnBody = TB; TurnHead = TH; EnemyLOS = enemyLOS; SpawnLOS = spawnLOS; walk = Walk; health = Health; punch = Punch; mana = Mana; }
public ActionResult Edit(Punch punch) { if (ModelState.IsValid) { db.Entry(punch).State = EntityState.Modified; db.SaveChanges(); return PartialView("GridData", new Punch[] { punch }); } ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName", punch.EmployeeID); return PartialView(punch); }
/* This functions determine the weekly minuts worked, as well as the time that the current payday started. * * This information is then used to call addLinesDaily(...); */ private static bool addLinesTimecard(TimeClockContext db, Punch punch, Timecard tc, DateTime splitStart, DateTime splitEnd) { // Calculate weeklyWorked, and dailyWorked var lines = db.Lines.Where(l => l.TimecardID == tc.TimecardID); double weeklyMinuts = punch.employee.minutesWorkedWeek(db, splitStart); TimeSpan dayBeginTime = punch.employee.department.PayPeriodSeed.TimeOfDay; DateTime currentDayStart = DateTime.Now.Date.Add(dayBeginTime); return addLinesDaily(db, punch, tc, splitStart, splitEnd, weeklyMinuts, currentDayStart); }
/* * this split up the punch to the different days that it happen, this is done recursively, and call allLinesHelper on the corresponding days * */ private static bool addLinesDaily(TimeClockContext db, Punch punch, Timecard tc, DateTime splitStart, DateTime splitEnd, double weeklyWorked, DateTime dayStartTime) { // Split on days if(splitStart.Subtract(dayStartTime).TotalMinutes < 0) // the punch started on the previous day, split and call recursively { addLinesDaily(db, punch, tc, splitStart, dayStartTime, weeklyWorked, dayStartTime.AddDays(-1)); splitStart = dayStartTime; // To continue adding the rest of the punch } if(splitEnd.Subtract(dayStartTime.AddDays(1)).TotalMinutes < 0) // the punch ended today, we can safely add it { double dailyworked = punch.employee.minutsWorkedDate(db, dayStartTime); bool seventhDay = punch.employee.workedSixPreviousDays(db); addLinesHelper(db, punch, tc, punch.employee.department.DefaultPayType, weeklyWorked, dailyworked, splitStart, splitEnd, seventhDay); } else // The punch ends on the next day { double dailyworked = punch.employee.minutsWorkedDate(db, dayStartTime); bool seventhDay = punch.employee.workedSixPreviousDays(db); addLinesHelper(db, punch, tc, punch.employee.department.DefaultPayType, weeklyWorked, dailyworked, splitStart, dayStartTime.AddDays(1), seventhDay); addLinesDaily(db, punch, tc, dayStartTime.AddDays(1), splitEnd, weeklyWorked, dayStartTime.AddDays(1)); } return true; }
private static bool addLinesHelper(TimeClockContext db, Punch punch, Timecard tc, PayType pt, double weeklyWorked, double dailyWorked, DateTime splitStart, DateTime splitEnd, bool seventhDay) { // a simple base case, to stop spawing extra lines -- Not sure if this is needed if (splitStart.Subtract(splitEnd).TotalMinutes == 0) return true; // Determin the correct pay type for this line. while (weeklyWorked > pt.getWeeklyMax(seventhDay)) pt = pt.NextPayType; while (dailyWorked > pt.getDailyMax(seventhDay)) pt = pt.NextPayType; // Calculate dailyLeft and weeklyLeft double dailyLeft = (double) pt.getDailyMax(seventhDay) - dailyWorked; double weeklyLeft = (double) pt.getWeeklyMax(seventhDay) - dailyWorked; double splitLength = splitEnd.Subtract(splitStart).TotalMinutes; // Check if we reach over the weekly -- if if (weeklyWorked + splitLength > pt.getWeeklyMax(seventhDay)) { addLinesHelper(db, punch, tc, pt, weeklyWorked, dailyWorked, splitStart, splitStart.AddMinutes(weeklyLeft), seventhDay); addLinesHelper(db, punch, tc, pt.NextPayType, weeklyWorked + weeklyLeft, dailyWorked + weeklyLeft, splitStart.AddMinutes(weeklyLeft), splitEnd, seventhDay); } // Check if we reached over the daily limit else if (dailyWorked + splitLength > pt.getDailyMax(seventhDay)) { addLinesHelper(db, punch, tc, pt, weeklyWorked, dailyWorked, splitStart, splitStart.AddMinutes(dailyLeft), seventhDay); addLinesHelper(db, punch, tc, pt.NextPayType, weeklyWorked + dailyLeft, dailyWorked + dailyLeft, splitStart.AddMinutes(dailyLeft), splitEnd, seventhDay); } // we can safely add the line to the DB else { db.Lines.Add(new Line() { TimecardID = tc.TimecardID, PunchID = punch.PunchID, SplitStart = splitStart, SplitEnd = splitEnd, PayTypeID = pt.PayTypeID }); db.SaveChanges(); } return true; }
public HttpResponseMessage<PunchResponse> Punch(PunchRequest request) { Employee emp = db.Employees.FirstOrDefault(e => e.EmployeeID.Equals(request.ID)); if (!emp.Pin.Equals(request.pin)) // the pin didn't match don't do anything { PunchResponse response = new PunchResponse() { isSuccess = false, pinError = "Pin and user did not match.", lines = null, generalError = null }; return new HttpResponseMessage<PunchResponse>(response); } else { var payPeriod = PayPeriodTools.LookupPayPeriod(db, emp.DepartmentID); var curTimeCard = emp.Timecards.SingleOrDefault(tc => tc.PayPeriod == payPeriod.Start); PunchResponse retVal = new PunchResponse() { isSuccess = true, pinError = "", generalError = null }; if (request.closesPunch == -1) // Create a new punch in the DB { Punch temp = new Punch() { EmployeeID = emp.EmployeeID, InTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0), OutTime = null, DepartmentID = emp.DepartmentID, PunchTypeID = Constants.DEFAULT_PUNCH_TYPE // Make this equal to the Regular punch type. }; db.Punches.Add(temp); db.SaveChanges(); var timeCardData = TimeCardView.LinesToTimeCardView(db.Lines.Where(l => l.TimecardID == curTimeCard.TimecardID).OrderBy(l => l.SplitStart)); // We add the last line to just display the information, letting the user know that we register the punch in timeCardData.Add(new TimeCardView() { DateText = DateTime.Now.ToString(@"MM\/dd\/yy"), InText = temp.InTime.ToString(@"hh\:mm"), OutText = "", RegularText = "", OvertimeText = "", DoubletimeText = "" }); retVal.lines = timeCardData; } else // We need to close the last punch and make lines -- Make it split the lines over the payperiod seed { // Set the ending time of the punch Punch currentPunch = db.Punches.First(p => p.PunchID == request.closesPunch); currentPunch.OutTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0); var timeCardData = db.Lines.Where(l => l.TimecardID == curTimeCard.TimecardID).OrderBy(l => l.SplitStart).ToList(); retVal.lines = TimeCardView.LinesToTimeCardView(timeCardData); if (currentPunch.OutTime.Value.Subtract(currentPunch.InTime).TotalMinutes < 1) // punch was shorter than a minut. { db.Punches.Remove(currentPunch); retVal.lines.Add(new TimeCardView() // Make the last line show, but mark is as rapid since it won't get put in the DB { DateText = currentPunch.InTime.ToString(@"MM\/dd\/yy"), InText = currentPunch.InTime.ToString(@"hh\:mm"), OutText = currentPunch.OutTime.Value.ToString(@"hh\:mm"), RegularText = "00:00", OvertimeText = "00:00", DoubletimeText = "00:00", isRapid = true }); } else // Punch was longer than a minut, we add it to the DB. { Calculations.addLines(db, currentPunch); } db.SaveChanges(); } return new HttpResponseMessage<PunchResponse>(retVal); } }