/// <summary> /// Checks if Exists the specified Source Journal Name. /// </summary> /// <param name="sourceCode">Source Journal Name</param> /// <param name="id">SourceJournalName</param> /// <returns>True if Source Journal Name exists.</returns> internal SourceJournalProfileViewModel <T> IsExist(string sourceCode, string id) { var exist = false; var model = new T { SourceJournalName = id }; if (SessionHelper.Get <List <SourceCode> >(_sourceJournalProfileCacheKey) != null) { exist = SessionHelper.Get <List <SourceCode> >(_sourceJournalProfileCacheKey) .Any(selectionCriteria => (selectionCriteria.Source == sourceCode && selectionCriteria.IsDeleted != true)); } else { var viewModel = GetSourceJournal(-1, -1, -1, model); if (viewModel != null && viewModel.Data.SourceCodeList != null && viewModel.Data.SourceCodeList.Items.Any()) { SessionHelper.Set(_sourceJournalProfileCacheKey, viewModel.Data.SourceCodeList.Items.ToList()); exist = SessionHelper.Get <List <SourceCode> >(_sourceJournalProfileCacheKey) .Any(selectioncriteria => (selectioncriteria.Source == sourceCode && selectioncriteria.IsDeleted != true)); } } UserMessage userMessage; var errorList = new List <EntityError>(); if (exist) { //Build custom error message. var entityError = new EntityError { Message = string.Format(CommonResx.DuplicateMessage, SourceJournalProfileResx.SourceJournalProfile, sourceCode), Priority = Priority.Error }; errorList.Add(entityError); userMessage = new UserMessage { IsSuccess = false, Errors = errorList }; } else { userMessage = new UserMessage { IsSuccess = true }; } return(new SourceJournalProfileViewModel <T> { IsSourceCodeExists = exist, UserMessage = userMessage }); }
public AppEntityErrorsException(EntityInfo entityInfo, object key, string propertyName, string message) : base(new List <EntityError>()) { // TODO add this constructor to breeze var ee = new EntityError() { EntityTypeName = entityInfo.Entity.GetType().Name, ErrorMessage = message, KeyValues = new object[] { key }, PropertyName = propertyName }; this.EntityErrors.Add(ee); }
/// <summary> /// Get a SegmentCodes /// </summary> /// <param name="id">Id for SegmentCodes</param> /// <returns>JSON object for SegmentCodes</returns> internal SegmentCodesViewModel <T> GetById(string id) { var viewModel = new SegmentCodesViewModel <T>(); // Remove cached data while page refreshing SessionHelper.Remove(_segmentCodesCacheKey); viewModel.UserAccess = GetAccessRights(); var itemSegmentService = Context.Container.Resolve <IItemSegmentService <ItemSegment> >(new ParameterOverride("context", Context)); var segmentname = itemSegmentService.Get(); if (segmentname.Items != null && segmentname.Items.Any()) { foreach (var items in segmentname.Items) { viewModel.Segments.Add(new SegmentName { Text = items.Description, Value = items.SegmentNumber, SegmentLength = items.Length, SegmentNumber = items.SegmentNumber }); } viewModel.SegmentNameLength = Convert.ToInt32(segmentname.Items.First().Length); viewModel.SegmentNumber = segmentname.Items.First().SegmentNumber; viewModel.UserMessage = new UserMessage(segmentname); viewModel.TotalResultsCount = viewModel.TotalResultsCount; viewModel.Data = viewModel.Data ?? new T(); } else { var errorList = new List <EntityError>(); var entityError = new EntityError { Message = SegmentCodesResx.NoSegments, Priority = Priority.Error }; errorList.Add(entityError); viewModel.UserMessage = new UserMessage { IsSuccess = false, Errors = errorList }; } return(viewModel); }
protected void CheckForKeyUpdate(EntityInfo entityInfo, IClassMetadata classMeta) { if (classMeta.HasIdentifierProperty && entityInfo.OriginalValuesMap != null && entityInfo.OriginalValuesMap.ContainsKey(classMeta.IdentifierPropertyName)) { var errors = new EntityError[1] { new EntityError() { EntityTypeName = entityInfo.Entity.GetType().FullName, ErrorMessage = "Cannot update part of the entity's key", ErrorName = "KeyUpdateException", KeyValues = GetIdentifierAsArray(entityInfo.Entity, classMeta), PropertyName = classMeta.IdentifierPropertyName } }; throw new EntityErrorsException("Cannot update part of the entity's key", errors); } }
///// <summary> ///// Get account formatted number and description ///// </summary> ///// <param name="id"> account code</param> ///// <param name="nonExistent"> account code not exist</param> ///// <param name="inactive"> account code inactive</param> ///// <returns>list of account number and description</returns> //private List<string> GetAccountDescription(string id, LockedFiscalPeriod nonExistent, LockedFiscalPeriod inactive) //{ // var accountService = Context.Container.Resolve<IAccountService<Account>>(new ParameterOverride("context", Context)); // var account = accountService.GetById(id); // if (string.IsNullOrEmpty(account.AccountNumber)) // case of account id does not exist // { // var error = GenerateAccountDescriptionEntityError(nonExistent, CommonResx.RecordNotFoundMessage, id); // if (error.Priority == Priority.Error || error.Priority == Priority.Warning) // { // throw new BusinessException(error.Message, null, new List<EntityError> { error }); // } // } // else if (account.Status == Sage.CA.SBS.ERP.Sage300.GL.Models.Enums.Status.Inactive) // case of account exist but inactive // { // var error = GenerateAccountDescriptionEntityError(inactive, CommonResx.InactiveErrorMessage, id); // error.Tag = account.AccountNumber + "|" + account.Description; // if (error.Priority == Priority.Error || error.Priority == Priority.Warning) // { // throw new BusinessException(error.Message, null, new List<EntityError> { error }); // } // } // //return id as passed in if non-existent account is allowed. // if (string.IsNullOrEmpty(account.AccountNumber)) return new List<string>() { id, string.Empty }; // // valid case // var description = account.Description ?? string.Empty; // return new List<string>() { account.AccountNumber, description }; //} private static EntityError GenerateAccountDescriptionEntityError(LockedFiscalPeriod period, string messageTemplate, string id) { var entityError = new EntityError { Message = string.Format(messageTemplate, "Account", id.ToUpper()) }; if (period == LockedFiscalPeriod.Warning) { entityError.Priority = Priority.Warning; } else if (period == LockedFiscalPeriod.Error) { entityError.Priority = Priority.Error; } else { entityError.Priority = Priority.Message; } return(entityError); }
/// <summary> /// Get the currecy description. /// </summary> /// <param name="id">currency code</param> /// <returns>currecy description </returns> internal string GetCurrencyDescription(string id) { var currencyService = Context.Container.Resolve <ICurrencyCodeService <CurrencyCode> >(new ParameterOverride("context", Context)); Expression <Func <CurrencyCode, bool> > filter = currencyCodes => currencyCodes.CurrencyCodeId == id; var currency = currencyService.Get(filter); if (currency != null && currency.Items != null && currency.Items.Any()) { var firstOrDefault = currency.Items.FirstOrDefault(); if (firstOrDefault != null) { return(firstOrDefault.Description); } } var errorMsg = string.Format(CommonResx.RecordNotFoundMessage, TaxAuthoritiesResx.TxRepCurr, id); var errorList = new List <EntityError>(); var entityError = new EntityError { Message = errorMsg, Priority = Priority.Error }; errorList.Add(entityError); throw new BusinessException(errorMsg, errorList); }
protected override void SaveChangesCore(SaveWorkState saveWorkState) { var saveMap = saveWorkState.SaveMap; var deletedEntities = ProcessSaves(saveMap); if (deletedEntities.Any()) { ProcessAllDeleted(deletedEntities); } ProcessAutogeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys); int count; try { if (Context is DbContext) { count = ((DbContext)(object)Context).SaveChanges(); } else { count = ObjectContext.SaveChanges(System.Data.Entity.Core.Objects.SaveOptions.AcceptAllChangesAfterSave); } } catch (DbEntityValidationException e) { var entityErrors = new List <EntityError>(); foreach (var eve in e.EntityValidationErrors) { var entity = eve.Entry.Entity; var entityTypeName = entity.GetType().FullName; Object[] keyValues; var key = ObjectContext.ObjectStateManager.GetObjectStateEntry(entity).EntityKey; if (key.EntityKeyValues != null) { keyValues = key.EntityKeyValues.Select(km => km.Value).ToArray(); } else { var entityInfo = saveWorkState.EntitiesWithAutoGeneratedKeys.FirstOrDefault(ei => ei.Entity == entity); if (entityInfo != null) { keyValues = new Object[] { entityInfo.AutoGeneratedKey.TempValue }; } else { // how can this happen? keyValues = null; } } foreach (var ve in eve.ValidationErrors) { var entityError = new EntityError() { EntityTypeName = entityTypeName, KeyValues = keyValues, ErrorMessage = ve.ErrorMessage, PropertyName = ve.PropertyName }; entityErrors.Add(entityError); } } saveWorkState.EntityErrors = entityErrors; } catch (Exception e) { throw; //var originalException = e; //while (e.InnerException != null) { // e = e.InnerException; //} //if (e == originalException) { // throw; //} else { // create a new exception that contains the toplevel exception // but has the innermost exception message propogated to the top. // For EF exceptions, this is often the most 'relevant' message. // throw new Exception(e.Message, originalException); //} } saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys); }
protected override void BeforeApplyChanges(SaveChangesContext context) { var tag = context.SaveOptions.Tag?.ToString(); var saveMap = context.SaveMap; if (tag == "CommentOrderShipAddress.Before") { var orderInfos = saveMap[typeof(Order)]; byte seq = 1; foreach (var info in orderInfos) { var order = (Order)info.ClientEntity; AddComment(order.ShipAddress, seq++); } } else if (tag == "UpdateProduceShipAddress.Before") { var orderInfos = saveMap[typeof(Order)]; var order = (Order)orderInfos[0].ClientEntity; UpdateProduceDescription(order.ShipAddress); } else if (tag == "LookupEmployeeInSeparateContext.Before") { LookupEmployeeInSeparateContext(false); } else if (tag == "LookupEmployeeInSeparateContext.SameConnection.Before") { LookupEmployeeInSeparateContext(true); } else if (tag == "ValidationError.Before") { foreach (var type in saveMap.Keys) { var list = saveMap[type]; foreach (var entityInfo in list) { var entity = entityInfo.ClientEntity; var entityError = new EntityError() { EntityTypeName = type.Name, ErrorMessage = "Error message for " + type.Name, ErrorName = "Server-Side Validation", }; if (entity is Order) { var order = (Order)entity; entityError.KeyValues = new object[] { order.OrderID }; entityError.PropertyName = "OrderDate"; } } } } else if (tag == "increaseProductPrice") { foreach (var type in saveMap.Keys) { if (type == typeof(Category)) { foreach (var entityInfo in saveMap[type]) { if (entityInfo.EntityState == BreezeEntityState.Modified) { Category category = (entityInfo.ClientEntity as Category); var products = Products.Where(p => p.CategoryID == category.CategoryID); foreach (var product in products) { context.AddAdditionalEntity(product, BreezeEntityState.Modified); var incr = (Convert.ToInt64(product.UnitPrice) % 2) == 0 ? 1 : -1; product.UnitPrice += incr; } } } } } } else if (tag == "deleteProductOnServer.Before") { var prodinfo = saveMap[typeof(Product)].First(); if (prodinfo.EntityState == BreezeEntityState.Added) { // because Deleted throws error when trying delete non-existent row from database prodinfo.EntityState = BreezeEntityState.Detached; } else { prodinfo.EntityState = BreezeEntityState.Deleted; } } else if (tag == "deleteSupplierOnServer.Before") { var product = (Product)saveMap[typeof(Product)].First().ClientEntity; var infos = GetEntityInfos(saveMap, typeof(Supplier)); var supinfo = infos?.FirstOrDefault(); if (supinfo != null) { supinfo.EntityState = BreezeEntityState.Deleted; } else { // create new EntityInfo for entity that we want to delete that was not in the save bundle var supplier = Session.Get <Supplier>(product.SupplierID); context.AddAdditionalEntity(supplier, BreezeEntityState.Deleted); } } }
internal void updateEntityWithDeeplinks(EntityBase entityRow, JobTimeRange jobTimeRange) { // Decide what kind of timerange string DEEPLINK_THIS_TIMERANGE = DEEPLINK_TIMERANGE_LAST_15_MINUTES; if (jobTimeRange != null) { long fromTimeUnix = UnixTimeHelper.ConvertToUnixTimestamp(jobTimeRange.From); long toTimeUnix = UnixTimeHelper.ConvertToUnixTimestamp(jobTimeRange.To); long differenceInMinutes = (toTimeUnix - fromTimeUnix) / (60000); DEEPLINK_THIS_TIMERANGE = String.Format(DEEPLINK_TIMERANGE_BETWEEN_TIMES, toTimeUnix, fromTimeUnix, differenceInMinutes); } // Determine what kind of entity we are dealing with and adjust accordingly string deepLinkMetricTemplateInMetricBrowser = DEEPLINK_METRIC_APPLICATION_TARGET_METRIC_ID; long entityIdForMetricBrowser = entityRow.ApplicationID; if (entityRow is EntityApplication) { entityRow.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entityRow.Controller, DEEPLINK_THIS_TIMERANGE); entityRow.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entityRow.Controller, entityRow.ApplicationID, DEEPLINK_THIS_TIMERANGE); } else if (entityRow is EntityTier) { EntityTier entity = (EntityTier)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.TierLink = String.Format(DEEPLINK_TIER, entity.Controller, entity.ApplicationID, entity.TierID, DEEPLINK_THIS_TIMERANGE); deepLinkMetricTemplateInMetricBrowser = DEEPLINK_METRIC_TIER_TARGET_METRIC_ID; entityIdForMetricBrowser = entity.TierID; } else if (entityRow is EntityNode) { EntityNode entity = (EntityNode)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.TierLink = String.Format(DEEPLINK_TIER, entity.Controller, entity.ApplicationID, entity.TierID, DEEPLINK_THIS_TIMERANGE); entity.NodeLink = String.Format(DEEPLINK_NODE, entity.Controller, entity.ApplicationID, entity.NodeID, DEEPLINK_THIS_TIMERANGE); deepLinkMetricTemplateInMetricBrowser = DEEPLINK_METRIC_NODE_TARGET_METRIC_ID; entityIdForMetricBrowser = entity.NodeID; } else if (entityRow is EntityBackend) { EntityBackend entity = (EntityBackend)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.BackendLink = String.Format(DEEPLINK_BACKEND, entity.Controller, entity.ApplicationID, entity.BackendID, DEEPLINK_THIS_TIMERANGE); } else if (entityRow is EntityBusinessTransaction) { EntityBusinessTransaction entity = (EntityBusinessTransaction)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.TierLink = String.Format(DEEPLINK_TIER, entity.Controller, entity.ApplicationID, entity.TierID, DEEPLINK_THIS_TIMERANGE); entity.BTLink = String.Format(DEEPLINK_BUSINESS_TRANSACTION, entity.Controller, entity.ApplicationID, entity.BTID, DEEPLINK_THIS_TIMERANGE); deepLinkMetricTemplateInMetricBrowser = DEEPLINK_METRIC_TIER_TARGET_METRIC_ID; entityIdForMetricBrowser = entity.TierID; } else if (entityRow is EntityServiceEndpoint) { EntityServiceEndpoint entity = (EntityServiceEndpoint)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.TierLink = String.Format(DEEPLINK_TIER, entity.Controller, entity.ApplicationID, entity.TierID, DEEPLINK_THIS_TIMERANGE); entity.SEPLink = String.Format(DEEPLINK_SERVICE_ENDPOINT, entity.Controller, entity.ApplicationID, entity.TierID, entity.SEPID, DEEPLINK_THIS_TIMERANGE); } else if (entityRow is EntityError) { EntityError entity = (EntityError)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.TierLink = String.Format(DEEPLINK_TIER, entity.Controller, entity.ApplicationID, entity.TierID, DEEPLINK_THIS_TIMERANGE); entity.ErrorLink = String.Format(DEEPLINK_ERROR, entity.Controller, entity.ApplicationID, entity.ErrorID, DEEPLINK_THIS_TIMERANGE); } else if (entityRow is EntityInformationPoint) { EntityInformationPoint entity = (EntityInformationPoint)entityRow; entity.ControllerLink = String.Format(DEEPLINK_CONTROLLER, entity.Controller, DEEPLINK_THIS_TIMERANGE); entity.ApplicationLink = String.Format(DEEPLINK_APPLICATION, entity.Controller, entity.ApplicationID, DEEPLINK_THIS_TIMERANGE); entity.IPLink = String.Format(DEEPLINK_INFORMATION_POINT, entity.Controller, entity.ApplicationID, entity.IPID, DEEPLINK_THIS_TIMERANGE); } if (entityRow.MetricsIDs != null && entityRow.MetricsIDs.Count > 0) { StringBuilder sb = new StringBuilder(128); foreach (int metricID in entityRow.MetricsIDs) { sb.Append(String.Format(deepLinkMetricTemplateInMetricBrowser, entityIdForMetricBrowser, metricID)); sb.Append(","); } sb.Remove(sb.Length - 1, 1); entityRow.MetricLink = String.Format(DEEPLINK_METRIC, entityRow.Controller, entityRow.ApplicationID, sb.ToString(), DEEPLINK_THIS_TIMERANGE); } }
protected override void SaveChangesCore(SaveWorkState saveWorkState) { var saveMap = saveWorkState.SaveMap; var deletedEntities = ProcessSaves(saveMap); if (deletedEntities.Any()) { ProcessAllDeleted(deletedEntities); } ProcessAutogeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys); int count; try { if (Context is DbContext) { count = ((DbContext)(object)Context).SaveChanges(); } else { count = ObjectContext.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave); } } catch (DbEntityValidationException e) { var entityErrors = new List <EntityError>(); foreach (var eve in e.EntityValidationErrors) { var entity = eve.Entry.Entity; var entityTypeName = entity.GetType().FullName; Object[] keyValues; var key = ObjectContext.ObjectStateManager.GetObjectStateEntry(entity).EntityKey; if (key.EntityKeyValues != null) { keyValues = key.EntityKeyValues.Select(km => km.Value).ToArray(); } else { var entityInfo = saveWorkState.EntitiesWithAutoGeneratedKeys.FirstOrDefault(ei => ei.Entity == entity); if (entityInfo != null) { keyValues = new Object[] { entityInfo.AutoGeneratedKey.TempValue }; } else { // how can this happen? keyValues = null; } } foreach (var ve in eve.ValidationErrors) { var entityError = new EntityError() { EntityTypeName = entityTypeName, KeyValues = keyValues, ErrorMessage = ve.ErrorMessage, PropertyName = ve.PropertyName }; entityErrors.Add(entityError); } } saveWorkState.EntityErrors = entityErrors; } catch (Exception) { throw; } saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys); }
public EntityException(EntityError entityError) { }
/* * overidden method to access saveMap, which contains all the entities that will be saved * saveMap allows you to modifed & pass new entites back to the front-end * * if you query it from the session, you must include it in saveMap back to the client * the UI will update automatically */ private void AfterSaveEntities(Dictionary <Type, List <EntityInfo> > saveMap, List <KeyMapping> keyMappings) { var requestToChange = saveMap .Where(p => p.Key.IsAssignableFrom(typeof(Request))) .Select(p => p.Value) .FirstOrDefault(); var smToChange = saveMap .Where(p => p.Key.IsAssignableFrom(typeof(SourceMaterial))) .Select(p => p.Value.Where(x => x.EntityState == EntityState.Added).ToList()) .FirstOrDefault(); if (requestToChange != null) { var rq = ((Request)requestToChange.First().Entity); if (rq.RequestTemplateId != null) { bool selectedTemplateChangedValue = false; var selectedTemplateChanged = requestToChange.First().UnmappedValuesMap.SingleOrDefault(x => x.Key == "SelectedTemplateChanged"); // only if true, if false or null don't create jobs if (!string.IsNullOrEmpty(selectedTemplateChanged.Key) && (bool.TryParse(selectedTemplateChanged.Value.ToString(), out selectedTemplateChangedValue) && selectedTemplateChangedValue)) { _requestBL.CreateJobsBasedOnRequestTemplate(rq); var sms = Session.Query <SourceMaterial>().Where(x => x.RequestId == rq.Id).Where(x => !x.Jobs.Any()).ToList(); foreach (var sm in sms) { if (!CheckForObjectTypeInSaveMap(sm, saveMap)) { sm.UpdateDate = DateTime.UtcNow; saveMap.AddCustomEntity <SourceMaterial>(sm, this); } } } } } else if (smToChange != null && smToChange.Count > 0) { var rq = Session.Query <Request>().SingleOrDefault(x => x.Id == ((SourceMaterial)smToChange.First().Entity).RequestId); if (rq.RequestTemplateId != null) { _requestBL.CreateJobsBasedOnRequestTemplate(rq); } } // upload file to filemanagement service when a new file is saved var physicalFiles = saveMap .Where(p => p.Key.IsAssignableFrom(typeof(PhysicalFile))) .Select(p => p.Value) .FirstOrDefault(); if (physicalFiles != null) { foreach (var physicalFile in physicalFiles) { if (physicalFile.EntityState == EntityState.Added) { // see TFS 11203 var file = Session.Load <PhysicalFile>(((PhysicalFile)physicalFile.Entity).Id); // call external storage service StoreFileResponse resp = null; Helper.UseWcfService <IFileManagement>("FileManagement", null, null, p => { try { // Copying from a physical file (case we use a template with references they must be cloned) if (file.ExternalStorageFileId == null) { var filePath = Path.Combine(ConfigurationManager.AppSettings["UploadFolder"], file.PhysicalPath); // Reads data from the client temp folder var fileBytes = File.ReadAllBytes(filePath); resp = p.StoreFile(new StoreFileRequest() { FileData = fileBytes, FileName = file.FileName, Anonymize = true }); // check embedded only if it's a sourcematerial if (file.MaterialClassification.Code != "CREF" && new EmbeddedFileBL().IsEmbedded(filePath, file.FileName)) { file.IsEmbedded = true; } } else { resp = p.CloneFile(new CloneFileRequest() { ExternalStorageFileId = file.ExternalStorageFileId.Value, FileName = file.FileName }); } } catch (FaultException <FileIOFault> ex) { if (ex.Detail.FaultType == FileIOFault.FaultTypes.UnableToStoreError) { // Display an error if an upload issue happened // find temp key in keymappings var tempKey = keyMappings.Where(key => (Guid)key.RealValue == file.Id).Select(key => key.TempValue); var entityError = new EntityError { ErrorName = "Store file", ErrorMessage = ex.Detail.ErrorMessage, EntityTypeName = file.GetType().FullName, PropertyName = "FileName", KeyValues = tempKey.ToArray() }; throw new EntityErrorsException("Error saving file", new List <EntityError>() { entityError }); } } }); file.ExternalStorageFileId = resp.FileId; Session.Save(file); } } } var entityInfos = saveMap .Where(p => p.Key.IsAssignableFrom(typeof(Request))) .Select(p => p.Value) .FirstOrDefault(); if (entityInfos != null) { foreach (var entityInfo in entityInfos) { // initialize workflow or send email only if the status of the request has changed if (entityInfo.OriginalValuesMap.ContainsKey("StatusId")) { Request request = (Request)entityInfo.Entity; if (request.Status.Code == "MTS" && request.RequestType.Code == "RST001") { this.SendMarkedToSendEmail(request); } Status oldStatus = Session.Query <Status>().First(x => x.Id == Guid.Parse(entityInfo.OriginalValuesMap["StatusId"].ToString())); if (request.Status.Code == "DRAF" && request.RequestType.Code == "RST001" && oldStatus.Code == Status.Codes.MTS) { this.SendBackToDraftEmail(request); } if (request.Status.Code == "NEW" && request.RequestType.Code == "RST003") { WorkflowInitializer.Initialize(request, "AsaDefaultFlow", this.Session); } else if (request.Status.Code == "NEW" && request.RequestType.Code == "RST001") { WorkflowInitializer.Initialize(request, "EcdtDefaultFlow", this.Session); } } } } AfterSaveSourceMaterial(saveMap); AfterSaveJob(saveMap); Session.Flush(); }
public SaveResult SaveCsf(JObject saveBundle) { var transactionSettings = new TransactionSettings() { TransactionType = TransactionType.DbTransaction }; this._context.BeforeSaveEntitiesDelegate = (saveMap) => { // force associated job and request update var entityInfos = saveMap.Where(e => e.Key == typeof(JobMaterial)).Select(e => e.Value).FirstOrDefault(); if (entityInfos != null) { foreach (var entityInfo in entityInfos) { var jobMaterial = (JobMaterial)(entityInfo.Entity); if (!saveMap.Any(e => e.Key.IsSubclassOf(typeof(Job)) && e.Value.Any(f => ((Job)f.Entity).Id == jobMaterial.JobId))) { // single query without lazy loading var temp = (from p in this._context.Session.Query <Job>() where p.Id == jobMaterial.JobId select new { Job = p, Request = p.SourceMaterial.Request }).FirstOrDefault(); if (temp != null) { temp.Job.UpdateDate = DateTime.UtcNow; saveMap.AddCustomEntity(temp.Job, this._context); if (!saveMap.Any(e => e.Key == typeof(Request))) { temp.Request.UpdateDate = DateTime.UtcNow; saveMap.AddCustomEntity(temp.Request, this._context); } } } } } return(saveMap); }; this._context.AfterSaveEntitiesDelegate = (saveMap, keyMappings) => { // upload file to filemanagement service when a new file is saved var physicalFiles = saveMap .Where(p => p.Key.IsAssignableFrom(typeof(PhysicalFile))) .Select(p => p.Value) .FirstOrDefault(); if (physicalFiles != null) { foreach (var physicalFile in physicalFiles) { if (physicalFile.EntityState == EntityState.Added) { // see TFS 11203 var file = this._context.Session.Load <PhysicalFile>(((PhysicalFile)physicalFile.Entity).Id); // call external storage service StoreFileResponse resp = null; Helper.UseWcfService <IFileManagement>("FileManagement", null, null, p => { try { var filePath = Path.Combine(ConfigurationManager.AppSettings["UploadFolder"], file.PhysicalPath); // Reads data from the client temp folder var fileBytes = File.ReadAllBytes(filePath); resp = p.StoreFile(new StoreFileRequest() { FileData = fileBytes, FileName = file.FileName, Anonymize = true }); } catch (FaultException <FileIOFault> ex) { if (ex.Detail.FaultType == FileIOFault.FaultTypes.UnableToStoreError) { // Display an error if an upload issue happened // find temp key in keymappings var tempKey = keyMappings.Where(key => (Guid)key.RealValue == file.Id).Select(key => key.TempValue); var entityError = new EntityError { ErrorName = "Store file", ErrorMessage = ex.Detail.ErrorMessage, EntityTypeName = file.GetType().FullName, PropertyName = "FileName", KeyValues = tempKey.ToArray() }; throw new EntityErrorsException("Error saving file", new List <EntityError>() { entityError }); } } }); file.ExternalStorageFileId = resp.FileId; this._context.Session.Save(file); } } } this._context.Session.Flush(); }; this._context.BeforeSaveEntityDelegate = (entityInfo) => { if (entityInfo.Entity.GetType().IsSubclassOf(typeof(Material)) && entityInfo.EntityState == EntityState.Added) { Material material = (Material)entityInfo.Entity; if (string.IsNullOrEmpty(material.UploadedBy)) { material.UploadedBy = Thread.CurrentPrincipal.Identity.Name; } if (!material.UploaderType.HasValue) { material.UploaderType = UploaderType.Other; } if (string.IsNullOrEmpty(material.ActivityLabel)) { // always csf in that case material.ActivityLabel = "CSF"; } } return(true); }; return(this._context.SaveChanges(saveBundle, transactionSettings)); }