Basit Nisar

Basit Nisar

  • 1.7k
  • 84
  • 11.1k

add validation to check for LastModifiedDate

Apr 14 2023 12:45 PM

Hii, below sharing my function where in i have to add validation that checks for lastmodifiedate if that matches than process runs else throw an error.

DateTime _LastModifiedDateTC = Global.GetTimecardLastModifiedDate(Item.TimeCardID, (int)InvoiceSourceTypes.PerHour ).GetValueOrDefault();

if (Item.LastModifiedDate == _LastModifiedDateTC && IsDateNotMatched == false)

then below code

List<int> StateFarmTimeCardIDs = timeSheetApprovedView.TimeCards.Where(x => x.IsStateFarm)?.Select(x => x.TimeCardID)?.ToList();
List<int> OtherTimeCardIDs = timeSheetApprovedView.TimeCards.Where(x => !x.IsStateFarm)?.Select(x => x.TimeCardID)?.ToList();
List<CIPHApprovedViewModel> lstTimeCards = new List<CIPHApprovedViewModel>();
lstTimeCards = timeSheetApprovedView.TimeCards.ToList();
int? BaseStateProvinceID = null;
CIPHPushReqMod timeCardPushRequest = new CIPHPushReqMod();
if (OtherTimeCardIDs != null && OtherTimeCardIDs.Count > 0)
{
    if (timeSheetApprovedView.TimeCards.Count == 1)
    {
        BaseStateProvinceID = timeSheetApprovedView.TimeCards.FirstOrDefault().BaseStateProvinceID;
    }
    using (SqlConnection connection = new SqlConnection(db.Database.Connection.ConnectionString))
    {
        try
        {
            using (SqlCommand command = new SqlCommand("spGetCIPHForPushToLawson", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@ContractInvoicePerHourIDs", SqlDbType.NVarChar).Value = string.Join(",", OtherTimeCardIDs) as object ?? DBNull.Value;
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    timeCardPushRequest.TimeCardLst = ((IObjectContextAdapter)db).ObjectContext.Translate<CIPHPushReqObj>(reader).ToList();
                    reader.NextResult();
                    timeCardPushRequest.AdditionalComponents = ((IObjectContextAdapter)db).ObjectContext.Translate<CIPHPushReqObj_AdditionalComponent>(reader).ToList();
                }
            }
        }
        catch (Exception)
        {
        }
        finally
        {
            if (connection.State != ConnectionState.Closed)
            {
                connection.Close();
            }
        }
    }
}
var contatDetail = db.ApplicationUsers.Where(x => x.ApplicationUserID == LogedInID && x.IsCatStaff == true).Select(x => new
{
            x.FirstName,
            x.MiddleName,
            x.LastName,
            x.EmployeeNumber,
            x.UserName
        }).FirstOrDefault();
        string UserName = string.Empty;
        if (!string.IsNullOrEmpty(contatDetail.FirstName))
        {
            UserName = contatDetail.FirstName.Trim() + " " + (string.IsNullOrEmpty(contatDetail.LastName) == false ? contatDetail.LastName : "");
        }
        else
        {
            UserName = contatDetail.UserName;
        }
        #region Intregation service class declaration
        TimeCardPushResMod response1 = null;
        CIPHPushResMod response2 = null;
        LawsonAPIService pushToLawsonTimesheet = new LawsonAPIService();
        bool isEndDatePush = false;
        bool StatusLawson = false;
        List<TimesheetPushToLawsonMessageViewModel> timecardMessages = new List<TimesheetPushToLawsonMessageViewModel>();
        BoltOnAPIServices boltOnAPIServices = new BoltOnAPIServices();
        List<BoltOnResponse> boltOnResponses = new List<BoltOnResponse>();
        BoltOnResponse boltOnResponseSF = null;
        BoltOnResponse boltOnResponseHR = null;
        bool isHCM = HCMShared.IsHCMPrimary();
        #endregion
        #region HCM Bolt On Integration
        try
        {
            if (isHCM)
            {
                if (StateFarmTimeCardIDs != null && StateFarmTimeCardIDs.Count > 0)
                {
                    foreach (var item in StateFarmTimeCardIDs)
                    {
                        string BranchNumber = contextTimesheet.vw_TimeSheetConstructTypeSummary.FirstOrDefault(t => StateFarmTimeCardIDs.Contains(t.TimeCardID)).BranchNumber ?? string.Empty;
                        HCMIntegration.BoltOnTimecardView hcm = boltOnAPIServices.BoltOnTimeCardPush(string.Join(",", item), BranchNumber);
                        boltOnResponseSF = await boltOnAPIServices.AddTimecard(hcm);
                        if (boltOnResponseSF != null)
                        {
                            if (!string.IsNullOrEmpty(boltOnResponseSF.Status))
                            {
                                int tsID = Convert.ToInt32(boltOnResponseSF.Status);
                                TimeSheetStatusType timeSheetStatusType = db.TimeSheetStatusTypes.Where(t => t.TimeSheetStatusTypeID == tsID).FirstOrDefault();
                                TimesheetPushToLawsonMessageViewModel objMessage = new TimesheetPushToLawsonMessageViewModel
                                {
                                    Message = tsID == 5 ? Global.StatusMessage.TimesheetPushedToLawson : timeSheetStatusType?.TimeSheetStatusTypeName ?? boltOnResponseHR.Message,
                                    MsgNbr = tsID,
                                    TimeCardId = item
                                };
                                timecardMessages.Add(objMessage);
                                boltOnAPIServices.UpadteStateFarmTS(item, UserName, LogedInID, Convert.ToInt32(boltOnResponseSF.Status));
                            }
                        }
                    }
                    StatusLawson = timecardMessages.Count == 0 ? false : true;
                }
                if (OtherTimeCardIDs != null && OtherTimeCardIDs.Count > 0 && (StatusLawson || StateFarmTimeCardIDs == null || StateFarmTimeCardIDs.Count == 0))
                {
                    foreach (CIPHPushReqObj tc in timeCardPushRequest.TimeCardLst)
                    {
                        BoltOnTimecardView hcm = boltOnAPIServices.BoltOnCIPHPush(tc, timeCardPushRequest);
                        boltOnResponseHR = await boltOnAPIServices.AddTimecard(hcm);
                        if (boltOnResponseHR != null)
                        {
                            if (!string.IsNullOrEmpty(boltOnResponseHR.Status))
                            {
                                int tsID = Convert.ToInt32(boltOnResponseHR.Status);
                                TimeSheetStatusType timeSheetStatusType = db.TimeSheetStatusTypes.Where(t => t.TimeSheetStatusTypeID == tsID).FirstOrDefault();
                                TimesheetPushToLawsonMessageViewModel objMessage = new TimesheetPushToLawsonMessageViewModel
                                {
                                    Message = tsID == 5 ? Global.StatusMessage.TimesheetPushedToLawson : timeSheetStatusType?.TimeSheetStatusTypeName ?? boltOnResponseHR.Message,
                                    MsgNbr = tsID,
                                    TimeCardId = tc.ContractInvoicePerHourID
                                };
                                timecardMessages.Add(objMessage);
                                boltOnAPIServices.UpadteHourlyTS(tc.ContractInvoicePerHourID, UserName, LogedInID, Convert.ToInt32(boltOnResponseHR.Status));
                            }
                        }
                    }
                    StatusLawson = timecardMessages.Count == 0 ? false : true;
                    try
                    {
                        if (StatusLawson && BaseStateProvinceID != null && BaseStateProvinceID > 0 && OtherTimeCardIDs.Count == 1)
                        {
                            var timeCard = db.ContractInvoicePerHours.Find(OtherTimeCardIDs.FirstOrDefault());
                            timeCard.BaseStateProvinceID = BaseStateProvinceID;
                            db.Entry(timeCard).State = EntityState.Modified;
                            await db.SaveChangesAsync();
                        }
                    }
                    catch (Exception _e)
                    {
                        Global.InsertException(_e);
                    }
                }
            }
            else
            {
                // Add in parrelle Bolton DB
                if (StateFarmTimeCardIDs != null && StateFarmTimeCardIDs.Count > 0)
                {
                    foreach (var item in StateFarmTimeCardIDs)
                    {
                        string BranchNumber = contextTimesheet.vw_TimeSheetConstructTypeSummary.FirstOrDefault(t => StateFarmTimeCardIDs.Contains(t.TimeCardID)).BranchNumber ?? string.Empty;
                        HCMIntegration.BoltOnTimecardView hcm = boltOnAPIServices.BoltOnTimeCardPush(string.Join(",", item), BranchNumber);
                        HCMIntegration.Services.BoltOnService.BoltOnParallelService bol = new HCMIntegration.Services.BoltOnService.BoltOnParallelService();
                        int z = await bol.AddTimecardParallel(hcm, 1, item, contextTimesheet.TimeCards.Find(item).ContactID);
                    }
                }
                if (OtherTimeCardIDs != null && OtherTimeCardIDs.Count > 0)
                {
                    foreach (CIPHPushReqObj tc in timeCardPushRequest.TimeCardLst)
                    {
                        BoltOnTimecardView hcm = boltOnAPIServices.BoltOnCIPHPush(tc, timeCardPushRequest);
                        HCMIntegration.Services.BoltOnService.BoltOnParallelService bol = new HCMIntegration.Services.BoltOnService.BoltOnParallelService();
                        int z = await bol.AddTimecardParallel(hcm, 2, tc.ContractInvoicePerHourID, tc.ContactID);
                    }
                }
                #region send to lawson
                #region Push To Lawson Intregation Service
                try
                {
                    if (StateFarmTimeCardIDs != null && StateFarmTimeCardIDs.Count > 0)
                    {
                        string BranchNumber = contextTimesheet.vw_TimeSheetConstructTypeSummary.FirstOrDefault(t => StateFarmTimeCardIDs.Contains(t.TimeCardID)).BranchNumber ?? string.Empty;
                        response1 = pushToLawsonTimesheet.TimeCardPush(string.Join(",", StateFarmTimeCardIDs), BranchNumber, UserName, LogedInID, "Secret");
                        if (response1 == null)
                        {
                            StatusLawson = false;
                            return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { Status = Global.Status.Invalid.ToString(), Message = "Failed to connect the Payroll Push service" }));
                        }
                        StatusLawson = !response1.IsFailed;
                    }
                    if (OtherTimeCardIDs != null && OtherTimeCardIDs.Count > 0 && (StatusLawson || StateFarmTimeCardIDs == null || StateFarmTimeCardIDs.Count == 0))
                    {
                        response2 = pushToLawsonTimesheet.CIPHPush(timeCardPushRequest, UserName, LogedInID, "Secret");
                        if (response2 == null)
                        {
                            StatusLawson = false;
                            return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { Status = Global.Status.Invalid.ToString(), Message = "Failed to connect the Payroll Push service" }));
                        }
                        StatusLawson = !response2.IsFailed;
                    }
                    if (!StatusLawson)
                    {
                        return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { Status = Global.Status.Invalid.ToString(), Message = response1?.FailedReason ?? response2?.FailedReason ?? string.Empty }));
                    }
                    else
                    {
                        #region Get Response Message from TCPushResObjLst
                        if (response1 != null && response1.TCPushResObjLst != null && response1.TCPushResObjLst.Count() > 0)
                        {
                            foreach (var item in response1.TCPushResObjLst)
                            {
                                TimesheetPushToLawsonMessageViewModel objMessage = new TimesheetPushToLawsonMessageViewModel();
                                objMessage.Message = item.MsgNbr == 0 ? Global.StatusMessage.TimesheetPushedToLawson : item.Message;
                                objMessage.MsgNbr = item.MsgNbr;
                                objMessage.TimeCardId = item.TimeCardId;
                                timecardMessages.Add(objMessage);
                            }
                        }
                        if (response2 != null && response2.TCPushResObjLst != null && response2.TCPushResObjLst.Count() > 0)
                        {
                            foreach (var item in response2.TCPushResObjLst)
                            {
                                TimesheetPushToLawsonMessageViewModel objMessage = new TimesheetPushToLawsonMessageViewModel();
                                objMessage.Message = item.MsgNbr == 0 ? Global.StatusMessage.TimesheetPushedToLawson : item.Message;
                                objMessage.MsgNbr = item.MsgNbr;
                                objMessage.TimeCardId = item.TimeCardId;
                                timecardMessages.Add(objMessage);
                            }
                            try
                            {
                                if (BaseStateProvinceID != null && BaseStateProvinceID > 0 && response2.TCPushResObjLst.Count() == 1)
                                {
                                    var timecardLawsonDetail = response2.TCPushResObjLst.FirstOrDefault();
                                    //if (timecardLawsonDetail.MsgNbr == 0)
                                    //{
                                    var timeCard = db.ContractInvoicePerHours.Find(timecardLawsonDetail.TimeCardId);
                                    timeCard.BaseStateProvinceID = BaseStateProvinceID;
                                    db.Entry(timeCard).State = EntityState.Modified;
                                    await db.SaveChangesAsync();
                                    //}
                                }
                            }
                            catch (Exception _e)
                            {
                                Global.InsertException(_e);
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    Global.InsertException(ex);
                }
                #endregion
                #endregion
            }
        }
        catch (Exception _ex)
        {
            Global.InsertException(_ex);
            return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { Status = Global.Status.Invalid.ToString(), Message = Global.StatusMessage.Invalid, MessageDetail = _ex.Message + _ex.InnerException }));
        }
        #endregion
        if (StatusLawson)
        {
            if (StateFarmTimeCardIDs != null)
            {
                foreach (var item in StateFarmTimeCardIDs)
                {
                    TimesheetPushToLawsonMessageViewModel Message = timecardMessages.FirstOrDefault(t => t.TimeCardId == item);
                    //We need to fetch from Config file later ie MsgNbr==107
                    if (Message.MsgNbr == 107 && Message.TimeCardId != null && Message.TimeCardId > 0)
                    {
                        int ContactAssignmentPSId = contextTimesheet.TimeCards.FirstOrDefault(t => t.TimeCardID == item).ContactAssignmentPSId;
                        if (isHCM)
                        {
                            //var res = await boltOnAPIServices.BoltOnCompRulePush(ContactAssignmentPSId, LogedInID);
                        }
                        else
                        {
                            //True:  for Inactive Assignment whose completion date is in past
                            //False: for Active Assignment whose completion date is either null or  in future 
                            isEndDatePush = !contextTimesheet.vw_TimeSheetContactAssignmentSummary.Any(t => t.ContactAssignmentPayStructureID == ContactAssignmentPSId && DbFunctions.TruncateTime(t.CompletionDate) >= DbFunctions.TruncateTime(DateTime.Now));
                            PushToLawsonTimesheet pushAssignment = new PushToLawsonTimesheet();
                            Models.AssignmentResponse resp = pushAssignment.PushAssignmentToLawson(ContactAssignmentPSId, isEndDatePush);
                        }
                    }
                    #region Notfication Section
                    TimeCard tm = contextTimesheet.TimeCards.FirstOrDefault(t => t.TimeCardID == item);
                    int contactID = tm.ContactID;
                    int branchID = tm.BranchId;
                    try
                    {
                        #region Via Stored Procedure
                        //Insert
                        //string dateRange = tm.WeekStartDate.Date.ToString() + "-" + tm.WeekStartDate.AddDays(6).Date.ToString();
                        // CHange date take full date and time
                        string dateRange = tm.WeekStartDate.ToString("MM/dd/yyyy").ToString() + "-" + tm.WeekStartDate.AddDays(6).ToString("MM/dd/yyyy");
                        InsertNotificationViewModel insertNotification = new InsertNotificationViewModel();
                        insertNotification.NotificationMessageID = Convert.ToInt32(Global.NotificationMessageID.TimesheetApproved);
                        insertNotification.LandingPageID = Convert.ToInt32(Global.NotificationLandingPageID.TimesheetApprovedTab);
                        insertNotification.ContactID = contactID;
                        insertNotification.TaskID = item;
                        insertNotification.BranchID = branchID;
                        insertNotification.DateRange = dateRange;
                        Global.InsertNotification(insertNotification);
                        //Send
                        Global.SendNotification();
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Global.InsertException(ex);
                    }
                    #endregion
                }
            }
            if (OtherTimeCardIDs != null && timeCardPushRequest != null && timeCardPushRequest.TimeCardLst != null)
            {
                foreach (var item in timeCardPushRequest.TimeCardLst)
                {
                    TimesheetPushToLawsonMessageViewModel Message = timecardMessages.FirstOrDefault(t => t.TimeCardId == item.ContractInvoicePerHourID);
                    //We need to fetch from Config file later ie MsgNbr==107
                    if (Message.MsgNbr == 107 && Message.TimeCardId != null && Message.TimeCardId > 0)
                    {
                        if (isHCM)
                        {
                            //var res = await boltOnAPIServices.BoltOnCompRulePush(item.ContactAssignmentPSId, LogedInID);
                        }
                        else
                        {
                            //True:  for Inactive Assignment whose completion date is in past
                            //False: for Active Assignment whose completion date is either null or  in future 
                            isEndDatePush = item.CompletionDate == null || item.CompletionDate >= DateTime.Now ? false : true;
                            PushToLawsonTimesheet pushAssignment = new PushToLawsonTimesheet();
                            Models.AssignmentResponse resp = pushAssignment.PushAssignmentToLawson(item.ContactAssignmentPSId, isEndDatePush);
                        }
                    }
                    #region Notfication Section
                    try
                    {
                        string dateRange = item.WeekStartDate.ToString("MM/dd/yyyy") + "-" + item.WeekEndDate.ToString("MM/dd/yyyy");
                        InsertNotificationViewModel insertNotification = new InsertNotificationViewModel();
                        insertNotification.NotificationMessageID = Convert.ToInt32(Global.NotificationMessageID.TimesheetApproved);
                        insertNotification.LandingPageID = Convert.ToInt32(Global.NotificationLandingPageID.TimesheetApprovedTab);
                        insertNotification.ContactID = item.ContactID;
                        insertNotification.TaskID = item.ContractInvoicePerHourID;
                        insertNotification.BranchID = item.BranchID;
                        insertNotification.DateRange = dateRange;
                        Global.InsertNotification(insertNotification);
                        Global.SendNotification();
                    }
                    catch (Exception ex)
                    {
                        Global.InsertException(ex);
                    }
                    #endregion
                }
            }
            return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new { Status = Global.Status.OK.ToString(), Message = Global.StatusMessage.Updated.ToString(), MessageDetail = timecardMessages }));
       }
        else
        {
            return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new { Status = Global.Status.Invalid.ToString(), Message = "" }));
        }
    }
    catch (Exception ex)
    {
        Global.InsertException(ex);
        return this.ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { Status = Global.Status.Invalid.ToString(), Message = Global.StatusMessage.Invalid, MessageDetail = ex.Message + ex.InnerException }));
    }
}

 


Answers (1)