示例#1
0
        public void TestWithValidValues()
        {
            // ARRANGE
            Guid                  paramId             = Guid.NewGuid();
            IAuditHeader          paramAuditHeader    = Create.AuditHeader();
            const string          paramTableName      = "Organisation";
            const string          paramColumnName     = "Id";
            Guid                  paramRecordId       = Guid.NewGuid();
            const string          paramOldValue       = "Old Value";
            const string          paramNewValue       = "New Value";
            const EDatabaseAction paramDatabaseAction = EDatabaseAction.Update;

            // ACT
            IAuditDetail auditDetail = new AuditDetail(
                id: paramId,
                auditHeader: paramAuditHeader,
                tableName: paramTableName,
                columnName: paramColumnName,
                recordId: paramRecordId,
                oldValue: paramOldValue,
                newValue: paramNewValue,
                databaseAction: paramDatabaseAction);

            // ASSERT
            Assert.AreEqual(paramId, auditDetail.Id);
            Assert.AreSame(paramAuditHeader, auditDetail.AuditHeader);
            Assert.AreEqual(paramTableName, auditDetail.TableName);
            Assert.AreEqual(paramColumnName, auditDetail.ColumnName);
            Assert.AreEqual(paramRecordId, auditDetail.RecordId);
            Assert.AreEqual(paramOldValue, auditDetail.OldValue);
            Assert.AreEqual(paramNewValue, auditDetail.NewValue);
            Assert.AreEqual(paramDatabaseAction, auditDetail.DatabaseAction);
        }
示例#2
0
        public static bool ModifyAuditDetail(AuditDetail model)
        {
            string sql = string.Format(@"update {0} set [UserId]=@UserId,[AudtiMainId]=@AudtiMainId,[CompanyId]=@CompanyId,[Remark]=@Remark,[OperateBy]=@OperateBy,[Status]=@Status,[ModifyDate]=getdate()
            where Id=@Id", TableName);

            return(DBAccess.ExecuteSqlWithEntity(sql, model));
        }
示例#3
0
        public void TestWithValidValuesThatAreNull()
        {
            // ARRANGE
            Guid                  paramId             = Guid.NewGuid();
            IAuditHeader          paramAuditHeader    = Create.AuditHeader();
            const string          paramTableName      = "Organisation";
            const string          paramColumnName     = "Id";
            Guid                  paramRecordId       = Guid.NewGuid();
            const EDatabaseAction paramDatabaseAction = EDatabaseAction.Update;

            // ACT
            IAuditDetail auditDetail = new AuditDetail(
                id: paramId,
                auditHeader: paramAuditHeader,
                tableName: paramTableName,
                columnName: paramColumnName,
                recordId: paramRecordId,
                oldValue: null,
                newValue: null,
                databaseAction: paramDatabaseAction);

            // ASSERT
            Assert.IsNull(auditDetail.OldValue);
            Assert.IsNull(auditDetail.NewValue);
        }
示例#4
0
        public void Test_Passing_Valid_Values()
        {
            // ARRANGE
            IAuditHeaderWithAuditDetails auditHeader = new AuditHeaderWithAuditDetails(
                auditEvent: EAuditEvent.OrganisationMaintenance,
                username: "******",
                correlationId: Guid.NewGuid());

            IAuditDetail auditDetail = new AuditDetail(
                id: Guid.NewGuid(),
                auditHeader: auditHeader,
                tableName: "TableName",
                columnName: "ColumnName",
                recordId: Guid.NewGuid(),
                oldValue: "Old Value",
                newValue: "New Value",
                databaseAction: EDatabaseAction.Update);

            auditHeader.AuditDetails.Add(auditDetail);

            // ACT
            AuditHeaderDto auditHeaderDto = AuditHeaderDto.ToDtoWithAuditDetails(auditHeader);

            // ASSERT
            Assert.AreEqual(auditHeader.Id, auditHeaderDto.Id);
            Assert.AreEqual(auditHeader.AuditEvent, auditHeaderDto.AuditEvent);
            Assert.AreEqual(auditHeader.TimeStamp, auditHeaderDto.TimeStamp);
            Assert.AreEqual(auditHeader.Username, auditHeaderDto.Username);
            Assert.AreEqual(auditHeader.CorrelationId, auditHeaderDto.CorrelationId);
            Assert.IsNotNull(auditHeaderDto.AuditDetails);
        }
示例#5
0
 public ExpenseClaim()
 {
     AuditDetail         = new AuditDetail();
     SupportingDocuments = new MultipleFilesHandle();
     ExpenseClaimItems   = new HashSet <ExpenseClaimItem>();
     Transitions         = new HashSet <ExpenseClaimTransition>();
 }
示例#6
0
        public static AuditDetail GetAuditDetail(this HttpContext httpContext, string senderAppName)
        {
            var audit = new AuditDetail()
            {
                SenderName     = senderAppName,
                OrganisationId = httpContext.GetOrganisation()?.Id
            };
            var routeData = httpContext.GetRouteData();

            if (routeData.Values.ContainsKey("action"))
            {
                audit.ActionName     = routeData.Values["action"]?.ToString();
                audit.ControllerName = routeData.Values["controller"]?.ToString();
            }

            if (httpContext.User.Identity.IsAuthenticated)
            {
                var claims = httpContext.User.Claims;

                audit.ClientId = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.ClientId)?.Value;
                audit.Name     = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value;
                audit.Email    = claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
            }

            return(audit);
        }
示例#7
0
文件: Budget.cs 项目: vish-j/LukeApps
 public Budget()
 {
     Enquiries      = new HashSet <Enquiry>();
     PurchaseOrders = new HashSet <PurchaseOrder>();
     Invoices       = new HashSet <Invoice>();
     AuditDetail    = new AuditDetail();
 }
示例#8
0
        public static AuditDetail CreateAuditDetail(int auditID)
        {
            AuditDetail auditDetail = new AuditDetail();

            auditDetail.AuditID = auditID;
            return(auditDetail);
        }
示例#9
0
        public void Test_Passing_Valid_Values()
        {
            // ARRANGE
            IAuditHeader auditHeader = new AuditHeader(
                id: Guid.NewGuid(),
                auditEvent: EAuditEvent.OrganisationMaintenance,
                timeStamp: DateTime.Now,
                username: "******",
                correlationId: Guid.NewGuid());
            IAuditDetail auditDetail = new AuditDetail(
                Guid.NewGuid(),
                auditHeader,
                "TableName",
                "ColumnName",
                Guid.NewGuid(),
                "Old Value",
                "New Value",
                EDatabaseAction.Update);

            // ACT
            AuditDetailDto auditDetailDto = AuditDetailDto.ToDto(auditDetail);

            // ASSERT
            Assert.AreEqual(auditDetail.Id, auditDetailDto.Id);
            Assert.AreEqual(auditDetail.AuditHeader.Id, auditDetailDto.AuditHeaderId);
            Assert.AreEqual(auditDetail.TableName, auditDetailDto.TableName);
            Assert.AreEqual(auditDetail.ColumnName, auditDetailDto.ColumnName);
            Assert.AreEqual(auditDetail.RecordId, auditDetailDto.RecordId);
            Assert.AreEqual(auditDetail.OldValue, auditDetailDto.OldValue);
            Assert.AreEqual(auditDetail.NewValue, auditDetailDto.NewValue);
            Assert.AreEqual(auditDetail.DatabaseAction, auditDetailDto.DatabaseAction);
        }
示例#10
0
        public void TestWithValidValues()
        {
            // ARRANGE
            IAuditHeader paramAuditHeader = Create.AuditHeader();
            const string paramTableName   = "Organisation";
            const string paramColumnName  = "Id";
            Guid         paramRecordId    = Guid.NewGuid();
            const string paramNewValue    = "New Value";
            const string paramOldValue    = "Old Value";

            // ACT
            IAuditDetail auditDetail = AuditDetail.CreateForUpdate(
                paramAuditHeader,
                paramTableName,
                paramColumnName,
                paramRecordId,
                paramOldValue,
                paramNewValue);

            // ASSERT
            Assert.IsNotNull(auditDetail);
            Assert.AreNotEqual(paramRecordId, auditDetail.Id);
            Assert.AreSame(paramAuditHeader, auditDetail.AuditHeader);
            Assert.AreEqual(paramTableName, auditDetail.TableName);
            Assert.AreEqual(paramColumnName, auditDetail.ColumnName);
            Assert.AreEqual(paramRecordId, auditDetail.RecordId);
            Assert.AreEqual(paramOldValue, auditDetail.OldValue);
            Assert.AreEqual(paramNewValue, auditDetail.NewValue);
            Assert.AreEqual(EDatabaseAction.Update, auditDetail.DatabaseAction);
        }
示例#11
0
 public Invoice()
 {
     AuditDetail    = new AuditDetail();
     Documents      = new MultipleFilesHandle();
     PurchaseOrders = new HashSet <PurchaseOrder>();
     Transitions    = new HashSet <InvoiceTransition>();
 }
 public AuditDetailDto(AuditDetail model)
 {
     this.Id       = model.Id;
     this.Field    = model.Field;
     this.Previous = model.Previous;
     this.Next     = model.Next;
 }
示例#13
0
 public async void SaveAuditDetails(AuditInfo auditInfo)
 {
     try
     {
         UnitOfWork  unitOfWork  = new UnitOfWork();
         var         repo        = unitOfWork.GetRepoInstance <AuditDetail>();
         bool        isSaved     = false;
         AuditDetail auditDetail = new AuditDetail();
         auditDetail.ActionName     = auditInfo.ActionName;
         auditDetail.ControllerName = auditInfo.ControllerName;
         auditDetail.CreatedDate    = DateTime.UtcNow;
         auditDetail.Parameter      = auditInfo.RequestData;
         auditDetail.RequestURL     = auditInfo.RequestURL;
         auditDetail.ReturnValue    = auditInfo.ResponseData;
         auditDetail.UserId         = auditInfo.UserId;
         isSaved = await repo.Add(auditDetail);
     }
     catch (Exception ex)
     {
         string parameter = "Action Name : " + auditInfo.ActionName;
         parameter += ", Controller Name : " + auditInfo.ControllerName;
         parameter += ", Request Data : " + auditInfo.RequestData;
         parameter += ", Request URL : " + auditInfo.RequestURL;
         parameter += ", UserId : " + auditInfo.UserId;
         //ShoppingCartExceptionHandler.HandleError(ex, parameter);
     }
 }
示例#14
0
 public Enquiry()
 {
     AuditDetail         = new AuditDetail();
     SupportingDocuments = new MultipleFilesHandle();
     Offers      = new HashSet <Offer>();
     Transitions = new HashSet <EnquiryTransition>();
 }
示例#15
0
        public ActionResult ApplyClubSubmit([Bind(Include = "ClubId,ApplyDesc,ApplyFile")] ApplyClubSubModel model)
        {
            try
            {
                ClubNumber club = db.ClubNumbers.Find(model.ClubId);
                if (string.IsNullOrWhiteSpace(model.ApplyFile))
                {
                    ModelState.AddModelError("", "申请任务未上传审批文件!");
                    return(View(model));
                }
                if (club.User.UserId != User.Identity.Name)
                {
                    ModelState.AddModelError("", "非用户" + User.Identity.Name + "创建的申请不能由用户" + User.Identity.Name + "提交!");
                    return(View(model));
                }
                if (club.State != (int)EnumState.待提交)
                {
                    ModelState.AddModelError("", "请求状态错误不允许提交审批");
                    return(View(model));
                }
                ApplyAudit apply = new ApplyAudit()
                {
                    Type             = db.ApplyTypes.Find((int)SQType.注册社团),
                    ApplicationDesc  = model.ApplyDesc,
                    ApplicationFiled = model.ApplyFile,
                    ApplyUser        = club.User,
                    Club             = club,
                    ApplyDate        = DateTime.Now,
                    CheckState       = (int)EnumAuditState.创建,
                    AuditTimes       = 0
                };
                db.ApplyAudits.Add(apply);
                db.SaveChanges();

                AuditDetail audit = new AuditDetail()
                {
                    ApplyId    = apply.Id,
                    CheckState = (int)EnumAuditState.创建,
                    AuditUser  = club.User,
                    AuditDate  = DateTime.Now
                };
                db.AuditDetails.Add(audit);

                club.State   = (int)EnumState.待审批;
                club.AuditID = apply.Id;
                if (string.IsNullOrEmpty(club.HeadImg))
                {
                    club.HeadImg = "Content/images/head5.jpg";//设置社团默认头像图片
                }
                db.Entry(club).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("MyClubs", new { Msg = "社团编号[" + club.ClubId + "]一个申请已提交,牢记并使用申请任务凭证[" + apply.Id + "]查看申请进度" }));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(View(model));
            }
        }
示例#16
0
 public PurchaseOrder()
 {
     ApprovedDocuments  = new MultipleFilesHandle();
     AuditDetail        = new AuditDetail();
     PurchaseOrderItems = new HashSet <PurchaseOrderItem>();
     Invoices           = new HashSet <Invoice>();
     Transitions        = new HashSet <PurchaseOrderTransition>();
 }
示例#17
0
        /// <summary>
        /// Audits the update.
        /// </summary>
        /// <param name="auditHeader">Audit Header.</param>
        /// <param name="recordId">Record Id.</param>
        /// <param name="oldObject">Old Value.</param>
        /// <param name="newObject">New Value.</param>
        internal static void AuditUpdate(
            IAuditHeaderWithAuditDetails?auditHeader,
            Guid recordId,
            BaseDto oldObject,
            BaseDto newObject)
        {
            if (auditHeader == null)
            {
                return;
            }

            Type type = newObject.GetType();

            PropertyDescriptorCollection propertyDescriptors = TypeDescriptor.GetProperties(type);

            foreach (PropertyInfo propertyInfo in type.GetProperties().OrderBy(p => p.MetadataToken))
            {
                // Skip if not auditable field
                if (!PropertyUtilities.IsAuditableColumn(propertyDescriptors, propertyInfo))
                {
                    continue;
                }

                // Get old and new values
                string oldValue = propertyInfo.GetValueAsString(oldObject);
                string newValue = propertyInfo.GetValueAsString(newObject);

                // Skip if value unchanged
                if (CompareNullable.AreEqual(oldValue, newValue))
                {
                    continue;
                }

                PropertyDescriptor propertyDescriptor = propertyDescriptors[propertyInfo.Name];

                TableAttribute?tableAttribute =
                    (TableAttribute?)propertyDescriptor.Attributes[typeof(TableAttribute)];
                string tableName = tableAttribute == null
                    ? type.Name
                    : tableAttribute.Name;

                ColumnAttribute?columnAttribute =
                    (ColumnAttribute?)propertyDescriptor.Attributes[typeof(ColumnAttribute)];
                string columnName = columnAttribute == null
                    ? propertyInfo.Name
                    : columnAttribute.Name;

                IAuditDetail auditDetail = AuditDetail.CreateForUpdate(
                    auditHeader: auditHeader,
                    tableName: tableName,
                    columnName: columnName,
                    recordId: recordId,
                    oldValue: oldValue,
                    newValue: newValue);

                auditHeader.AuditDetails.Add(auditDetail);
            }
        }
示例#18
0
 public Company()
 {
     Address            = new Address();
     CompanyFocalPoints = new HashSet <CompanyFocalPoint>();
     PurchaseOrders     = new HashSet <PurchaseOrder>();
     BankAccounts       = new HashSet <BankAccount>();
     Offers             = new HashSet <Offer>();
     AuditDetail        = new AuditDetail();
 }
        public async Task <ActionResult <IEnumerable <AuditDetail> > > GetAuditDetails()
        {
            IList <AuditDetail> auditDetails = new List <AuditDetail>();
            //IList<CountryToAudit> countryToAudits = new List<CountryToAudit>();
            //IList<PersonMapping> personMappings = new List<PersonMapping>();


            var audits = await _context.Audit.ToListAsync();

            foreach (var audit in audits)
            {
                var auditDetail = new AuditDetail
                {
                    AuditId   = audit.AuditId,
                    Status    = audit.Status,
                    Duration  = audit.Duration,
                    Year      = audit.Year,
                    AuditDate = audit.AuditDate
                };

                IList <CountryToAudit> countryToAudits = await _context.CountryToAudit.Where(x => x.AuditId == audit.AuditId).ToListAsync();

                IList <PersonMapping> personMappings = await _context.PersonMapping.Where(x => x.AuditId == audit.AuditId && x.IsPrimary == true).ToListAsync();

                IList <Country> countries = new List <Country>();
                IList <Person>  people    = new List <Person>();

                var countryNames = "";

                foreach (var countryToAudit in countryToAudits)
                {
                    var country = await _context.Country.Where(x => x.CountryId == countryToAudit.CountryId).FirstOrDefaultAsync();

                    countryNames = countryNames + country.CountryName + "; ";
                    countries.Add(country);
                }

                foreach (var personMapping in personMappings)
                {
                    var person = await _context.Person.Where(x => x.PersonId == personMapping.PersonId).FirstOrDefaultAsync();

                    people.Add(person);
                }

                auditDetail.CountryToAudits = countryToAudits;
                auditDetail.Countries       = countries;
                auditDetail.CountryNames    = countryNames;
                auditDetail.PersonMappings  = personMappings;
                auditDetail.People          = people;

                auditDetails.Add(auditDetail);
            }


            return(auditDetails.ToList());
        }
示例#20
0
        public void QueueBackgroundAudit(AuditDetail auditDetails)
        {
            if (auditDetails == null)
            {
                throw new ArgumentNullException(nameof(auditDetails));
            }

            WorkItems.Enqueue(JsonSerializer.Serialize(auditDetails));
            signal.Release();
        }
示例#21
0
        public async Task Test_Commit_Writes_Record()
        {
            // ARRANGE
            Mock <ILogger <VirtualBridgeData> > loggerMock =
                MockFactory.CreateLoggerMock <VirtualBridgeData>();
            Mock <ILogger <AuditHeaderRepository> > auditHeaderRepositoryLoggerMock =
                MockFactory.CreateLoggerMock <AuditHeaderRepository>();
            DbContextOptions <DataContext> dbOptions =
                TestUtils.DbContextOptionsInMemory <TestBeginCommit>(
                    nameof(this.Test_Commit_Writes_Record));

            await using DataContext dataContext = new DataContext(dbOptions);
            AuditHeaderRepository auditHeaderRepository = new AuditHeaderRepository(
                logger: auditHeaderRepositoryLoggerMock.Object,
                dataContext: dataContext);
            Mock <IOrganisationRepository> organisationRepositoryMock
                = MockFactory.CreateRepositoryMock <IOrganisationRepository>();

            VirtualBridgeData data = new VirtualBridgeData(
                logger: loggerMock.Object,
                dataContext: dataContext,
                auditHeaderRepository: auditHeaderRepository,
                organisationRepository: organisationRepositoryMock.Object);

            IWho who = Create.Who();

            // ACT
            IAuditHeaderWithAuditDetails auditHeader = await data.BeginTransactionAsync(
                who : who,
                auditEvent : EAuditEvent.OrganisationMaintenance)
                                                       .ConfigureAwait(false);

            auditHeader.AuditDetails.Add(
                AuditDetail.CreateForCreate(
                    auditHeader: auditHeader,
                    tableName: "Organisation",
                    columnName: "Name",
                    recordId: Guid.NewGuid(),
                    newValue: "NewValue"));

            await data.CommitTransactionAsync(who, auditHeader)
            .ConfigureAwait(false);

            // ASSERT
            int auditHeadersCount = await dataContext.AuditHeaders.CountAsync()
                                    .ConfigureAwait(false);

            int auditDetailsCount = await dataContext.AuditDetails.CountAsync()
                                    .ConfigureAwait(false);

            Assert.AreEqual(1, auditHeadersCount);
            Assert.AreEqual(1, auditDetailsCount);
        }
 public void ApplyOldValue(ChangeTypes changeType, AuditDetail change)
 {
     if (changeType == ChangeTypes.Delete)
     {
         FieldValue = change.NewValue;
     }
     else
     {
         FieldValue = change.OldValue;
     }
     IsChanged = true;
 }
        private async Task AuditAsync(AuditDetail data)
        {
            var client  = RestFactory.CreateClient(BaseUrl);
            var request = RestFactory.CreateRequest("api/InssAuditMessaging", RestSharp.Method.POST);

            request = request.AddJsonBody(data);

            var response = await client.ExecuteAsync(request);

            if (!response.IsSuccessful)
            {
                Logger.LogWarning($"Auditing Failed: {response.StatusCode}");
            }
        }
示例#24
0
        /// <summary>
        /// Displays audit change history details on the console.
        /// </summary>
        /// <param name="detail"></param>
        //<snippetAuditing2>
        private static void DisplayAuditDetails(AuditDetail detail)
        {
            // Write out some of the change history information in the audit record.
            Audit record = (Audit)detail.AuditRecord;

            Console.WriteLine("\nAudit record created on: {0}", record.CreatedOn.Value.ToLocalTime());
            Console.WriteLine("Entity: {0}, Action: {1}, Operation: {2}",
                              record.ObjectId.LogicalName, record.FormattedValues["action"],
                              record.FormattedValues["operation"]);

            // Show additional details for certain AuditDetail sub-types.
            var detailType = detail.GetType();

            if (detailType == typeof(AttributeAuditDetail))
            {
                var attributeDetail = (AttributeAuditDetail)detail;

                // Display the old and new attribute values.
                foreach (KeyValuePair <String, object> attribute in attributeDetail.NewValue.Attributes)
                {
                    String oldValue = "(no value)", newValue = "(no value)";

                    //TODO Display the lookup values of those attributes that do not contain strings.
                    if (attributeDetail.OldValue.Contains(attribute.Key))
                    {
                        oldValue = attributeDetail.OldValue[attribute.Key].ToString();
                    }

                    newValue = attributeDetail.NewValue[attribute.Key].ToString();

                    Console.WriteLine("Attribute: {0}, old value: {1}, new value: {2}",
                                      attribute.Key, oldValue, newValue);
                }

                foreach (KeyValuePair <String, object> attribute in attributeDetail.OldValue.Attributes)
                {
                    if (!attributeDetail.NewValue.Contains(attribute.Key))
                    {
                        String newValue = "(no value)";

                        //TODO Display the lookup values of those attributes that do not contain strings.
                        String oldValue = attributeDetail.OldValue[attribute.Key].ToString();

                        Console.WriteLine("Attribute: {0}, old value: {1}, new value: {2}",
                                          attribute.Key, oldValue, newValue);
                    }
                }
            }
            Console.WriteLine();
        }
示例#25
0
        private async Task AuditUpdatesAsync()
        {
            foreach (var entry in ModifiedEntries)
            {
                var oldEntityValues = await entry.GetDatabaseValuesAsync();

                var newEntityValues = entry.CurrentValues;

                var log = new AuditLog
                {
                    EntityState   = "M",
                    Entity        = $"{ entry.Metadata.Relational().Schema }.{ entry.Metadata.Relational().TableName }",
                    EntityId      = entry.Entity.Id,
                    RowModifyUser = UserService.GetCurrentUser(),
                    RowModifyDate = DateTime.UtcNow,
                    AuditDetails  = new List <AuditDetail>()
                };

                foreach (var property in newEntityValues.Properties.Where(p => !ExcludedProperties.Contains(p.Name)))
                {
                    var oldValue = oldEntityValues[property.Name];
                    var newValue = newEntityValues[property.Name];

                    if (oldValue == null && newValue == null)
                    {
                        continue;
                    }

                    if (oldValue != null && newValue != null && oldValue.Equals(newValue))
                    {
                        continue;
                    }

                    var detail = new AuditDetail
                    {
                        Property = property.Name,
                        OldValue = oldValue?.ToString() ?? "",
                        NewValue = newValue?.ToString() ?? ""
                    };

                    log.AuditDetails.Add(detail);
                }

                if (log.AuditDetails.Any())
                {
                    NewAuditLogs.Add(log);
                }
            }
        }
示例#26
0
        /// <summary>
        /// Audits the create.
        /// </summary>
        /// <param name="auditHeader">Audit Header.</param>
        /// <param name="newObject">New value.</param>
        /// <param name="recordId">Record Id.</param>
        internal static void AuditCreate(
            IAuditHeaderWithAuditDetails?auditHeader,
            BaseDto newObject,
            Guid recordId)
        {
            if (auditHeader == null)
            {
                return;
            }

            Type type = newObject.GetType();

            PropertyDescriptorCollection propertyDescriptors = TypeDescriptor.GetProperties(type);

            foreach (PropertyInfo propertyInfo in type.GetProperties().OrderBy(p => p.MetadataToken))
            {
                if (!PropertyUtilities.
                    IsAuditableColumn(propertyDescriptors, propertyInfo))
                {
                    continue;
                }

                string newValue = propertyInfo.GetValueAsString(newObject);

                PropertyDescriptor propertyDescriptor = propertyDescriptors[propertyInfo.Name];

                TableAttribute?tableAttribute =
                    (TableAttribute?)propertyDescriptor.Attributes[typeof(TableAttribute)];
                string tableName = tableAttribute == null
                    ? type.Name
                    : tableAttribute.Name;

                ColumnAttribute?columnAttribute =
                    (ColumnAttribute?)propertyDescriptor.Attributes[typeof(ColumnAttribute)];
                string columnName = columnAttribute == null
                    ? propertyInfo.Name
                    : columnAttribute.Name;

                IAuditDetail auditDetail = AuditDetail.CreateForCreate(
                    auditHeader: auditHeader,
                    tableName: tableName,
                    columnName: columnName,
                    recordId: recordId,
                    newValue: newValue);

                auditHeader.AuditDetails.Add(auditDetail);
            }
        }
示例#27
0
        public async Task AuditAsync()
        {
            foreach (var entry in AddedEntries)
            {
                var newEntityValues = entry.CurrentValues;

                var log = new AuditLog
                {
                    EntityState   = "A",
                    Entity        = $"{ entry.Metadata.Relational().Schema }.{ entry.Metadata.Relational().TableName }",
                    EntityId      = entry.Entity.Id,
                    RowModifyUser = UserService.GetCurrentUser(),
                    RowModifyDate = DateTime.UtcNow,
                    AuditDetails  = new List <AuditDetail>()
                };

                foreach (var property in newEntityValues.Properties.Where(p => !ExcludedProperties.Contains(p.Name)))
                {
                    var newValue = newEntityValues[property];

                    if (newValue == null)
                    {
                        continue;
                    }

                    var detail = new AuditDetail
                    {
                        Property = property.Name,
                        OldValue = "",
                        NewValue = newValue.ToString()
                    };

                    log.AuditDetails.Add(detail);
                }

                if (log.AuditDetails.Any())
                {
                    NewAuditLogs.Add(log);
                }
            }

            if (NewAuditLogs.Any())
            {
                await AuditLogs.AddRangeAsync(NewAuditLogs);
                await SaveChangesAsync();
            }
        }
示例#28
0
        public async Task PerformAuditing(AuditDetail auditDetail)
        {
            var client  = _restFactory.CreateClient(_baseUrl);
            var request = _restFactory.CreateRequest("api/InssAuditMessaging", RestSharp.Method.POST);

            request = request.AddJsonBody(auditDetail);

            var response = await client.ExecuteAsync(request);

            if (!response.IsSuccessful)
            {
                string errorMessage = $"Auditing Failed: {response.StatusCode}";

                _logger.LogWarning(errorMessage);

                throw new Exception(errorMessage);
            }
        }
        /// <summary>
        /// Displays audit change history details on the console.
        /// </summary>
        /// <param name="detail"></param>
        private static void DisplayAuditDetails(CrmServiceClient service, AuditDetail detail)
        {
            // Write out some of the change history information in the audit record.
            var record = (Audit)detail.AuditRecord;

            Console.WriteLine($"\nAudit record created on: {record.CreatedOn.Value.ToLocalTime()}");
            Console.WriteLine($"Entity: {record.ObjectId.LogicalName}, Action: {record.FormattedValues["action"]}, Operation: {record.FormattedValues["operation"]}");
            Console.WriteLine($"Operation performed by {record.UserId.Name}");

            // Show additional details for certain AuditDetail sub-types.
            var detailType = detail.GetType();

            if (detailType == typeof(AttributeAuditDetail))
            {
                var    attributeDetail = (AttributeAuditDetail)detail;
                string oldValue = "(no value)", newValue = "(no value)";

                // Display the old and new attribute values.
                foreach (KeyValuePair <string, object> attribute in attributeDetail.NewValue.Attributes)
                {
                    if (attributeDetail.OldValue.Contains(attribute.Key))
                    {
                        oldValue = GetTypedValueAsString(attributeDetail.OldValue[attribute.Key]);
                    }

                    newValue = GetTypedValueAsString(attributeDetail.NewValue[attribute.Key]);

                    Console.WriteLine($"Attribute: {attribute.Key}, old value: {oldValue}, new value: {newValue}");
                }

                foreach (KeyValuePair <String, object> attribute in attributeDetail.OldValue.Attributes)
                {
                    if (!attributeDetail.NewValue.Contains(attribute.Key))
                    {
                        newValue = "(no value)";

                        oldValue = GetTypedValueAsString(attributeDetail.OldValue[attribute.Key]);

                        Console.WriteLine($"Attribute: {attribute.Key}, old value: {oldValue}, new value: {newValue}");
                    }
                }
            }
            Console.WriteLine();
        }
示例#30
0
文件: Audit.cs 项目: dev027/Agenda
        /// <summary>
        /// Audits the create.
        /// </summary>
        /// <param name="auditHeader">Audit Header.</param>
        /// <param name="newObject">New value.</param>
        /// <param name="recordId">Record Id.</param>
        internal static void AuditCreate(
            IAuditHeaderWithAuditDetails?auditHeader,
            BaseDto newObject,
            Guid recordId)
        {
            if (auditHeader == null)
            {
                return;
            }

            Type   type      = newObject.GetType();
            string tableName = type.Name; // TODO:[SJW] Assumed table name matches type name

            PropertyDescriptorCollection propertyDescriptors = TypeDescriptor.GetProperties(type);

            foreach (PropertyInfo propertyInfo in type.GetProperties().OrderBy(p => p.MetadataToken))
            {
                if (!PropertyUtilities.IsAuditableColumn(propertyDescriptors, propertyInfo))
                {
                    continue;
                }

                string newValue = propertyInfo.GetGetMethod().Invoke(newObject, null) == null
                    ? string.Empty
                    : propertyInfo.GetGetMethod().Invoke(newObject, null).ToString();

                PropertyDescriptor propertyDescriptor = propertyDescriptors[propertyInfo.Name];
                ColumnAttribute?   columnAttribute    =
                    (ColumnAttribute?)propertyDescriptor.Attributes[typeof(ColumnAttribute)];
                string columnName = columnAttribute == null
                    ? propertyInfo.Name
                    : columnAttribute.Name ?? string.Empty;

                IAuditDetail auditDetail = AuditDetail.CreateForCreate(
                    auditHeader: auditHeader,
                    tableName: tableName,
                    columnName: columnName,
                    recordId: recordId,
                    newValue: newValue);

                auditHeader.AuditDetails.Add(auditDetail);
            }
        }
        /// <summary>
        /// Displays the audit details.
        /// </summary>
        /// <param name="detail">The detail.</param>
        /// <param name="profile">The profile.</param>
        /// <param name="ObjectName">Name of the object.</param>
        /// <param name="path">The path.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="DisplayedColumns">The displayed columns.</param>
        private void DisplayAuditDetails(AuditDetail detail, MSCRMAuditExportProfile profile, string ObjectName, string path, List<string> columns, List<string> DisplayedColumns)
        {
            Audit record = (Audit)detail.AuditRecord;

            if (profile.AuditRecordCreatedOnFilter == "Last X Days")
            {
                DateTime CreatedOnBottomLimit = DateTime.Today.AddDays(-(double)profile.AuditRecordCreatedOnFilterLastX);
                if (CreatedOnBottomLimit > record.CreatedOn)
                    return;
            }
            else if (profile.AuditRecordCreatedOnFilter == "Last X Months")
            {
                DateTime CreatedOnBottomLimit = DateTime.Today.AddMonths(-(int)profile.AuditRecordCreatedOnFilterLastX);
                if (CreatedOnBottomLimit > record.CreatedOn)
                    return;
            }
            else if (profile.AuditRecordCreatedOnFilter == "Last X Years")
            {
                DateTime CreatedOnBottomLimit = DateTime.Today.AddYears(-(int)profile.AuditRecordCreatedOnFilterLastX);
                if (CreatedOnBottomLimit > record.CreatedOn)
                    return;
            }
            else if (profile.AuditRecordCreatedOnFilter == "Between Dates")
            {
                if (profile.AuditRecordCreatedOnFilterFrom > record.CreatedOn || profile.AuditRecordCreatedOnFilterTo < record.CreatedOn)
                    return;
            }

            List<AuditDetailLine> AuditDetailLines = new List<AuditDetailLine>();
            // Show additional details for certain AuditDetail sub-types.
            var detailType = detail.GetType();
            if (detailType == typeof(AttributeAuditDetail))
            {
                var attributeDetail = (AttributeAuditDetail)detail;
                AuditDetailLine adl = new AuditDetailLine();

                if (attributeDetail.NewValue != null)
                {
                    // Display the old and new attribute values.
                    foreach (KeyValuePair<String, object> attribute in attributeDetail.NewValue.Attributes)
                    {
                        String oldValue = "(no value)", newValue = "(no value)";

                        //format values
                        oldValue = getFormattedValue(attributeDetail.OldValue, attribute.Key);
                        newValue = getFormattedValue(attributeDetail.NewValue, attribute.Key);

                        adl = new AuditDetailLine();
                        adl.TransactionId = record.Id;
                        adl.createdon = record.CreatedOn.Value.ToLocalTime();
                        adl.UserName = record.UserId.Name;
                        adl.RecordLogicalName = record.ObjectId.LogicalName;
                        adl.RecordName = ObjectName;
                        adl.action = record.FormattedValues["action"];
                        adl.operation = record.FormattedValues["operation"];
                        adl.key = attribute.Key;
                        adl.oldValue = oldValue;
                        adl.newValue = newValue;

                        AuditDetailLines.Add(adl);
                    }
                }

                if (attributeDetail.OldValue != null)
                {
                    foreach (KeyValuePair<String, object> attribute in attributeDetail.OldValue.Attributes)
                    {
                        if (!attributeDetail.NewValue.Contains(attribute.Key))
                        {
                            String newValue = "(no value)";

                            //format values
                            String oldValue = getFormattedValue(attributeDetail.OldValue, attribute.Key);

                            adl = new AuditDetailLine();
                            adl.TransactionId = record.Id;
                            adl.createdon = record.CreatedOn.Value.ToLocalTime();
                            adl.UserName = record.UserId.Name;
                            adl.RecordLogicalName = record.ObjectId.LogicalName;
                            adl.RecordName = ObjectName;
                            adl.action = record.FormattedValues["action"];
                            adl.operation = record.FormattedValues["operation"];
                            adl.key = attribute.Key;
                            adl.oldValue = oldValue;
                            adl.newValue = newValue;

                            AuditDetailLines.Add(adl);
                        }
                    }
                }
            }
            else
            {
                AuditDetailLine adl = new AuditDetailLine();
                adl.TransactionId = record.Id;
                adl.createdon = record.CreatedOn.Value.ToLocalTime();
                adl.UserName = record.UserId.Name;
                adl.RecordLogicalName = record.ObjectId.LogicalName;
                adl.RecordName = ObjectName;
                adl.action = record.FormattedValues["action"];
                adl.operation = record.FormattedValues["operation"];

                AuditDetailLines.Add(adl);
            }

            if (profile.ExportFormat.ToLower() == "csv")
                WriteCSVAuditDetail(AuditDetailLines, fileName, columns, DisplayedColumns);
            else if (profile.ExportFormat.ToLower() == "xml")
                WriteXMLAuditDetail(AuditDetailLines, fileName, columns, DisplayedColumns);
            else if (profile.ExportFormat.ToLower() == "xml spreadsheet 2003")
                WriteXMLSpreadsheet2003AuditDetail(AuditDetailLines, fileName, columns, DisplayedColumns);
        }
示例#32
0
        private static void GetAuditDetails( DbContext dbContext, ContextItem item, int? personAliasId )
        {
            // Get the base class (not the proxy class)
            Type rockEntityType = item.Entity.GetType();
            if ( rockEntityType.IsDynamicProxyType() )
            {
                rockEntityType = rockEntityType.BaseType;
            }

            // Check to make sure class does not have [NotAudited] attribute
            if ( AuditClass( rockEntityType ) )
            {
                var dbEntity = item.DbEntityEntry;
                var audit = item.Audit;

                PropertyInfo[] properties = rockEntityType.GetProperties();

                foreach ( PropertyInfo propInfo in properties )
                {
                    // Check to make sure property does not have the [NotAudited] attribute
                    if ( AuditProperty( propInfo ) )
                    {
                        // If entire entity was added or deleted or this property was modified
                        var dbPropertyEntry = dbEntity.Property( propInfo.Name );
                        if ( dbPropertyEntry != null && (
                            dbEntity.State == EntityState.Added ||
                            dbEntity.State == EntityState.Deleted ||
                            dbPropertyEntry.IsModified ) )
                        {
                            var currentValue = dbEntity.State == EntityState.Deleted ? string.Empty : dbPropertyEntry.CurrentValue;
                            var originalValue = dbEntity.State == EntityState.Added ? string.Empty : dbPropertyEntry.OriginalValue;

                            var detail = new AuditDetail();
                            detail.Property = propInfo.Name;
                            detail.CurrentValue = currentValue != null ? currentValue.ToString() : string.Empty;
                            detail.OriginalValue = originalValue != null ? originalValue.ToString() : string.Empty;
                            if ( detail.CurrentValue != detail.OriginalValue )
                            {
                                audit.Details.Add( detail );
                            }
                        }
                    }
                }

                if ( audit.Details.Any() )
                {
                    var entityType = Rock.Web.Cache.EntityTypeCache.Read( rockEntityType );
                    if ( entityType != null )
                    {
                        string title;
                        try
                        {
                            title = item.Entity.ToString();
                        }
                        catch
                        {
                            // ignore exception (Entity often overrides ToString() and we don't want that prevent the audit if it fails)
                            title = null;
                        }

                        if ( string.IsNullOrWhiteSpace( title ) )
                        {
                            title = entityType.FriendlyName ?? string.Empty;
                        }
                        audit.DateTime = RockDateTime.Now;
                        audit.PersonAliasId = personAliasId;
                        audit.EntityTypeId = entityType.Id;
                        audit.EntityId = item.Entity.Id;
                        audit.Title = title.Truncate( 195 );
                    }
                }
            }
        }
示例#33
0
        /// <summary>
        /// Displays audit change history details on the console.
        /// </summary>
        /// <param name="detail"></param>
        //<snippetAuditing2>
        private static void DisplayAuditDetails(AuditDetail detail)
        {
            // Write out some of the change history information in the audit record. 
            Audit record = (Audit)detail.AuditRecord;

            Console.WriteLine("\nAudit record created on: {0}", record.CreatedOn.Value.ToLocalTime());
            Console.WriteLine("Entity: {0}, Action: {1}, Operation: {2}",
                record.ObjectId.LogicalName, record.FormattedValues["action"],
                record.FormattedValues["operation"]);

            // Show additional details for certain AuditDetail sub-types.
            var detailType = detail.GetType();
            if (detailType == typeof(AttributeAuditDetail))
            {
                var attributeDetail = (AttributeAuditDetail)detail;

                // Display the old and new attribute values.
                foreach (KeyValuePair<String, object> attribute in attributeDetail.NewValue.Attributes)
                {
                    String oldValue = "(no value)", newValue = "(no value)";

                    //TODO Display the lookup values of those attributes that do not contain strings.
                    if (attributeDetail.OldValue.Contains(attribute.Key))
                        oldValue = attributeDetail.OldValue[attribute.Key].ToString();

                    newValue = attributeDetail.NewValue[attribute.Key].ToString();

                    Console.WriteLine("Attribute: {0}, old value: {1}, new value: {2}",
                        attribute.Key, oldValue, newValue);
                }

                foreach (KeyValuePair<String, object> attribute in attributeDetail.OldValue.Attributes)
                {
                    if (!attributeDetail.NewValue.Contains(attribute.Key))
                    {
                        String newValue = "(no value)";

                        //TODO Display the lookup values of those attributes that do not contain strings.
                        String oldValue = attributeDetail.OldValue[attribute.Key].ToString();

                        Console.WriteLine("Attribute: {0}, old value: {1}, new value: {2}",
                            attribute.Key, oldValue, newValue);
                    }
                }
            }
            Console.WriteLine();
        }