public ChangeCredentialsStatus ChangeUserName(IUserBasic userBasic, string newUserName) { string userName = newUserName.RemoveMaliciousTags() .RemoveScriptTags() .RemoveMaliciousSQLCharacters() .DefuseScriptTags(); if (userName != newUserName) { return(ChangeCredentialsStatus.UserNameNotValid); } ChangeCredentialsStatus changeCredentialsStatus; try { using (IDataStoreContext dataStoreContext = this.DataStore.CreateContext()) changeCredentialsStatus = dataStoreContext.wm_Users_UpdateUserName(userBasic.UserId, newUserName); } catch (Exception ex) { _Log.Error("Error at Users_UpdateUserName", ex); throw new DataStoreException(ex, true); } if (changeCredentialsStatus == ChangeCredentialsStatus.Success) { _Log.InfoFormat("User {0} changed username from {1} to {2}.", userBasic.UserId, userBasic.UserName, newUserName); userBasic.UserName = newUserName; } return(changeCredentialsStatus); }
public ChangeCredentialsStatus ChangeEmail(IUserBasic userBasic, string newEmail) { if (!ValidationExpressions.IsValidEmail(newEmail)) { return(ChangeCredentialsStatus.EmailNotValid); } ChangeCredentialsStatus changeCredentialsStatus; try { using (IDataStoreContext dataStoreContext = this.DataStore.CreateContext()) changeCredentialsStatus = dataStoreContext.wm_Users_UpdateEmail(userBasic.UserId, newEmail); } catch (Exception ex) { _Log.Error("Error at Users_UpdateUserName", ex); throw new DataStoreException(ex, true); } if (changeCredentialsStatus == ChangeCredentialsStatus.Success) { _Log.InfoFormat("User {0} changed email from {1} to {2}.", userBasic.UserId, userBasic.Email, newEmail); userBasic.Email = newEmail; } return(changeCredentialsStatus); }
private static void ImportJson (IDataStoreContext ctx, WorkspaceUserData data, WorkspaceUserJson json) { var workspaceId = GetLocalId<WorkspaceData> (ctx, json.WorkspaceId); var user = GetByRemoteId<UserData> (ctx, json.UserId, null); // Update linked user data: if (user == null) { user = new UserData () { RemoteId = json.UserId, Name = json.Name, Email = json.Email, DefaultWorkspaceId = workspaceId, ModifiedAt = DateTime.MinValue, }; } else { user.Name = json.Name; user.Email = json.Email; } user = ctx.Put (user); data.IsAdmin = json.IsAdmin; data.IsActive = json.IsActive; data.WorkspaceId = workspaceId; data.UserId = user.Id; ImportCommonJson (data, json); }
public ChangePasswordStatus ResetPassword(int applicationId, IUserBasic userBasic, string newPassword) { string text = this.GenerateSalt(); ValidatePasswordStatus result = ValidatePasswordStatus.Valid; if (!this.IsPasswordValid(newPassword, text, out result)) { return((ChangePasswordStatus)result); } ChangePasswordStatus changePasswordStatus; try { using (IDataStoreContext dataStoreContext = this.DataStore.CreateContext()) { changePasswordStatus = dataStoreContext.wm_Users_SetPassword(userBasic.UserId, this.EncodePassword(newPassword, text, this.PasswordFormat), text, (byte)this.PasswordFormat) == 0 ? ChangePasswordStatus.NoRecordRowAffected : ChangePasswordStatus.Success; } } catch (Exception ex) { _Log.Error("Error at ResetPassword.Users_SetPassword", ex); throw new DataStoreException(ex, true); } if (changePasswordStatus == ChangePasswordStatus.Success) { _Log.InfoFormat("User {0} changed password", userBasic.UserId); } return(changePasswordStatus); }
private static void ImportJson(IDataStoreContext ctx, WorkspaceUserData data, WorkspaceUserJson json) { var workspaceId = GetLocalId <WorkspaceData> (ctx, json.WorkspaceId); var user = GetByRemoteId <UserData> (ctx, json.UserId, null); // Update linked user data: if (user == null) { user = new UserData() { RemoteId = json.UserId, Name = json.Name, Email = json.Email, DefaultWorkspaceId = workspaceId, ModifiedAt = DateTime.MinValue, }; } else { user.Name = json.Name; user.Email = json.Email; } user = ctx.Put(user); data.IsAdmin = json.IsAdmin; data.IsActive = json.IsActive; data.WorkspaceId = workspaceId; data.UserId = user.Id; ImportCommonJson(data, json); }
/// <summary> /// Gets the content level nodes. /// </summary> /// <returns></returns> public Dictionary <int, ICMSContentLevelNode> GetContentLevelNodes() { Dictionary <int, ICMSContentLevelNode> records = new Dictionary <int, ICMSContentLevelNode>(); try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { foreach (ICMSContentLevelNode record in dataStoreContext.cms_ContentLevelNodes_Get()) { records[record.ContentLevelNodeId] = record; } } } catch (Exception ex) { _Log.Error("Error at cms_ContentLevelNodes_Get", ex); throw new DataStoreException(ex, true); } foreach (ICMSContentLevelNode record in records.Values) { if (record.ParentContentLevelNodeId.HasValue) { record.Parent = records[record.ParentContentLevelNodeId.Value]; records[record.ParentContentLevelNodeId.Value].Children.Add(record); } } return(records); }
internal BusinessObjectActionReport <DataRepositoryActionStatus> DeleteTemporaryFiles(IUserBasic userBasic, FileType fileType) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { num = dataStoreContext.cms_FilesTemp_DeleteByUserId(userBasic.UserId, fileType); } } catch (Exception ex) { _Log.Error("Error at cms_FilesTemp_DeleteByUserId", ex); throw new DataStoreException(ex, true); } if (num != -1002) { if (num != 0) { businessObjectActionReport.Status = DataRepositoryActionStatus.SqlError; _Log.ErrorFormat("Temporary profile images of user with id {0} were not deleted from the database (ErrorCode: {1}).", userBasic.UserId , num); } } else { businessObjectActionReport.Status = DataRepositoryActionStatus.NoRecordRowAffected; _Log.ErrorFormat("Temporary profile images of user with id {0} were not deleted from the database (ErrorCode: {1}).", userBasic.UserId , num); } return(businessObjectActionReport); }
public static ClientData Import(this ClientJson json, IDataStoreContext ctx, Guid?localIdHint = null, ClientData mergeBase = null) { var converter = ServiceContainer.Resolve <ClientJsonConverter> (); return(converter.Import(ctx, json, localIdHint, mergeBase)); }
internal BusinessObjectActionReport <DataRepositoryActionStatus> Delete(CMSThreadRating cmsThreadRating) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); businessObjectActionReport.ValidationResult = BusinessObjectManager.Validate(cmsThreadRating); if (businessObjectActionReport.ValidationResult.IsValid) { int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { num = dataStoreContext.cms_ThreadRatings_Delete(cmsThreadRating.CMSUserId, cmsThreadRating.CMSThreadId); } } catch (Exception ex) { _Log.Error("Error at cms_ThreadRatings_Delete", ex); throw new DataStoreException(ex, true); } if (num != 0) { businessObjectActionReport.Status = DataRepositoryActionStatus.SqlError; _Log.WarnFormat("CMSThreadRating {0} was not deleted from the database (ErrorCode: {1})." , DebugUtility.GetObjectString(cmsThreadRating), num); } } else { businessObjectActionReport.Status = DataRepositoryActionStatus.ValidationFailed; _Log.WarnFormat("CMSThreadRating {0} was not deleted from the database because the validation failed.\nReport: {1}", DebugUtility.GetObjectString(cmsThreadRating), businessObjectActionReport.ValidationResult.ToString(TextFormat.ASCII)); } return(businessObjectActionReport); }
internal BusinessObjectActionReport <DataRepositoryActionStatus> Delete(int fileId) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { num = dataStoreContext.cms_Files_Delete(fileId); } } catch (Exception ex) { _Log.Error("Error at cms_Files_Delete", ex); throw new DataStoreException(ex, true); } if (num == 0) { businessObjectActionReport.Status = DataRepositoryActionStatus.SqlError; _Log.ErrorFormat("CMSFile {0} was not deleted from the database (ErrorCode: {1}).", fileId, num); } return(businessObjectActionReport); }
internal bool IncreaseTotalViews(CMSContent content, int viewsToAdd) { int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { num = dataStoreContext.cms_Contents_IncreaseTotalViews(content.CMSContentId, viewsToAdd); } } catch (Exception ex) { _Log.Error("Error at cms_Contents_IncreaseTotalViews", ex); throw new DataStoreException(ex, true); } if (num == 1) { content.TotalViews += viewsToAdd; return(true); } else { _Log.WarnFormat("Unable to increase total views for ConentId {0}. No record rows affected", content.CMSBaseContentId); return(false); } }
internal BusinessObjectActionReport <DataRepositoryActionStatus> Update(CMSGroup cmsGroup) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); businessObjectActionReport.ValidationResult = BusinessObjectManager.Validate(cmsGroup); if (businessObjectActionReport.ValidationResult.IsValid) { try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) businessObjectActionReport.Status = (DataRepositoryActionStatus)dataStoreContext.cms_Groups_InsertOrUpdate(cmsGroup.CMSGroupId, cmsGroup.Name, cmsGroup.Description, cmsGroup.CMSGroupType); return(businessObjectActionReport); } catch (Exception ex) { _Log.Error("Error at cms_Groups_InsertOrUpdate", ex); throw new DataStoreException(ex, true); } } else { businessObjectActionReport.Status = DataRepositoryActionStatus.ValidationFailed; _Log.WarnFormat("CMSGroup {0} was not updated at the database because the validation failed.\nReport: {1}" , DebugUtility.GetObjectString(cmsGroup) , businessObjectActionReport.ValidationResult.ToString(TextFormat.ASCII)); } return(businessObjectActionReport); }
public BusinessObjectActionReport <DataRepositoryActionStatus> Delete(IApplication application) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); businessObjectActionReport.ValidationResult = BusinessObjectManager.Validate(application); if (businessObjectActionReport.ValidationResult.IsValid) { int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) num = dataStoreContext.wm_Applications_Delete(application.ApplicationId); } catch (Exception ex) { _Log.Error("Error at wm_Applications_Delete", ex); throw new DataStoreException(ex, true); } if (num == 0) { businessObjectActionReport.Status = DataRepositoryActionStatus.SqlError; _Log.WarnFormat("Application {0} was not deleted from the database (ErrorCode: {1})." , DebugUtility.GetObjectString(application) , num); } } else { businessObjectActionReport.Status = DataRepositoryActionStatus.ValidationFailed; _Log.WarnFormat("Application {0} was not deleted from the database because the validation failed.\nReport: {1}" , DebugUtility.GetObjectString(application) , businessObjectActionReport.ValidationResult.ToString(TextFormat.ASCII)); } return(businessObjectActionReport); }
public void CreateRolesIfNotExist(int applicationId, string[] userRoles) { try { using (IDataStoreContext dataStoreContext = this.DataStore.CreateContext()) { foreach (string role in userRoles) { try { dataStoreContext.wm_Roles_InsertIfNotExists(applicationId, role, null); } catch (Exception ex) { _Log.Error("Error at wm_Roles_InsertIfNotExists", ex); throw new DataStoreException(ex, true); } } } } catch (Exception ex) { _Log.Error("Error at wm_Roles_InsertIfNotExists", ex); throw new DataStoreException(ex, true); } }
internal BusinessObjectActionReport <DataRepositoryActionStatus> DeleteTemporaryFile(int fileId, int userId) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { num = dataStoreContext.cms_FilesTemp_Delete(fileId, userId); } } catch (Exception ex) { _Log.Error("Error at cms_FilesTemp_Delete", ex); throw new DataStoreException(ex, true); } if (num != -1002) { if (num != 0) { businessObjectActionReport.Status = DataRepositoryActionStatus.SqlError; _Log.ErrorFormat("Temporary CMSFile with id {0} was not deleted from the database (ErrorCode: {1}).", fileId, num); } } else { businessObjectActionReport.Status = DataRepositoryActionStatus.NoRecordRowAffected; _Log.InfoFormat("Temporary CMSFile with id {0} was not deleted from the database (ErrorCode: {1}).", fileId, num); } return(businessObjectActionReport); }
public async Task <List <ValidationError> > ProvideAsync(IDataStoreContext dataStoreContext, CancellationToken cancellationToken) { using (var stream = await _fileService.OpenReadStreamAsync(dataStoreContext.ValidationErrors, dataStoreContext.Container, cancellationToken)) { return(_jsonSerializationService.Deserialize <List <ValidationError> >(stream)); } }
/// <summary> /// Renames the content level node. /// </summary> /// <param name="contentLevelNodeId">The content level node id.</param> /// <param name="name">The name.</param> /// <returns></returns> public bool RenameContentLevelNode(int contentLevelNodeId, string name) { if (string.IsNullOrWhiteSpace(name)) { return(false); } int num; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { num = dataStoreContext.cms_ContentLevelNodes_Update(contentLevelNodeId, HttpUtility.HtmlEncode(name)); } } catch (Exception ex) { _Log.Error("Error at cms_ContentLevelNodes_Update", ex); throw new DataStoreException(ex, true); } if (num != 0) { _Log.ErrorFormat("Conten level node {0} was not renamed to {2} (ErrorCode: {1})." , contentLevelNodeId , num , name); return(false); } return(true); }
public static int PurgeDatedTimeCorrections(this IDataStoreContext ctx, DateTime time) { var tbl = ctx.Connection.GetMapping <TimeCorrectionData> ().TableName; var q = String.Concat("DELETE FROM ", tbl, " WHERE MeasuredAt < ?"); return(ctx.Connection.Execute(q, time)); }
public WorkspaceUserJson Export(IDataStoreContext ctx, WorkspaceUserData data) { var userRows = ctx.Connection.Table <UserData> () .Where(m => m.Id == data.UserId).Take(1).ToList(); if (userRows.Count == 0) { throw new InvalidOperationException(String.Format( "Cannot export data with invalid local relation ({0}#{1}) to JSON.", typeof(UserData).Name, data.UserId )); } var user = userRows [0]; if (user.RemoteId == null) { throw new RelationRemoteIdMissingException(typeof(UserData), data.UserId); } var workspaceId = GetRemoteId <WorkspaceData> (ctx, data.WorkspaceId); return(new WorkspaceUserJson() { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc(), IsAdmin = data.IsAdmin, IsActive = data.IsActive, Name = user.Name, Email = user.Email, WorkspaceId = workspaceId, UserId = user.RemoteId.Value, }); }
private List<string> GetTimeEntryTags (IDataStoreContext ctx, Guid id) { if (id == Guid.Empty) { return new List<string> (0); } return ctx.GetTimeEntryTagNames (id); }
private static void AddDefaultTags(IDataStoreContext ctx, Guid workspaceId, Guid timeEntryId) { // Check that there aren't any tags set yet: var tagCount = ctx.Connection.Table <TimeEntryTagData> () .Count(r => r.TimeEntryId == timeEntryId && r.DeletedAt == null); if (tagCount > 0) { return; } var defaultTag = ctx.Connection.Table <TagData> () .Where(r => r.Name == DefaultTag && r.WorkspaceId == workspaceId && r.DeletedAt == null) .FirstOrDefault(); if (defaultTag == null) { var newDefaultTag = new TagData { Name = DefaultTag, WorkspaceId = workspaceId, }; Model <TagData> .MarkDirty(newDefaultTag); defaultTag = ctx.Put(newDefaultTag); } ctx.Put(new TimeEntryTagData() { TimeEntryId = timeEntryId, TagId = defaultTag.Id, }); }
public async Task <bool> WriteAsync(IDataStoreContext dataStoreContext, IDataStoreCache cache, CancellationToken cancellationToken) { using (var connection = new OleDbConnection(string.Format(MdbConstants.MdbConnectionStringTemplate, dataStoreContext.ExportOutputLocation))) { await connection.OpenAsync(cancellationToken); var exports = _exports .Where(e => dataStoreContext.Tasks.Contains(e.TaskKey, StringComparer.OrdinalIgnoreCase)) .OrderBy(e => e.TaskOrder); _logger.LogInfo("Starting Export"); foreach (var export in exports) { await export.ExportAsync(cache, connection, dataStoreContext.ExportOutputLocation, cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); _logger.LogInfo("Finished Export"); } return(true); }
public FM36HistoryData MapData(FM36Global fm36Global, IDataStoreContext dataStoreContext) { return(new FM36HistoryData() { AppsEarningsHistories = MapAppsEarningsHistory(fm36Global, dataStoreContext.ReturnCode, dataStoreContext.CollectionYear).ToList(), }); }
public ClientData Import (IDataStoreContext ctx, ClientJson json, Guid? localIdHint = null, ClientData mergeBase = null) { var data = GetByRemoteId<ClientData> (ctx, json.Id.Value, localIdHint); var merger = mergeBase != null ? new ClientMerger (mergeBase) : null; if (merger != null && data != null) merger.Add (new ClientData (data)); if (json.DeletedAt.HasValue) { if (data != null) { ctx.Delete (data); data = null; } } else if (merger != null || ShouldOverwrite (data, json)) { data = data ?? new ClientData (); ImportJson (ctx, data, json); if (merger != null) { merger.Add (data); data = merger.Result; } data = ctx.Put (data); } return data; }
public static CommonData Import (this CommonJson json, IDataStoreContext ctx, Guid? localIdHint = null, CommonData mergeBase = null) { var type = json.GetType (); if (type == typeof (ClientJson)) { return Import ((ClientJson)json, ctx, localIdHint, (ClientData)mergeBase); } else if (type == typeof (ProjectJson)) { return Import ((ProjectJson)json, ctx, localIdHint, (ProjectData)mergeBase); } else if (type == typeof (ProjectUserJson)) { return Import ((ProjectUserJson)json, ctx, localIdHint, (ProjectUserData)mergeBase); } else if (type == typeof (TagJson)) { return Import ((TagJson)json, ctx, localIdHint, (TagData)mergeBase); } else if (type == typeof (TaskJson)) { return Import ((TaskJson)json, ctx, localIdHint, (TaskData)mergeBase); } else if (type == typeof (TimeEntryJson)) { return Import ((TimeEntryJson)json, ctx, localIdHint, (TimeEntryData)mergeBase); } else if (type == typeof (UserJson)) { return Import ((UserJson)json, ctx, localIdHint, (UserData)mergeBase); } else if (type == typeof (WorkspaceJson)) { return Import ((WorkspaceJson)json, ctx, localIdHint, (WorkspaceData)mergeBase); } else if (type == typeof (WorkspaceUserJson)) { return Import ((WorkspaceUserJson)json, ctx, localIdHint, (WorkspaceUserData)mergeBase); } throw new InvalidOperationException (String.Format ("Unknown type of {0}", type)); }
public WorkspaceUserJson Export (IDataStoreContext ctx, WorkspaceUserData data) { var userRows = ctx.Connection.Table<UserData> () .Take (1).Where (m => m.Id == data.UserId).ToList (); if (userRows.Count == 0) { throw new InvalidOperationException (String.Format ( "Cannot export data with invalid local relation ({0}#{1}) to JSON.", typeof(UserData).Name, data.UserId )); } var user = userRows [0]; if (user.RemoteId == null) { throw new RelationRemoteIdMissingException (typeof(UserData), data.UserId); } var workspaceId = GetRemoteId<WorkspaceData> (ctx, data.WorkspaceId); return new WorkspaceUserJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), IsAdmin = data.IsAdmin, IsActive = data.IsActive, Name = user.Name, Email = user.Email, WorkspaceId = workspaceId, UserId = user.RemoteId.Value, }; }
/// <summary> /// Gets the system profile images. /// </summary> /// <returns></returns> public Dictionary <string, SystemProfileImage> GetSystemProfileImages(int applicationId) { Dictionary <string, SystemProfileImage> records = new Dictionary <string, SystemProfileImage>(); try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) { foreach (CMSFile cmsFile in dataStoreContext.cms_Files_GetMultiple(applicationId, FileType.SystemProfileImage)) { if (!string.IsNullOrWhiteSpace(cmsFile.FriendlyFileName)) { records[cmsFile.FriendlyFileName] = new SystemProfileImage(cmsFile); } } } } catch (Exception ex) { _Log.Error("Error at cms_Files_Get", ex); throw new DataStoreException(ex, true); } return(records); }
public TimeEntryJson Export(IDataStoreContext ctx, TimeEntryData data) { var userId = GetRemoteId <UserData> (ctx, data.UserId); var workspaceId = GetRemoteId <WorkspaceData> (ctx, data.WorkspaceId); var projectId = GetRemoteId <ProjectData> (ctx, data.ProjectId); var taskId = GetRemoteId <TaskData> (ctx, data.TaskId); var tags = GetTimeEntryTags(ctx, data.Id); return(new TimeEntryJson() { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc(), Description = data.Description, IsBillable = data.IsBillable, StartTime = data.StartTime.ToUtc(), StopTime = data.StopTime.ToUtc(), DurationOnly = data.DurationOnly, Duration = EncodeDuration(data), Tags = tags, UserId = userId, WorkspaceId = workspaceId, ProjectId = projectId, TaskId = taskId, }); }
public BusinessObjectActionReport <DataRepositoryActionStatus> Update(IDepartmentModel department) { BusinessObjectActionReport <DataRepositoryActionStatus> businessObjectActionReport = new BusinessObjectActionReport <DataRepositoryActionStatus>(DataRepositoryActionStatus.Success); businessObjectActionReport.ValidationResult = BusinessObjectManager.Validate(department); if (businessObjectActionReport.ValidationResult.IsValid) { int num; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) num = dataStoreContext.wm_Departments_Update(department.DepartmentId, department.ParentDepartmentId, department.Name, department.OfficeId); } catch (Exception ex) { _Log.Error("Error at wm_Departments_Update", ex); throw new DataStoreException(ex, true); } if (num == 0) { businessObjectActionReport.Status = DataRepositoryActionStatus.NoRecordRowAffected; _Log.ErrorFormat("Department {0} was not updated at the database, NoRecordRowAffected" , DebugUtility.GetObjectString(department)); } } else { businessObjectActionReport.Status = DataRepositoryActionStatus.ValidationFailed; _Log.WarnFormat("Department {0} was not updated at the database because the validation failed.\nReport: {1}" , DebugUtility.GetObjectString(department) , businessObjectActionReport.ValidationResult.ToString(TextFormat.ASCII)); } return(businessObjectActionReport); }
private void PopulateDataStoreCache(IDataStoreCache cache, IDataStoreContext dataStoreContext, IMessage message, IEnumerable <FM70Learner> learners, int ukprn) { var academicYear = $"20{dataStoreContext.CollectionYear.Substring(0, 2)}/{dataStoreContext.CollectionYear.Substring(2, 2)}"; var collectionReturnCode = dataStoreContext.CollectionPeriod; var collectionType = $"ILR{dataStoreContext.CollectionYear}"; cache.Add(BuildLatestProviderSubmission(ukprn, collectionReturnCode, collectionType)); if (learners == null) { return; } var conRefNumberDictionary = BuildConRefNumberDictionary(message); var learningDeliveryPeriodisedValues = learners .SelectMany(l => l.LearningDeliveries .SelectMany(ld => ld.LearningDeliveryDeliverableValues .Select(ldd => new FundModelESFLearningDeliveryPeriodisedValue <List <LearningDeliveryDeliverablePeriodisedValue> >(ukprn, l.LearnRefNumber, ld.AimSeqNumber.Value, ldd.DeliverableCode, ldd.LearningDeliveryDeliverablePeriodisedValues)))); learningDeliveryPeriodisedValues .NullSafeForEach(ldpv => ldpv.LearningDeliveryPeriodisedValue .NullSafeForEach(learningDeliveryPeriodisedValue => cache.Add(BuildFundingData(dataStoreContext, learningDeliveryPeriodisedValue, conRefNumberDictionary, ukprn, ldpv.AimSeqNumber, ldpv.LearnRefNumber, ldpv.EsfDeliverableCode, academicYear, collectionReturnCode, collectionType)))); }
public ESFFundingData BuildFundingData(IDataStoreContext dataStoreContext, LearningDeliveryDeliverablePeriodisedValue lddpv, Dictionary <string, Dictionary <int, string> > conRefNumberDictionary, int ukprn, int aimSeqNumber, string learnRefNumber, string deliverableCode, string academicYear, string collectionReturnCode, string collectionType) { var conRefNumber = GetConRefNumber(conRefNumberDictionary, aimSeqNumber, learnRefNumber); return(new ESFFundingData() { UKPRN = ukprn, LearnRefNumber = learnRefNumber, AimSeqNumber = aimSeqNumber, ConRefNumber = conRefNumber, DeliverableCode = deliverableCode, AttributeName = lddpv.AttributeName, Period_1 = lddpv.Period1, Period_2 = lddpv.Period2, Period_3 = lddpv.Period3, Period_4 = lddpv.Period4, Period_5 = lddpv.Period5, Period_6 = lddpv.Period6, Period_7 = lddpv.Period7, Period_8 = lddpv.Period8, Period_9 = lddpv.Period9, Period_10 = lddpv.Period10, Period_11 = lddpv.Period11, Period_12 = lddpv.Period12, AcademicYear = academicYear, CollectionReturnCode = collectionReturnCode, CollectionType = collectionType }); }
public DataRepositoryActionStatus SetToSent(int emailId, EmailStatus status, EmailPriority priority) { int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) num = dataStoreContext.wm_Emails_SetToSent(emailId, status, priority); } catch (Exception ex) { _Log.Error("Error at wm_Emails_SetToSent", ex); throw new DataStoreException(ex, true); } if (num == 0) { _Log.WarnFormat("Email {0} was not set to sent (ErrorCode: {1})." , emailId , num); return(DataRepositoryActionStatus.NoRecordRowAffected); } return(DataRepositoryActionStatus.Success); }
public static WorkspaceUserData Import(this WorkspaceUserJson json, IDataStoreContext ctx, Guid?localIdHint = null, WorkspaceUserData mergeBase = null) { var converter = ServiceContainer.Resolve <WorkspaceUserJsonConverter> (); return(converter.Import(ctx, json, localIdHint, mergeBase)); }
public DataRepositoryActionStatus Delete(int emailId) { int num = 0; try { using (IDataStoreContext dataStoreContext = this._DataStore.CreateContext()) num = dataStoreContext.wm_Emails_Delete(emailId); } catch (Exception ex) { _Log.Error("Error at wm_Emails_Delete", ex); throw new DataStoreException(ex, true); } if (num == 0) { _Log.WarnFormat("Email {0} was not deleted from the database (ErrorCode: {1})." , emailId , num); return(DataRepositoryActionStatus.NoRecordRowAffected); } return(DataRepositoryActionStatus.Success); }
public TimeEntryData Import(IDataStoreContext ctx, TimeEntryJson json, Guid?localIdHint = null, TimeEntryData mergeBase = null) { var log = ServiceContainer.Resolve <ILogger> (); var data = GetByRemoteId <TimeEntryData> (ctx, json.Id.Value, localIdHint); var merger = mergeBase != null ? new TimeEntryMerger(mergeBase) : null; if (merger != null && data != null) { merger.Add(new TimeEntryData(data)); } if (json.DeletedAt.HasValue) { if (data != null) { // TODO: Delete TimeEntryTag intermediate data log.Info(Tag, "Deleting local data for {0}.", data.ToIdString()); ctx.Delete(data); data = null; } } else if (merger != null || ShouldOverwrite(data, json)) { data = data ?? new TimeEntryData(); ImportJson(ctx, data, json); if (merger != null) { merger.Add(data); data = merger.Result; } if (merger != null) { log.Info(Tag, "Importing {0}, merging with local data.", data.ToIdString()); } else { log.Info(Tag, "Importing {0}, replacing local data.", data.ToIdString()); } data = ctx.Put(data); // Also update tags from the JSON we are merging: if (mergeBase == null || (mergeBase != null && mergeBase.ModifiedAt != data.ModifiedAt)) { log.Info(Tag, "Resetting tags for {0}.", data.ToIdString()); ResetTags(ctx, data, json); } } else { log.Info(Tag, "Skipping import of {0}.", json.ToIdString()); } return(data); }
public ClientJson Export (IDataStoreContext ctx, ClientData data) { var workspaceId = GetRemoteId<WorkspaceData> (ctx, data.WorkspaceId); return new ClientJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), Name = data.Name, WorkspaceId = workspaceId, }; }
private static void ImportJson (IDataStoreContext ctx, ProjectUserData data, ProjectUserJson json) { var projectId = GetLocalId<ProjectData> (ctx, json.ProjectId); var userId = GetLocalId<UserData> (ctx, json.UserId); data.HourlyRate = json.HourlyRate; data.IsManager = json.IsManager; data.ProjectId = projectId; data.UserId = userId; ImportCommonJson (data, json); }
private static void Merge (IDataStoreContext ctx, TaskData data, TaskJson json) { var projectId = GetLocalId<ProjectData> (ctx, json.ProjectId); var workspaceId = GetLocalId<WorkspaceData> (ctx, json.WorkspaceId); data.Name = json.Name; data.IsActive = json.IsActive; data.Estimate = json.Estimate; data.ProjectId = projectId; data.WorkspaceId = workspaceId; MergeCommon (data, json); }
public ProjectUserJson Export (IDataStoreContext ctx, ProjectUserData data) { var projectId = GetRemoteId<ProjectData> (ctx, data.ProjectId); var userId = GetRemoteId<UserData> (ctx, data.UserId); return new ProjectUserJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), HourlyRate = data.HourlyRate, IsManager = data.IsManager, ProjectId = projectId, UserId = userId, }; }
public TaskJson Export (IDataStoreContext ctx, TaskData data) { var projectId = GetRemoteId<ProjectData> (ctx, data.ProjectId); var workspaceId = GetRemoteId<WorkspaceData> (ctx, data.WorkspaceId); return new TaskJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), Name = data.Name, IsActive = data.IsActive, Estimate = data.Estimate, ProjectId = projectId, WorkspaceId = workspaceId, }; }
public TagData Import (IDataStoreContext ctx, TagJson json, Guid? localIdHint = null, bool forceUpdate = false) { var data = GetByRemoteId<TagData> (ctx, json.Id.Value, localIdHint); if (json.DeletedAt.HasValue) { if (data != null) { ctx.Delete (data); data = null; } } else if (data == null || forceUpdate || data.ModifiedAt < json.ModifiedAt) { data = Merge (ctx, data, json); data = ctx.Put (data); } return data; }
public WorkspaceJson Export (IDataStoreContext ctx, WorkspaceData data) { return new WorkspaceJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), Name = data.Name, IsPremium = data.IsPremium, DefaultRate = data.DefaultRate, DefaultCurrency = data.DefaultCurrency, OnlyAdminsMayCreateProjects = data.ProjectCreationPrivileges == AccessLevel.Admin, OnlyAdminsSeeBillableRates = data.BillableRatesVisibility == AccessLevel.Admin, RoundingMode = data.RoundingMode, RoundingPercision = data.RoundingPercision, LogoUrl = data.LogoUrl, }; }
public ProjectJson Export (IDataStoreContext ctx, ProjectData data) { var workspaceId = GetRemoteId<WorkspaceData> (ctx, data.WorkspaceId); var clientId = GetRemoteId<ClientData> (ctx, data.ClientId); return new ProjectJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), Name = data.Name, Color = data.Color.ToString (), IsActive = data.IsActive, IsBillable = data.IsBillable, IsPrivate = data.IsPrivate, IsTemplate = data.IsTemplate, UseTasksEstimate = data.UseTasksEstimate, WorkspaceId = workspaceId, ClientId = clientId, }; }
private static void ImportJson (IDataStoreContext ctx, UserData data, UserJson json) { var defaultWorkspaceId = GetLocalId<WorkspaceData> (ctx, json.DefaultWorkspaceId); data.Name = json.Name; data.Email = json.Email; data.StartOfWeek = json.StartOfWeek; data.DateFormat = json.DateFormat; data.TimeFormat = json.TimeFormat; data.ImageUrl = json.ImageUrl; data.Locale = json.Locale; data.Timezone = json.Timezone; data.SendProductEmails = json.SendProductEmails; data.SendTimerNotifications = json.SendTimerNotifications; data.SendWeeklyReport = json.SendWeeklyReport; data.TrackingMode = json.StoreStartAndStopTime ? TrackingMode.StartNew : TrackingMode.Continue; data.DefaultWorkspaceId = defaultWorkspaceId; ImportCommonJson (data, json); }
private static TagData ImportJson (IDataStoreContext ctx, TagData data, TagJson json) { var workspaceId = GetLocalId<WorkspaceData> (ctx, json.WorkspaceId); if (data == null) { // Fallback to name lookup for unsynced tags: var rows = ctx.Connection.Table<TagData> ().Take (1) .Where (r => r.WorkspaceId == workspaceId && r.Name == json.Name && r.RemoteId == null); data = rows.FirstOrDefault (); } // As a last chance create new tag: data = data ?? new TagData (); data.Name = json.Name; data.WorkspaceId = workspaceId; ImportCommonJson (data, json); return data; }
private static void ImportJson (IDataStoreContext ctx, ProjectData data, ProjectJson json) { var workspaceId = GetLocalId<WorkspaceData> (ctx, json.WorkspaceId); var clientId = GetLocalId<ClientData> (ctx, json.ClientId); data.Name = json.Name; try { data.Color = Convert.ToInt32 (json.Color); } catch { data.Color = ProjectModel.DefaultColor; } data.IsActive = json.IsActive; data.IsBillable = json.IsBillable; data.IsPrivate = json.IsPrivate; data.IsTemplate = json.IsTemplate; data.UseTasksEstimate = json.UseTasksEstimate; data.WorkspaceId = workspaceId; data.ClientId = clientId; ImportCommonJson (data, json); }
public ClientData Import (IDataStoreContext ctx, ClientJson json, Guid? localIdHint = null, ClientData mergeBase = null) { var log = ServiceContainer.Resolve<ILogger> (); var data = GetByRemoteId<ClientData> (ctx, json.Id.Value, localIdHint); var merger = mergeBase != null ? new ClientMerger (mergeBase) : null; if (merger != null && data != null) { merger.Add (new ClientData (data)); } if (json.DeletedAt.HasValue) { if (data != null) { log.Info (Tag, "Deleting local data for {0}.", data.ToIdString ()); ctx.Delete (data); data = null; } } else if (merger != null || ShouldOverwrite (data, json)) { data = data ?? new ClientData (); ImportJson (ctx, data, json); if (merger != null) { merger.Add (data); data = merger.Result; } if (merger != null) { log.Info (Tag, "Importing {0}, merging with local data.", data.ToIdString ()); } else { log.Info (Tag, "Importing {0}, replacing local data.", data.ToIdString ()); } data = ctx.Put (data); } else { log.Info (Tag, "Skipping import of {0}.", json.ToIdString ()); } return data; }
public UserJson Export (IDataStoreContext ctx, UserData data) { var defaultWorkspaceId = GetRemoteId<WorkspaceData> (ctx, data.DefaultWorkspaceId); return new UserJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), Name = data.Name, Email = data.Email, StartOfWeek = data.StartOfWeek, DateFormat = data.DateFormat, TimeFormat = data.TimeFormat, ImageUrl = data.ImageUrl, Locale = data.Locale, Timezone = data.Timezone, SendProductEmails = data.SendProductEmails, SendTimerNotifications = data.SendTimerNotifications, SendWeeklyReport = data.SendWeeklyReport, StoreStartAndStopTime = data.TrackingMode == TrackingMode.StartNew, DefaultWorkspaceId = defaultWorkspaceId, }; }
public static CommonJson Export (this CommonData data, IDataStoreContext ctx) { var type = data.GetType (); if (type == typeof (ClientData)) { return Export ((ClientData)data, ctx); } else if (type == typeof (ProjectData)) { return Export ((ProjectData)data, ctx); } else if (type == typeof (ProjectUserData)) { return Export ((ProjectUserData)data, ctx); } else if (type == typeof (TagData)) { return Export ((TagData)data, ctx); } else if (type == typeof (TaskData)) { return Export ((TaskData)data, ctx); } else if (type == typeof (TimeEntryData)) { return Export ((TimeEntryData)data, ctx); } else if (type == typeof (UserData)) { return Export ((UserData)data, ctx); } else if (type == typeof (WorkspaceData)) { return Export ((WorkspaceData)data, ctx); } else if (type == typeof (WorkspaceUserData)) { return Export ((WorkspaceUserData)data, ctx); } throw new InvalidOperationException (String.Format ("Unknown type of {0}", type)); }
public TimeEntryJson Export (IDataStoreContext ctx, TimeEntryData data) { var userId = GetRemoteId<UserData> (ctx, data.UserId); var workspaceId = GetRemoteId<WorkspaceData> (ctx, data.WorkspaceId); var projectId = GetRemoteId<ProjectData> (ctx, data.ProjectId); var taskId = GetRemoteId<TaskData> (ctx, data.TaskId); var tags = GetTimeEntryTags (ctx, data.Id); return new TimeEntryJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt.ToUtc (), Description = data.Description, IsBillable = data.IsBillable, StartTime = data.StartTime.ToUtc (), StopTime = data.StopTime.ToUtc (), DurationOnly = data.DurationOnly, Duration = EncodeDuration (data), Tags = tags, UserId = userId, WorkspaceId = workspaceId, ProjectId = projectId, TaskId = taskId, }; }
public static TagData Import (this TagJson json, IDataStoreContext ctx, Guid? localIdHint = null, TagData mergeBase = null) { var converter = ServiceContainer.Resolve<TagJsonConverter> (); return converter.Import (ctx, json, localIdHint, mergeBase); }
public static WorkspaceJson Export (this WorkspaceData data, IDataStoreContext ctx) { var converter = ServiceContainer.Resolve<WorkspaceJsonConverter> (); return converter.Export (ctx, data); }
private static void ImportJson (IDataStoreContext ctx, ClientData data, ClientJson json) { data.Name = json.Name; data.WorkspaceId = GetLocalId<WorkspaceData> (ctx, json.WorkspaceId); ImportCommonJson (data, json); }
public static ClientJson Export (this ClientData data, IDataStoreContext ctx) { var converter = ServiceContainer.Resolve<ClientJsonConverter> (); return converter.Export (ctx, data); }
public static ProjectUserJson Export (this ProjectUserData data, IDataStoreContext ctx) { var converter = ServiceContainer.Resolve<ProjectUserJsonConverter> (); return converter.Export (ctx, data); }
public TimeEntryData Import (IDataStoreContext ctx, TimeEntryJson json, Guid? localIdHint = null, TimeEntryData mergeBase = null) { var data = GetByRemoteId<TimeEntryData> (ctx, json.Id.Value, localIdHint); var merger = mergeBase != null ? new TimeEntryMerger (mergeBase) : null; if (merger != null && data != null) merger.Add (new TimeEntryData (data)); if (json.DeletedAt.HasValue) { if (data != null) { // TODO: Delete TimeEntryTag intermediate data ctx.Delete (data); data = null; } } else if (merger != null || ShouldOverwrite (data, json)) { data = data ?? new TimeEntryData (); ImportJson (ctx, data, json); if (merger != null) { merger.Add (data); data = merger.Result; } data = ctx.Put (data); // Also update tags from the JSON we are merging: if (mergeBase == null || (mergeBase != null && mergeBase.ModifiedAt != data.ModifiedAt)) { ResetTags (ctx, data, json); } } return data; }
private static void ImportJson (IDataStoreContext ctx, TimeEntryData data, TimeEntryJson json) { var userId = GetUserLocalId (ctx, json.UserId); var workspaceId = GetLocalId<WorkspaceData> (ctx, json.WorkspaceId); var projectId = GetLocalId<ProjectData> (ctx, json.ProjectId); var taskId = GetLocalId<TaskData> (ctx, json.TaskId); data.Description = json.Description; data.IsBillable = json.IsBillable; data.DurationOnly = json.DurationOnly; data.UserId = userId; data.WorkspaceId = workspaceId; data.ProjectId = projectId; data.TaskId = taskId; DecodeDuration (data, json); ImportCommonJson (data, json); }
private static void ResetTags (IDataStoreContext ctx, TimeEntryData timeEntryData, TimeEntryJson json) { // Don't touch the tags when the field is null if (json.Tags == null) { return; } var con = ctx.Connection; // Resolve tags to IDs: var tagIds = new List<Guid> (); foreach (var tagName in json.Tags) { // Prevent importing empty (invalid) tags: if (String.IsNullOrWhiteSpace (tagName)) { continue; } var id = ctx.GetTagIdFromName (timeEntryData.WorkspaceId, tagName); if (id == Guid.Empty) { // Need to create a new tag: var tagData = new TagData () { Name = tagName, WorkspaceId = timeEntryData.WorkspaceId, }; con.Insert (tagData); id = timeEntryData.Id; } tagIds.Add (id); } // Iterate over TimeEntryTags and determine which to keep and which to discard: var inters = con.Table<TimeEntryTagData> ().Where (m => m.TimeEntryId == timeEntryData.Id); var toDelete = new List<TimeEntryTagData> (); foreach (var inter in inters) { if (tagIds.Contains (inter.TagId)) { tagIds.Remove (inter.TagId); } else { toDelete.Add (inter); } } // Delete unused tags intermediate rows: foreach (var inter in toDelete) { ctx.Delete (inter); } // Create new intermediate rows: foreach (var tagId in tagIds) { ctx.Put (new TimeEntryTagData () { TagId = tagId, TimeEntryId = timeEntryData.Id, }); } }
public TimeEntryData Import (IDataStoreContext ctx, TimeEntryJson json, Guid? localIdHint = null, TimeEntryData mergeBase = null) { var log = ServiceContainer.Resolve<ILogger> (); var data = GetByRemoteId<TimeEntryData> (ctx, json.Id.Value, localIdHint); var merger = mergeBase != null ? new TimeEntryMerger (mergeBase) : null; if (merger != null && data != null) { merger.Add (new TimeEntryData (data)); } if (json.DeletedAt.HasValue) { if (data != null) { // TODO: Delete TimeEntryTag intermediate data log.Info (Tag, "Deleting local data for {0}.", data.ToIdString ()); ctx.Delete (data); data = null; } } else if (merger != null || ShouldOverwrite (data, json)) { data = data ?? new TimeEntryData (); ImportJson (ctx, data, json); if (merger != null) { merger.Add (data); data = merger.Result; } if (merger != null) { log.Info (Tag, "Importing {0}, merging with local data.", data.ToIdString ()); } else { log.Info (Tag, "Importing {0}, replacing local data.", data.ToIdString ()); } data = ctx.Put (data); // Also update tags from the JSON we are merging: if (mergeBase == null || (mergeBase != null && mergeBase.ModifiedAt != data.ModifiedAt)) { log.Info (Tag, "Resetting tags for {0}.", data.ToIdString ()); ResetTags (ctx, data, json); } } else { log.Info (Tag, "Skipping import of {0}.", json.ToIdString ()); } return data; }
private static Guid GetUserLocalId (IDataStoreContext ctx, long id) { if (id == 0) { var authManager = ServiceContainer.Resolve<AuthManager> (); if (authManager.User == null) { throw new ArgumentException ("Cannot import TimeEntry with missing user when no authenticated user.", "id"); } return authManager.User.Id; } return GetLocalId<UserData> (ctx, id); }