internal static string ToJsonAudit(this AgreementFile entity) { var state = JsonConvert.SerializeObject(new { entity.Id, entity.Guid, entity.AgreementId, entity.Length, entity.MimeType, entity.Name, entity.Path, entity.FileName, entity.Visibility, }); return(state); }
public void Handle(CreateFile command) { if (command == null) { throw new ArgumentNullException("command"); } // create the initial entity var entity = new AgreementFile { AgreementId = command.AgreementId, Visibility = command.Visibility.AsEnum <AgreementVisibility>(), Path = string.Format(AgreementFile.PathFormat, command.AgreementId, Guid.NewGuid()), }; _entities.Create(entity); // will we be moving an upload or creating a new file from scratch? var upload = command.UploadGuid.HasValue ? _entities.Get <Upload>().Single(x => x.Guid.Equals(command.UploadGuid.Value)) : null; // populate other entity properties and store binary data if (upload != null) { entity.FileName = upload.FileName; entity.Length = (int)upload.Length; entity.MimeType = upload.MimeType; entity.Name = GetExtensionedCustomName(command.CustomName, upload.FileName); _binaryData.Move(upload.Path, entity.Path); _purgeUpload.Handle(new PurgeUpload(upload.Guid) { NoCommit = true }); } else { entity.FileName = command.FileData.FileName; entity.Length = command.FileData.Content.Length; entity.MimeType = command.FileData.MimeType; entity.Name = GetExtensionedCustomName(command.CustomName, command.FileData.FileName); _binaryData.Put(entity.Path, command.FileData.Content, true); } // log audit var audit = new CommandEvent { RaisedBy = command.Principal.Identity.Name, Name = command.GetType().FullName, Value = JsonConvert.SerializeObject(new { command.AgreementId, command.CustomName, command.Visibility, command.UploadGuid, FileData = command.FileData == null ? null : new { command.FileData.FileName, ContentType = command.FileData.MimeType, ContentLength = command.FileData.Content.Length, } }), NewState = entity.ToJsonAudit(), }; _entities.Create(audit); try { _unitOfWork.SaveChanges(); command.CreatedFileId = entity.Id; } catch { // restore binary data state when the db save fails if (_binaryData.Exists(entity.Path)) { if (upload != null) { _binaryData.Move(entity.Path, upload.Path); } else { _binaryData.Delete(entity.Path); } } } }