private void SaveDelta(Delta delta) { if (MODE == "DATABASE") { NmsContext nmsContext = new NmsContext(); DeltaModel deltaModel = new DeltaModel(); deltaModel.Time = DateTime.Now; deltaModel.Delta = ObjectToByteArray(delta); nmsContext.DeltaModels.Add(deltaModel); nmsContext.SaveChanges(); string message = string.Format("Insert new Delta into database successfully finished. "); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); Console.WriteLine(message); } else { bool fileExisted = false; if (File.Exists(Config.Instance.ConnectionString)) { fileExisted = true; } FileStream fs = new FileStream(Config.Instance.ConnectionString, FileMode.OpenOrCreate, FileAccess.ReadWrite); fs.Seek(0, SeekOrigin.Begin); BinaryReader br = null; int deltaCount = 0; if (fileExisted) { br = new BinaryReader(fs); deltaCount = br.ReadInt32(); } BinaryWriter bw = new BinaryWriter(fs); fs.Seek(0, SeekOrigin.Begin); delta.Id = ++deltaCount; byte[] deltaSerialized = delta.Serialize(); int deltaLength = deltaSerialized.Length; bw.Write(deltaCount); fs.Seek(0, SeekOrigin.End); bw.Write(deltaLength); bw.Write(deltaSerialized); if (br != null) { br.Close(); br.Dispose(); } bw.Close(); bw.Dispose(); fs.Close(); fs.Dispose(); } }
protected override async Task SetTeamsIdsAsync(DeltaModel <TimeOffModel> delta, CacheModel <TimeOffModel> savedRecords, TeamActivityModel activityModel, ILogger log) { var allTimeOff = delta.All; // set time off reasons await SetTimeOffReasonAsync(allTimeOff, savedRecords.Tracked, activityModel, log).ConfigureAwait(false); // set teams employee await SetTeamsEmployeeIdsAsync(allTimeOff.Where(s => string.IsNullOrEmpty(s.TeamsEmployeeId)), activityModel.TeamId).ConfigureAwait(false); }
private async Task UpdateScheduleAsync(TeamActivityModel activityModel, DeltaModel <ShiftModel> delta) { // apply the final delta to the current version of the savedShifts ensuring that no // other process can update it while we do so - N.B. the minimum lease time is 15s, the // maximum lease time is 1m var savedShifts = await _scheduleCacheService.LoadScheduleWithLeaseAsync(GetSaveScheduleId(activityModel.TeamId), activityModel.StartDate, new TimeSpan(0, 0, _options.StorageLeaseTimeSeconds)); delta.ApplyChanges(savedShifts.Tracked); delta.ApplySkipped(savedShifts.Skipped); await _scheduleCacheService.SaveScheduleWithLeaseAsync(GetSaveScheduleId(activityModel.TeamId), activityModel.StartDate, savedShifts); }
/// <summary> /// Returns a list that contains all the <see cref="DeltaModel"/> that meet given criteria. /// </summary> /// <param name="codeName">The Name of the code.</param> /// <param name="startCode">The starting of the code.</param> /// <param name="lastUpdateDate">Last update date.</param> /// <param name="lastUpdateVersion">Last update version.</param> /// <param name="rowPosition">Row position.</param> /// <param name="maxRows">Maximum rows to returned.</param> /// <param name="wsType">WS type.</param> /// <returns>The list of all the <see cref="DeltaModel"/> that meet the specified criteria.</returns> public IList <DeltaModel> GetDeltaList(string codeName, string startCode, DateTime lastUpdateDate, int lastUpdateVersion = 0, int rowPosition = 0, int maxRows = 0, bool wsType = false) { var keymodel = new KeyModel("DeltaList").Add(codeName).Add(startCode).Add(lastUpdateDate).Add(lastUpdateVersion).Add(rowPosition).Add(maxRows).Add(wsType); IList <DeltaModel> list; if (!CacheService.TryGet(keymodel, out list)) { var sqlParameters = new List <SqlParameter>(); var storedProc = "up_ListCodeDelta"; sqlParameters.Add(new SqlParameter { ParameterName = "@Code_Type", SqlDbType = SqlDbType.VarChar, Value = codeName }); sqlParameters.Add(new SqlParameter { ParameterName = "@StartingCode", SqlDbType = SqlDbType.VarChar, Value = startCode }); sqlParameters.Add(new SqlParameter { ParameterName = "@LastUpdatedDate", SqlDbType = SqlDbType.DateTime, Value = lastUpdateDate }); sqlParameters.Add(new SqlParameter { ParameterName = "@MaxRows", SqlDbType = SqlDbType.Int, Value = maxRows }); list = SqlService.Execute <DeltaModel>(ConnectionName, storedProc, sqlParameters, dataReader => { var model = new DeltaModel(); model.Code = dataReader["code"].ToString(); model.LongDescription = dataReader["long_desc"].ToString(); model.ShortDescription = dataReader["short_desc"].ToString(); if (!dataReader.IsDBNull(3)) { model.CurrencyStartDate = (DateTime)dataReader[3]; } if (!dataReader.IsDBNull(4)) { model.CurrencyEndDate = (DateTime)dataReader[4]; } return(model); }).ToList(); if (!list.Any()) { CacheService.Set(keymodel, list); } } return(list); }
protected override async Task SetTeamsIdsAsync(DeltaModel <ShiftModel> delta, CacheModel <ShiftModel> savedRecords, TeamActivityModel activityModel, ILogger log) { var allRecords = delta.All; // set job & department name var jobLookup = BuildJobLookup(savedRecords.Tracked); await SetJobAndDepartmentNameAsync(allRecords, jobLookup, activityModel, log).ConfigureAwait(false); // set teams schedule group (N.B this must be set after jobs) await SetTeamsSchedulingGroupIdAsync(allRecords.Where(s => string.IsNullOrEmpty(s.TeamsSchedulingGroupId)), activityModel, log).ConfigureAwait(false); }
/// <summary> /// Extension method for mapping <see cref="DeltaModel"/> to <see cref="DeltaViewModel"/>. /// </summary> /// <param name="deltaModel"><see cref="DeltaModel"/> instance.</param> /// <returns>Instance of <see cref="DeltaViewModel"/>.</returns> public static DeltaViewModel ToDeltaViewModel(this DeltaModel deltaModel) { if (deltaModel == null) { return(null); } return(new DeltaViewModel { Code = deltaModel.Code, CurrencyEnd = deltaModel.CurrencyEndDate != null?deltaModel.CurrencyEndDate.Value.ToString() : deltaModel.CurrencyEnd, CurrencyStart = deltaModel.CurrencyStartDate != null?deltaModel.CurrencyStartDate.Value.ToString() : deltaModel.CurrencyStart, LongDescription = deltaModel.LongDescription, ShortDescription = deltaModel.ShortDescription }); }
private async Task AddEmployeesToSchedulingGroups(DeltaModel delta, IDictionary <string, string> groupLookup, WeekModel weekModel, ILogger log) { var allShifts = delta.All; foreach (var department in groupLookup.Keys) { // get all the user id's in this department var userIds = GetAllUsersInDepartment(allShifts, department); if (userIds.Count > 0) { try { // and add them to the matching schedule group if necessary await _scheduleDestinationService.AddUsersToSchedulingGroupAsync(weekModel.TeamId, groupLookup[department], userIds); } catch (Exception e) { delta.Created.Concat(delta.Updated).Where(i => i.DepartmentName == department).ForEach(i => delta.FailedChange(i)); log.LogSchedulingGroupError(e, weekModel, department, groupLookup[department]); continue; } } } }
public static void LogAppliedDelta(this ILogger log, WeekModel week, DeltaModel delta) { log.LogDelta(Stage.Applied, week, delta); }
protected abstract Task ApplyDeltaAsync(TeamActivityModel activityModel, DeltaModel <T> delta, ILogger log);
public static void LogDelta(this ILogger log, string stage, WeekModel week, DeltaModel delta) { log.LogInformation(new EventId(3, "Delta"), "Delta: Stage={stage}, Created={createdCount}, Updated={updatedCount}, Deleted={deletedCount}, Failed={failedCount}, Skipped={skippedCount}, TeamId={teamId}, WeekDate={weekDate}", stage, delta.Created.Count, delta.Updated.Count, delta.Deleted.Count, delta.Failed.Count, delta.Skipped.Count, week.TeamId, week.StartDate.AsDateString()); }
public static void LogPartialDelta(this ILogger log, WeekModel week, DeltaModel delta) { log.LogDelta(Stage.Partial, week, delta); }
protected abstract Task SetTeamsIdsAsync(DeltaModel <T> delta, CacheModel <T> savedRecords, TeamActivityModel activityModel, ILogger log);
protected override async Task UpdateSavedRecordsAsync(TeamActivityModel activityModel, CacheModel <ShiftModel> savedRecords, DeltaModel <ShiftModel> delta) { var policy = GetConflictRetryPolicy(_options.RetryMaxAttempts, _options.RetryIntervalSeconds); await policy.ExecuteAsync(() => UpdateScheduleAsync(activityModel, delta)); }
protected override async Task SetTeamsIdsAsync(DeltaModel <EmployeeAvailabilityModel> delta, CacheModel <EmployeeAvailabilityModel> savedRecords, TeamActivityModel activityModel, ILogger log) { // set teams employee ids await SetTeamsEmployeeIdsAsync(delta.All.Where(s => string.IsNullOrEmpty(s.TeamsEmployeeId))).ConfigureAwait(false); }
protected override async Task ApplyDeltaAsync(TeamActivityModel activityModel, DeltaModel <EmployeeAvailabilityModel> delta, ILogger log) { // Teams does not support creating availability items, so we must simply do an update // instead of a create await UpdateDestinationAsync(nameof(delta.Created), activityModel, delta, delta.Created, _teamsService.UpdateAvailabilityAsync, log).ConfigureAwait(false); await UpdateDestinationAsync(nameof(delta.Updated), activityModel, delta, delta.Updated, _teamsService.UpdateAvailabilityAsync, log).ConfigureAwait(false); await UpdateDestinationAsync(nameof(delta.Deleted), activityModel, delta, delta.Deleted, _teamsService.DeleteAvailabilityAsync, log).ConfigureAwait(false); }
public static void LogAppliedDelta <T>(this ILogger log, string teamId, string dateValue, DeltaModel <T> delta, string itemType = "Shifts") where T : IDeltaItem { log.LogDelta(Stage.Applied, teamId, dateValue, delta, itemType); }
private async Task ApplyDeltaAsync(WeekModel weekModel, DeltaModel delta, ILogger log) { await UpdateDestinationAsync(nameof(delta.Created), weekModel, delta, delta.Created, _scheduleDestinationService.CreateShiftAsync, log); await UpdateDestinationAsync(nameof(delta.Updated), weekModel, delta, delta.Updated, _scheduleDestinationService.UpdateShiftAsync, log); await UpdateDestinationAsync(nameof(delta.Deleted), weekModel, delta, delta.Deleted, _scheduleDestinationService.DeleteShiftAsync, log); }
private async Task UpdateDestinationAsync(string operation, TeamActivityModel activityModel, DeltaModel <T> delta, T record, Func <string, T, bool, Task> destinationMethod, ILogger log) { try { await destinationMethod(activityModel.TeamId, record, false).ConfigureAwait(false); } catch (ArgumentException) { delta.SkippedChange(record); LogRecordSkipped(activityModel, operation, record, log); } catch (Exception ex) { delta.FailedChange(record); LogRecordError(ex, activityModel, operation, record, log); } }
protected virtual async Task UpdateSavedRecordsAsync(TeamActivityModel activityModel, CacheModel <T> savedRecords, DeltaModel <T> delta) { delta.ApplyChanges(savedRecords.Tracked); delta.ApplySkipped(savedRecords.Skipped); await SaveRecordsAsync(activityModel, savedRecords).ConfigureAwait(false); }
protected async Task UpdateDestinationAsync(string operation, TeamActivityModel activityModel, DeltaModel <T> delta, IEnumerable <T> records, Func <string, T, bool, Task> destinationMethod, ILogger log) { var tasks = records .Select(record => UpdateDestinationAsync(operation, activityModel, delta, record, destinationMethod, log)) .ToArray(); await Task.WhenAll(tasks); }
private async Task UpdateDestinationAsync(string operation, WeekModel weekModel, DeltaModel delta, IEnumerable <ShiftModel> shifts, Func <string, ShiftModel, Task> destinationMethod, ILogger log) { var tasks = shifts .Select(shift => UpdateDestinationAsync(operation, weekModel, delta, shift, destinationMethod, log)) .ToArray(); await Task.WhenAll(tasks); }
public static void LogDelta <T>(this ILogger log, string stage, string teamId, string dateValue, DeltaModel <T> delta, string itemType = "Shifts") where T : IDeltaItem { log.LogInformation(EventIds.Delta, "Delta_{itemType}: Stage={stage}, Created={createdCount}, Updated={updatedCount}, Deleted={deletedCount}, Failed={failedCount}, Skipped={skippedCount}, TeamId={teamId}, DateValue={dateValue}", itemType, stage, delta.Created.Count, delta.Updated.Count, delta.Deleted.Count, delta.Failed.Count, delta.Skipped.Count, teamId, dateValue); }