コード例 #1
0
        public AuditDelta Post(AuditDeltaCopy request)
        {
            AuditDelta ret = null;

            using (Execute)
            {
                Execute.Run(ssn =>
                {
                    var entity = DocEntityAuditDelta.Get(request?.Id);
                    if (null == entity)
                    {
                        throw new HttpError(HttpStatusCode.NoContent, "The COPY request did not succeed.");
                    }
                    if (!DocPermissionFactory.HasPermission(entity, currentUser, DocConstantPermission.ADD))
                    {
                        throw new HttpError(HttpStatusCode.Forbidden, "You do not have ADD permission for this route.");
                    }

                    var pAudit = entity.Audit;
                    var pDelta = entity.Delta;
                    var copy   = new DocEntityAuditDelta(ssn)
                    {
                        Hash    = Guid.NewGuid()
                        , Audit = pAudit
                        , Delta = pDelta
                    };

                    copy.SaveChanges(DocConstantPermission.ADD);
                    ret = copy.ToDto();
                });
            }
            return(ret);
        }
コード例 #2
0
        private AuditDelta GetAuditDelta(AuditDelta request)
        {
            var        id    = request?.Id;
            AuditDelta ret   = null;
            var        query = DocQuery.ActiveQuery ?? Execute;

            DocPermissionFactory.SetSelect <AuditDelta>(currentUser, "AuditDelta", request.Select);

            DocEntityAuditDelta entity = null;

            if (id.HasValue)
            {
                entity = DocEntityAuditDelta.Get(id.Value);
            }
            if (null == entity)
            {
                throw new HttpError(HttpStatusCode.NotFound, $"No AuditDelta found for Id {id.Value}");
            }

            if (!DocPermissionFactory.HasPermission(entity, currentUser, DocConstantPermission.VIEW))
            {
                throw new HttpError(HttpStatusCode.Forbidden, "You do not have VIEW permission for this route.");
            }

            ret = entity?.ToDto();
            return(ret);
        }
コード例 #3
0
        public AuditDelta Post(AuditDelta request)
        {
            if (request == null)
            {
                throw new HttpError(HttpStatusCode.NotFound, "Request cannot be null.");
            }

            request.Select = request.Select ?? new List <string>();

            AuditDelta ret = null;

            using (Execute)
            {
                Execute.Run(ssn =>
                {
                    if (!DocPermissionFactory.HasPermissionTryAdd(currentUser, "AuditDelta"))
                    {
                        throw new HttpError(HttpStatusCode.Forbidden, "You do not have ADD permission for this route.");
                    }

                    ret = _AssignValues(request, DocConstantPermission.ADD, ssn);
                });
            }
            return(ret);
        }
コード例 #4
0
        public TblAudit ToAudit()
        {
            var audit = new TblAudit
            {
                TableName = TableName,
                DateTime  = DateTime.UtcNow,
                Action    = Action,
                UserId    = UserId,
                KeyValues = KeyValues.First().Value.ToString(),
                OldValues = OldValues.Count == 0 ? null : JsonConvert.SerializeObject(OldValues),
                NewValues = NewValues.Count == 0 ? null : JsonConvert.SerializeObject(NewValues),
            };


            List <AuditDelta> DeltaList = new List <AuditDelta>();

            JObject sourceJObject = JsonConvert.DeserializeObject <JObject>(audit.OldValues);

            if (audit.Action == "Modified")
            {
                JObject targetJObject = JsonConvert.DeserializeObject <JObject>(audit.NewValues);

                foreach (KeyValuePair <string, JToken> sourceProperty in sourceJObject)
                {
                    JProperty targetProp = targetJObject.Property(sourceProperty.Key);

                    if (!JToken.DeepEquals(sourceProperty.Value, targetProp.Value))
                    {
                        AuditDelta delta = new AuditDelta
                        {
                            FieldName   = sourceProperty.Key,
                            ValueBefore = Convert.ToString(sourceProperty.Value),
                            ValueAfter  = Convert.ToString(targetProp.Value)
                        };
                        DeltaList.Add(delta);
                    }
                }
            }
            else
            {
                foreach (KeyValuePair <string, JToken> sourceProperty in sourceJObject)
                {
                    AuditDelta delta = new AuditDelta
                    {
                        FieldName   = sourceProperty.Key,
                        ValueBefore = Convert.ToString(sourceProperty.Value),
                        ValueAfter  = string.Empty
                    };
                    DeltaList.Add(delta);
                }
            }



            audit.Changes = JsonConvert.SerializeObject(DeltaList);

            return(audit);
        }
コード例 #5
0
        // Call This Function to call Transaction in Audit History Table

        //_backgroundService.EnqueueJob<IGeneralBackgroundJobs>
        //(m => m.AddAuditTrail(ActionTypeEnum.@ActionType, @TransactionSaveId, @OldDataModel, @NewDataModel,
        //(long)TableEnum.@tableName));

        // if Model Null or no data than passs " (@tableName)Activator.CreateInstance(typeof(@tableName)) "

        #region Audit Trail

        public void AddAuditTrail <T>(
            ActionTypeEnum action, long recordid, T oldObject, T newObject, long?tableId)
        {
            var compObjects = new CompareLogic
            {
                Config = { MaxDifferences    =   99, IgnoreCollectionOrder = true,
                           CompareProperties = true, CompareChildren       = false }
            };

            ComparisonResult compResult = compObjects.Compare(oldObject, newObject);
            var deltaList = new List <AuditDelta>();

            foreach (var change in compResult.Differences)
            {
                var delta = new AuditDelta();
                if (!string.IsNullOrEmpty(change.PropertyName) && change.PropertyName.Substring(0, 1) == ".")
                {
                    delta.FieldName = change.PropertyName.Substring(1, change.PropertyName.Length - 1);
                }
                delta.ValueBefore = change.Object1Value;
                delta.ValueAfter  = change.Object2Value;
                deltaList.Add(delta);
            }
            var jsSettings = new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            // Create AuditHistory Table
            //var auditTrail = new AuditHistory
            //{
            //    ActionType = (int)action,
            //    TableId = tableId,
            //    CreatedOn = DateTime.UtcNow,
            //    RecordId = recordid,
            //    OldValue = JsonConvert.SerializeObject(oldObject, Formatting.None, jsSettings),
            //    NewValue = JsonConvert.SerializeObject(newObject, Formatting.None, jsSettings),
            //    LogText = JsonConvert.SerializeObject(deltaList, Formatting.None, jsSettings)
            //};

            var obj = JObject.Parse(JsonConvert.SerializeObject(newObject, Formatting.None, jsSettings));

            if (obj != null && CommonHelper.IsNumeric(Convert.ToString(obj["CreatedBy"])))
            {
                var createdby = (long?)obj["CreatedBy"];

                if (createdby != null)
                {
                    //  auditTrail.CreatedBy = createdby;
                }
            }
            //TODO Save Audit History in Database
        }
コード例 #6
0
        /// <summary>
        /// Add audit logs with delta changes
        /// </summary>
        /// <param name="action">Audit action <see cref="AuditAction"/>.</param>
        /// <param name="id">Key Id for entity</param>
        /// <param name="before">Entity before changes occured. You must pass empty instance when action is Add.</param>
        /// <param name="after">Entity after changes occured. You must pass empty instance when action is Delete.</param>
        public async Task AddAuditLogAsync(AuditAction action, string id, T before, T after)
        {
            Validate(action, id, before, after);

            CompareLogic compareLogic = new CompareLogic();

            compareLogic.Config.MaxDifferences = 100;
            compareLogic.Config.CaseSensitive  = false;
            compareLogic.Config.TreatStringEmptyAndNullTheSame = true;

            ComparisonResult comapreResults = compareLogic.Compare(before, after);

            List <AuditDelta> deltaList = new List <AuditDelta>();

            foreach (var change in comapreResults.Differences)
            {
                AuditDelta delta = new AuditDelta
                {
                    FieldName = change.PropertyName.Replace(change.ParentPropertyName + ".", string.Empty),
                    Value     = change.Object2Value
                };
                deltaList.Add(delta);
            }

            AuditTable auditTable = new AuditTable()
            {
                _id             = Guid.NewGuid(),
                EntityId        = id,
                EntityName      = typeof(T).Name.ToLower(),
                AuditActionType = (int)action,
                DateTimeStamp   = DateTime.UtcNow,
                Changes         = JsonConvert.SerializeObject(deltaList)
            };

            await dsStorageAdapter.AddAsync(auditTable);
        }
コード例 #7
0
        private AuditDelta _AssignValues(AuditDelta request, DocConstantPermission permission, Session session)
        {
            if (permission != DocConstantPermission.ADD && (request == null || request.Id <= 0))
            {
                throw new HttpError(HttpStatusCode.NotFound, $"No record");
            }

            if (permission == DocConstantPermission.ADD && !DocPermissionFactory.HasPermissionTryAdd(currentUser, "AuditDelta"))
            {
                throw new HttpError(HttpStatusCode.Forbidden, "You do not have ADD permission for this route.");
            }

            request.Select = request.Select ?? new List <string>();

            AuditDelta ret = null;

            request = _InitAssignValues <AuditDelta>(request, permission, session);
            //In case init assign handles create for us, return it
            if (permission == DocConstantPermission.ADD && request.Id > 0)
            {
                return(request);
            }

            var cacheKey = GetApiCacheKey <AuditDelta>(DocConstantModelName.AUDITDELTA, nameof(AuditDelta), request);

            //First, assign all the variables, do database lookups and conversions
            var pAudit    = DocEntityAuditRecord.Get(request.Audit?.Id, true, Execute) ?? DocEntityAuditRecord.Get(request.AuditId, true, Execute);
            var pDelta    = request.Delta;
            var pArchived = true == request.Archived;
            var pLocked   = request.Locked;

            var entity = InitEntity <DocEntityAuditDelta, AuditDelta>(request, permission, session);

            if (AllowPatchValue <AuditDelta, bool>(request, DocConstantModelName.AUDITDELTA, pArchived, permission, nameof(request.Archived), pArchived != entity.Archived))
            {
                entity.Archived = pArchived;
            }
            if (AllowPatchValue <AuditDelta, DocEntityAuditRecord>(request, DocConstantModelName.AUDITDELTA, pAudit, permission, nameof(request.Audit), pAudit != entity.Audit))
            {
                entity.Audit = pAudit;
            }
            if (AllowPatchValue <AuditDelta, string>(request, DocConstantModelName.AUDITDELTA, pDelta, permission, nameof(request.Delta), pDelta != entity.Delta))
            {
                entity.Delta = pDelta;
            }
            if (request.Locked && AllowPatchValue <AuditDelta, bool>(request, DocConstantModelName.AUDITDELTA, pArchived, permission, nameof(request.Locked), pLocked != entity.Locked))
            {
                entity.Archived = pArchived;
            }
            entity.SaveChanges(permission);

            var idsToInvalidate = new List <int>();

            if (idsToInvalidate.Any())
            {
                idsToInvalidate.Add(entity.Id);
                DocCacheClient.RemoveByEntityIds(idsToInvalidate);
                DocCacheClient.RemoveSearch(DocConstantModelName.AUDITDELTA);
            }

            entity.SaveChanges(permission);
            DocPermissionFactory.SetSelect <AuditDelta>(currentUser, nameof(AuditDelta), request.Select);
            ret = entity.ToDto();

            var cacheExpires = DocResources.Metadata.GetCacheExpiration(DocConstantModelName.AUDITDELTA);

            DocCacheClient.Set(key: cacheKey, value: ret, entityId: request.Id, entityType: DocConstantModelName.AUDITDELTA, cacheExpires);

            return(ret);
        }
コード例 #8
0
 public object Get(AuditDelta request) => GetEntityWithCache <AuditDelta>(DocConstantModelName.AUDITDELTA, request, GetAuditDelta);
コード例 #9
0
        private void AudtiChanges()
        {
            var auditProcessor = AppRuntimeContext.Current.Resolve <IAuditProcessor>() as IAuditProcessor;

            if (auditProcessor != null)
            {
                var changeTrack = Context.ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);
                foreach (var entry in changeTrack)
                {
                    var entityType = entry.Entity.GetType();
                    if (entityType.Namespace == "System.Data.Entity.DynamicProxies")
                    {
                        entityType = entityType.BaseType;
                    }
                    if (auditProcessor.AuditTypes.Contains(entityType) == false)
                    {
                        continue;
                    }

                    var objectId = entry.Property("Id")?.CurrentValue?.ToString();

                    if (entry.State == EntityState.Added)
                    {
                        var record = new AuditRecord
                        {
                            ObjectId      = objectId,
                            ObjectType    = entityType,
                            DateTimeStamp = DateTime.UtcNow,
                            OperationType = OperationType.Create,
                            UserName      = Thread.CurrentPrincipal?.Identity?.Name
                        };
                        foreach (var prop in entry.CurrentValues.Properties)
                        {
                            var currentValue = entry.CurrentValues[prop];
                            // var property = entityType.GetProperty(prop, flags);

                            var auditDelta = new AuditDelta
                            {
                                FieldName  = prop.PropertyInfo.Name,
                                FieldType  = prop.PropertyInfo.PropertyType,
                                ValueAfter = currentValue
                            };
                            record.Changes.Add(auditDelta);
                        }
                        auditProcessor.Audit(record);
                    }
                    if (entry.State == EntityState.Modified)
                    {
                        var record = new AuditRecord
                        {
                            ObjectId      = objectId,
                            ObjectType    = entityType,
                            DateTimeStamp = DateTime.UtcNow,
                            OperationType = OperationType.Update,
                            UserName      = Thread.CurrentPrincipal?.Identity?.Name
                        };
                        foreach (var prop in entry.OriginalValues.Properties)
                        {
                            var currentValue  = entry.CurrentValues[prop];
                            var originalValue = entry.OriginalValues[prop];

                            //    var property = entityType.GetProperty(prop, flags);

                            var auditDelta = new AuditDelta
                            {
                                FieldName   = prop.PropertyInfo.Name,
                                FieldType   = prop.PropertyInfo.PropertyType,
                                ValueBefore = originalValue,
                                ValueAfter  = currentValue
                            };
                            record.Changes.Add(auditDelta);
                        }
                        auditProcessor.Audit(record);
                    }
                    if (entry.State == EntityState.Deleted)
                    {
                        var record = new AuditRecord
                        {
                            ObjectId      = objectId,
                            ObjectType    = entityType,
                            DateTimeStamp = DateTime.UtcNow,
                            OperationType = OperationType.Delete,
                            UserName      = Thread.CurrentPrincipal?.Identity?.Name
                        };
                        foreach (var prop in entry.OriginalValues.Properties)
                        {
                            var originalValue = entry.OriginalValues[prop];

                            //var property = entityType.GetProperty(prop, flags);

                            var auditDelta = new AuditDelta
                            {
                                FieldName   = prop.PropertyInfo.Name,
                                FieldType   = prop.PropertyInfo.PropertyType,
                                ValueBefore = originalValue
                            };
                            record.Changes.Add(auditDelta);
                        }
                        auditProcessor.Audit(record);
                    }
                }
            }
        }