Пример #1
0
        /*
         * 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();
        }
Пример #2
0
        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));
        }