Ejemplo n.º 1
0
        private AuditRecordField GetEntryValueInString(ObjectStateEntry entry, bool isOrginal)
        {
            var auditTrailDetail = new AuditRecordField();
            //entry.CurrentValues
            //entry.OriginalValues.
            var rt = entry.GetModifiedProperties();

            if (entry.Entity is EntityObject)
            {
                foreach (string propName in entry.GetModifiedProperties())
                {
                }
            }
            return(auditTrailDetail);
        }
Ejemplo n.º 2
0
        //protected override DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
        //{
        //    var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
        //    if (entityEntry.Entity is AliasChapterRel && entityEntry.State == EntityState.Added)
        //    {
        //        AliasChapterRel entity = entityEntry.Entity as AliasChapterRel;
        //        if (entity.FirstKnownUseDate > entity.LastKnownUseDate)
        //        {
        //            result.ValidationErrors.Add(new System.Data.Entity.Validation.DbValidationError("FirstKnownUseDate", "Date error."));
        //        }
        //    }

        //    if (result.ValidationErrors.Count > 0)
        //    {
        //        return result;
        //    }
        //    else
        //    {
        //        return base.ValidateEntity(entityEntry, items);
        //    }
        //}

        private DBAudit AuditTrailFactory(ObjectStateEntry entry, int userId)
        {
            //var userRepo = new UserRepository(this);
            //var user = userRepo.Find(userId);

            DBAudit audit = new DBAudit();

            audit.RevisionStamp = DateTime.Now;
            audit.TableName     = entry.EntitySet.Name;
            audit.KeyValue      = (int?)entry.CurrentValues.GetValue(0);
            audit.UserName      = userName;

            if (entry.State == EntityState.Added)
            {//entry is Added
                audit.NewData = GetEntryValueInString(entry, false);
                audit.Actions = "Added";
            }
            else if (entry.State == EntityState.Deleted)
            {//entry in deleted
                audit.OldData = GetEntryValueInString(entry, true);
                audit.Actions = "Deleted";
            }
            else
            {//entry is modified
                //audit.OldData = GetEntryValueInString(entry, true);
                audit.NewData = GetEntryValueInString(entry, false);
                audit.Actions = "Modified";

                IEnumerable <string> modifiedProperties = entry.GetModifiedProperties();
                //assing collection of mismatched Columns name as serialized string
                audit.ChangedColumns = XMLSerializationHelper.XmlSerialize(modifiedProperties.ToArray());
            }

            return(audit);
        }
Ejemplo n.º 3
0
        public void TestDomainService_UpdateMemberToDefaultValue()
        {
            TestDomainServices.EF.Catalog service = ServerTestHelper.CreateInitializedDomainService <TestDomainServices.EF.Catalog>(DomainOperationType.Submit);

            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(service.GetType());

            // in the below, non RTO is simulated by leaving ReorderPoint as its default value in the
            // original instance
            AdventureWorksModel.Product currProduct = new AdventureWorksModel.Product {
                ProductID = 1, ReorderPoint = 0, Weight = 0
            };
            AdventureWorksModel.Product origProduct = new AdventureWorksModel.Product {
                ProductID = 1, Weight = 50.0M
            };

            // verify expected test state - this test relies on the below attribute values
            PropertyDescriptor pd = TypeDescriptor.GetProperties(typeof(AdventureWorksModel.Product))["ReorderPoint"];

            Assert.IsNull(pd.Attributes[typeof(RoundtripOriginalAttribute)]);
            pd = TypeDescriptor.GetProperties(typeof(AdventureWorksModel.Product))["Weight"];
            Assert.IsNotNull(pd.Attributes[typeof(RoundtripOriginalAttribute)]);
            pd = TypeDescriptor.GetProperties(typeof(AdventureWorksModel.Product))["SafetyStockLevel"];
            Assert.IsNotNull(pd.Attributes[typeof(ExcludeAttribute)]);

            ObjectContextExtensions.AttachAsModified(service.ObjectContext.Products, currProduct, origProduct);

            // verify the expected property modifications
            ObjectStateEntry stateEntry = service.ObjectContext.ObjectStateManager.GetObjectStateEntry(currProduct);

            string[] modifiedProperties = stateEntry.GetModifiedProperties().ToArray();
            Assert.IsTrue(modifiedProperties.Contains("ReorderPoint"));      // no RTO so this should be modified
            Assert.IsTrue(modifiedProperties.Contains("Weight"));            // RTO so this is picked up by normal value comparison
            Assert.IsFalse(modifiedProperties.Contains("SafetyStockLevel")); // excluded member, so shouldn't be marked modified
            Assert.IsFalse(modifiedProperties.Contains("ProductID"));        // key members shouldn't be marked modified
        }
Ejemplo n.º 4
0
 private static void ChangeInformation()
 {
     using (var data = new Formula1Entities())
     {
         var jean = new Racer
         {
             FirstName   = "Jean-Eric",
             LastName    = "Vergne",
             Nationality = "France",
             Starts      = 0
         };
         data.Racers.AddObject(jean);
         Racer fernando = data.Racers.Where("it.Lastname='Alonso'").First();
         fernando.Starts++;
         DisplayState(EntityState.Added.ToString(),
                      data.ObjectStateManager.GetObjectStateEntries(EntityState.Added));
         DisplayState(EntityState.Modified.ToString(),
                      data.ObjectStateManager.GetObjectStateEntries(EntityState.Modified));
         ObjectStateEntry stateOfFernando =
             data.ObjectStateManager.GetObjectStateEntry(fernando.EntityKey);
         Console.WriteLine("state of Fernando: {0}",
                           stateOfFernando.State.ToString());
         foreach (string modifiedProp in stateOfFernando.GetModifiedProperties())
         {
             Console.WriteLine("modified: {0}", modifiedProp);
             Console.WriteLine("original: {0}",
                               stateOfFernando.OriginalValues[modifiedProp]);
             Console.WriteLine("current: {0}",
                               stateOfFernando.CurrentValues[modifiedProp]);
         }
     }
 }
        private DBAudit AuditTrailFactory(ObjectStateEntry entry, string UserName)
        {
            DBAudit audit = new DBAudit();

            audit.AuditId       = Guid.NewGuid().ToString();
            audit.RevisionStamp = DateTime.Now;
            audit.TableName     = entry.EntitySet.Name;
            audit.UserName      = UserName;

            if (entry.State == EntityState.Added)
            {//entry is Added
                audit.NewData = GetEntryValueInString(entry, false);
                audit.Actions = AuditActions.I.ToString();
            }
            else if (entry.State == EntityState.Deleted)
            {//entry in deleted
                audit.OldData = GetEntryValueInString(entry, true);
                audit.Actions = AuditActions.D.ToString();
            }
            else
            {//entry is modified
                audit.OldData = GetEntryValueInString(entry, true);
                audit.NewData = GetEntryValueInString(entry, false);
                audit.Actions = AuditActions.U.ToString();

                IEnumerable <string> modifiedProperties = entry.GetModifiedProperties();
                //assing collection of mismatched Columns name as serialized string
                audit.ChangedColumns = XMLSerializationHelper.XmlSerialize(modifiedProperties.ToArray());
            }

            return(audit);
        }
Ejemplo n.º 6
0
        private void GetEntryValueInString(ObjectStateEntry entry, bool isOrginal, ref DocumentAudit auditEntity)
        {
            PropertyInfo[] entityProperties = auditEntity.GetType().GetProperties().Where(p => p.PropertyType != typeof(EntityCollection <>) &&
                                                                                          p.PropertyType != typeof(EntityState) &&
                                                                                          p.PropertyType != typeof(EntityKey) &&
                                                                                          p.PropertyType != typeof(EntityObject) &&
                                                                                          p.PropertyType != typeof(EntityReference) &&
                                                                                          p.PropertyType.FullName != "System.Object").ToArray();

            foreach (string propName in entry.GetModifiedProperties())
            {
                if (propName == "Id")
                {
                    continue;
                }

                // object setterValue = null;
                var prop = entityProperties.FirstOrDefault(p => p.Name.ToLower() == propName.ToLower());
                if (prop != null)
                {
                    var currentValue = entry.CurrentValues[propName];
                    var orignalValue = auditEntity.GetType().GetProperty(propName).GetValue(auditEntity, null); //.OriginalValues[propName];
                    if (!object.ReferenceEquals(currentValue, orignalValue))                                    //currentValue.Equals(orignalValue))
                    {
                        if (currentValue == DBNull.Value)
                        {
                            currentValue = null;
                        }
                        PropertyInfo propInfo = auditEntity.GetType().GetProperty(propName);
                        propInfo.SetValue(auditEntity, currentValue, null);
                    }
                }
            }//end foreach
        }
Ejemplo n.º 7
0
        private string getAuditOperation(ObjectStateEntry objectStateEntry)
        {
            EntityState entityState = objectStateEntry.State;
            string      operation   = "UNKNOWN";

            switch (entityState)
            {
            case EntityState.Added:
                operation = AuditingOperation.INSERT.ToString();
                break;

            case EntityState.Modified:
                if (objectStateEntry.GetModifiedProperties().First().ToLower() == ("Deleted").ToLower())
                {
                    operation = operation = AuditingOperation.DELETE.ToString();
                }
                else
                {
                    operation = AuditingOperation.UPDATE.ToString();
                }
                break;

            case EntityState.Deleted:
                operation = AuditingOperation.DELETE.ToString();
                break;
            }

            return(operation);
        }
Ejemplo n.º 8
0
        private void EntriesComparer_Load(object sender, EventArgs e)
        {
            var modifiedProperties = _entry.GetModifiedProperties();

            for (int i = 0; i < _entry.OriginalValues.FieldCount; i++)
            {
                var isModified = modifiedProperties.Any(n => n ==
                                                        _entry.OriginalValues.GetName(i));
                TreeNode node = new TreeNode(CreateNodeText(
                                                 _entry.OriginalValues.GetName(i), isModified));
                node.Checked = isModified;
                node.Tag     = _entry.OriginalValues.GetName(i);
                tree.Nodes.Add(node);
                if (_entry.OriginalValues[i] is DbDataRecord)
                {
                    DrawComplexType(node, _entry.OriginalValues[i] as DbDataRecord,
                                    _entry.CurrentValues[i] as DbDataRecord);
                }
                else
                {
                    DrawProperty(node, _entry.OriginalValues[i],
                                 _entry.CurrentValues[i]);
                }
            }
        }
Ejemplo n.º 9
0
        public static void VisualizeObjectStateEntryOLD(this EntityKey eKey, ObjectContext context)
        {
            ObjectStateEntry ose = null;

            //If object is Detached, then there will be on Entry in the ObjectStateManager

            if (!(context.ObjectStateManager.TryGetObjectStateEntry(eKey, out ose)))
            {
                MessageBox.Show("Object is not currently being change tracked and no ObjectStateEntry exists.", "ObjectStateEntryVisualizer", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                var currentValues = ose.CurrentValues;
                //If Object is Added, there will be no Original values and it will throw an exception
                DbDataRecord originalValues = null;
                if (ose.State != EntityState.Added)
                {
                    originalValues = ose.OriginalValues;
                }
                //walk through arrays to get the values
                var valueArray = new System.Collections.ArrayList();
                for (var i = 0; i < currentValues.FieldCount; i++)
                {
                    //metadata provides field names
                    var    sName    = currentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;
                    var    sCurrVal = currentValues[i];
                    object sOrigVal = null;
                    if (originalValues == null)
                    {
                        sOrigVal = "n/a"; //this will be for Added entities
                    }
                    else
                    {
                        sOrigVal = originalValues[i];
                    }
                    string changedProp = (
                        from prop in ose.GetModifiedProperties()
                        where prop == sName
                        select prop).FirstOrDefault();

                    string propModified;

                    if (changedProp == null)
                    {
                        propModified = "";
                    }
                    else
                    {
                        propModified = "X";
                    }
                    valueArray.Add(new { _Index = i.ToString(), _Property = sName, Current = sCurrVal, Original = sOrigVal, ValueModified = propModified });
                }
                var form = new VisualizerForm();
                form.dataGridView1.DataSource = valueArray;
                form.lblState.Text            = ose.State.ToString();
                form.lblType.Text             = ose.Entity.ToString();
                form.ShowDialog();
            }
        }
Ejemplo n.º 10
0
        private string GetEntryValueInString(ObjectStateEntry entry, bool isOrginal)
        {
            StringBuilder sb = new StringBuilder();

            foreach (string propertyName in entry.GetModifiedProperties())
            {
                DbDataRecord       original = entry.OriginalValues;
                CurrentValueRecord current  = entry.CurrentValues;
                //if (original.GetValue(original.GetOrdinal(propertyName)).ToString() != current.GetValue(current.GetOrdinal(propertyName)).ToString())
                //{
                if (isOrginal)
                {
                    sb.Append(String.Format("Property:{0} Value:{1} /", propertyName, original.GetValue(original.GetOrdinal(propertyName)).ToString()));
                }
                else
                {
                    sb.Append(String.Format("Property:{0} Value:{1} /", propertyName, current.GetValue(current.GetOrdinal(propertyName)).ToString()));
                }
                //}
            }
            return(sb.ToString());

            //if (entry.Entity is EntityObject)
            //{
            //    object target = CloneEntity((EntityObject)entry.Entity);
            //    foreach (string propName in entry.GetModifiedProperties())
            //    {
            //        object setterValue = null;
            //        if (isOrginal)
            //        {
            //            //Get orginal value
            //            setterValue = entry.OriginalValues[propName];
            //        }
            //        else
            //        {
            //            //Get orginal value
            //            setterValue = entry.CurrentValues[propName];
            //        }
            //        //Find property to update
            //        PropertyInfo propInfo = target.GetType().GetProperty(propName);
            //        //update property with orgibal value
            //        if (setterValue == DBNull.Value)
            //        {//
            //            setterValue = null;
            //        }
            //        propInfo.SetValue(target, setterValue, null);
            //    }//end foreach

            //    XmlSerializer formatter = new XmlSerializer(target.GetType());
            //    XDocument document = new XDocument();

            //    using (XmlWriter xmlWriter = document.CreateWriter())
            //    {
            //        formatter.Serialize(xmlWriter, target);
            //    }
            //    return document.Root.ToString();
            //}
            //return null;
        }
Ejemplo n.º 11
0
        IEnumerable <ModifiedProperty> IAuditableContext.GetModifiedProperties(object entity)
        {
            ObjectStateEntry entry = ObjectStateManager.GetObjectStateEntry(entity);

            return
                (entry.GetModifiedProperties().Select(
                     p =>
                     new ModifiedProperty(entity.GetType().GetProperty(p), entry.OriginalValues[p], entry.CurrentValues[p])));
        }
Ejemplo n.º 12
0
        private void ProcessUpdating(string contentName, IQPArticle instance, ObjectStateEntry entry)
        {
            throw new NotImplementedException();
            var      properties = entry.GetModifiedProperties().ToList();
            var      values     = instance.Pack(this);
            DateTime modified   = DateTime.Now;

            throw new NotImplementedException("CUD operations are not implemented yet.");
            // Cnn.AddFormToContent(SiteId, Cnn.GetContentIdByNetName(SiteId, contentName), instance.StatusType.StatusTypeName, ref values, (int)instance.Id, true, 0, instance.Visible, instance.Archive, true, ref modified);
            // instance.Modified = modified;
        }
 private void SetDeletedProperties(ObjectStateEntry entry, StringBuilder oldData)
 {
     foreach (var propertyName in entry.GetModifiedProperties())
     {
         var oldVal = entry.OriginalValues[propertyName];
         if (oldVal != null)
         {
             oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
         }
     }
 }
 private void SetModifiedProperties(ObjectStateEntry entry, StringBuilder oldData, StringBuilder newData)
 {
     foreach (var propertyName in entry.GetModifiedProperties())
     {
         var oldVal = entry.OriginalValues[propertyName];
         var newVal = entry.CurrentValues[propertyName];
         if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
         {
             newData.AppendFormat("{0}={1} || ", propertyName, newVal);
             oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
         }
     }
 }
Ejemplo n.º 15
0
        private void AuditChange(ObjectStateEntry entry)
        {
            var obj = entry.Entity as IModelObject;

            if (obj == null)
            {
                return;
            }

            var audit = new AuditLog
            {
                Action     = entry.State.ToString(),
                Changed    = DateTime.Now,
                ObjectId   = obj.Id,
                User       = Thread.CurrentPrincipal.Identity.Name,
                Collection = entry.EntitySet.Name
            };

            switch (entry.State)
            {
            case EntityState.Added:
                audit.Comment = obj.GetReportHtml();
                break;

            case EntityState.Modified:
                string report = string.Format("<b>{0}</b><br/>", entry.Entity);
                foreach (var prop in entry.GetModifiedProperties())
                {
                    var    displayFormat = entry.Entity.GetType().GetProperty(prop).GetCustomAttribute <DisplayFormatAttribute>();
                    string format        = displayFormat == null ? "{0}" : displayFormat.DataFormatString;

                    report += string.Format(
                        "{0}: {1} => {2}<br/>",
                        prop,
                        string.Format(format, entry.OriginalValues[prop]),
                        string.Format(format, entry.CurrentValues[prop]));
                }
                audit.Comment = report;
                break;

            case EntityState.Deleted:
                object original;
                this.ComparisonContext.TryGetObjectByKey(entry.EntityKey, out original);
                audit.Comment = ((IModelObject)original).GetReportHtml();
                break;

            default:
                throw new NotImplementedException("Unhandled state" + entry.State.ToString());
            }
            this.AuditLog.Add(audit);
        }
Ejemplo n.º 16
0
        public void AfterPersistence(ObjectStateEntry entry, ObjectContext context)
        {
            var type = entry.Entity.GetType();

            if (type.GetCustomAttributes(typeof(AuditableAttribute), false).Any())
            {
                string properties = null;
                if (entry.State == EntityState.Modified)
                {
                    properties = String.Join(", ", entry.GetModifiedProperties());
                }
                context.ExecuteStoreCommand("Exec InsertAudit {0}, {1}, {2}, {3}, {4}",
                                            entry.Entity.GetType().FullName, DateTime.Now, _username, entry.State.ToString().Substring(0, 1), properties);
            }
        }
Ejemplo n.º 17
0
            public ChangeEntry(ObjectStateEntry f)
            {
                Entity         = f.Entity;
                State          = f.State;
                OriginalValues = new Dictionary <string, object>();
                EntityType     = Entity.GetType().GetEntityType();

                if (State != EntityState.Modified)
                {
                    return;
                }

                var d = OriginalValues;

                foreach (var item in f.GetModifiedProperties())
                {
                    d[item] = f.OriginalValues[item];
                }
                OriginalValues = d;
            }
Ejemplo n.º 18
0
        private string GetEntryValueInString(ObjectStateEntry entry, bool isOrginal)
        {
            if (entry.Entity is EntityObject)
            {
                object target = CloneEntity((EntityObject)entry.Entity);

                foreach (string propName in entry.GetModifiedProperties())
                {
                    object setterValue = null;
                    if (isOrginal)
                    {
                        //Get orginal value
                        setterValue = entry.OriginalValues[propName];
                    }
                    else
                    {
                        //Get orginal value
                        setterValue = entry.CurrentValues[propName];
                    }
                    //Find property to update
                    PropertyInfo propInfo = target.GetType().GetProperty(propName);

                    //update property with orgibal value
                    if (setterValue == DBNull.Value)
                    {//
                        setterValue = null;
                    }
                    propInfo.SetValue(target, setterValue, null);
                }//end foreach

                XmlSerializer formatter = new XmlSerializer(target.GetType());
                XDocument     document  = new XDocument();

                using (XmlWriter xmlWriter = document.CreateWriter())
                {
                    formatter.Serialize(xmlWriter, target);
                }
                return(document.Root.ToString());
            }
            return(null);
        }
Ejemplo n.º 19
0
 private static void ChangeInformation()
 {
     using (var data = new Formula1Entities())
     {
         var jaime = new Racer
         {
             Firstname = "Jaime",
             Lastname  = "Alguersuari",
             Country   = "Spain",
             Starts    = 0
         };
         data.Racers.AddObject(jaime);
         Racer fernando = data.Racers.Where("it.Lastname='Alonso'").First();
         fernando.Starts++;
         DisplayState(EntityState.Added.ToString(),
                      data.ObjectStateManager.GetObjectStateEntries(EntityState.Added));
         DisplayState(EntityState.Modified.ToString(),
                      data.ObjectStateManager.GetObjectStateEntries(EntityState.Modified));
         ObjectStateEntry stateOfFernando =
             data.ObjectStateManager.GetObjectStateEntry(fernando.EntityKey);
         Console.WriteLine("state of Fernando: {0}",
                           stateOfFernando.State.ToString());
         foreach (string modifiedProp in stateOfFernando.GetModifiedProperties())
         {
             Console.WriteLine("modified: {0}", modifiedProp);
             Console.WriteLine("original: {0}", stateOfFernando.OriginalValues[modifiedProp]);
             Console.WriteLine("current: {0}", stateOfFernando.CurrentValues[modifiedProp]);
         }
         int changes = 0;
         try
         {
             changes += data.SaveChanges();
         }
         catch (OptimisticConcurrencyException ex)
         {
             data.Refresh(RefreshMode.ClientWins, ex.StateEntries);
             changes += data.SaveChanges();
         }
         Console.WriteLine("{0} entities changed", changes);
     }
 }
Ejemplo n.º 20
0
        private static IEnumerable <DatabaseEntityModifiedProperty> GetModifiedPropertiesForEntry(ObjectStateEntry entry)
        {
            IEnumerable <string> modifiedPropertyNames = entry.GetModifiedProperties();

            for (int i = 0; i < entry.OriginalValues.FieldCount; ++i)
            {
                string currentPropertyName = entry.OriginalValues.GetName(i);
                if (modifiedPropertyNames.Contains(currentPropertyName))
                {
                    object oldValue = entry.OriginalValues.GetValue(i);
                    object newValue = entry.CurrentValues.GetValue(i);

                    yield return(new DatabaseEntityModifiedProperty()
                    {
                        ValueBeforeChange = oldValue,
                        ValueAfterChange = newValue,
                        PropertyName = currentPropertyName,
                        TypeName = entry.OriginalValues.GetFieldType(i).ToString()
                    });
                }
            }
        }
Ejemplo n.º 21
0
        private void ProcessCreating(string contentName, IQPArticle instance, ObjectStateEntry entry)
        {
            throw new NotImplementedException();
            var      properties = entry.GetModifiedProperties().ToList();
            var      values     = instance.Pack(this);
            DateTime created    = DateTime.Now;
            // instance.LoadStatusType();
            // todo: load first status
            const string lowestStatus = "None";

            if (!properties.Contains("Visible"))
            {
                instance.Visible = true;
            }
            if (!properties.Contains("Archive"))
            {
                instance.Archive = false;
            }

            // instance.Id = Cnn.AddFormToContent(SiteId, Cnn.GetContentIdByNetName(SiteId, contentName), lowestStatus, ref values, 0, true, 0, instance.Visible, instance.Archive, true, ref created);
            instance.Created  = created;
            instance.Modified = created;
        }
Ejemplo n.º 22
0
        public List <AuditingDetail> GetAuditEntries(ObjectStateEntry objectStateEntry)
        {
            List <AuditingDetail> auditDetails = new List <AuditingDetail>();
            var allProperties      = getAllProperties(objectStateEntry);
            var modifiedProperties = objectStateEntry.GetModifiedProperties();
            var currentValues      = objectStateEntry.CurrentValues;

            if (objectStateEntry.State == EntityState.Added)
            {
                foreach (var propertyName in allProperties)
                {
                    // Add whole entry to database
                    auditDetails.Add(new AuditingDetail()
                    {
                        ColumnName = propertyName.Key.ToString(),
                        OldValue   = null,
                        NewValue   = currentValues[propertyName.Key.ToString()].ToString()
                    });
                }
            }
            else if (objectStateEntry.State == EntityState.Modified)
            {
                var originalValues = objectStateEntry.OriginalValues;

                // If object was in Modified state and property is Deleted => records has been Deleted
                // Record all of its properties to Audit
                if (currentValues[modifiedProperties.First()].ToString() == ("Deleted").ToLower())
                {
                    foreach (var propertyName in allProperties)
                    {
                        auditDetails.Add(new AuditingDetail()
                        {
                            ColumnName = propertyName.Key.ToString(),
                            OldValue   = originalValues[propertyName.Key.ToString()].ToString(),
                            NewValue   = null
                        });
                    }
                }
                else
                {
                    // Loop modified properties and make audit
                    foreach (var propertyName in modifiedProperties)
                    {
                        // write Decision date everytime
                        if (!currentValues[propertyName].Equals(originalValues[propertyName]) || propertyName == "ChangeDate")
                        {
                            string oldValue = originalValues[propertyName].ToString();
                            string newValue = currentValues[propertyName].ToString();

                            if (oldValue.Length > 0 && oldValue != "DELETED-VALUE" && newValue == "")
                            {
                                newValue = "DELETED-VALUE";
                            }

                            // Add only modified properties
                            auditDetails.Add(new AuditingDetail()
                            {
                                ColumnName = propertyName,
                                OldValue   = oldValue,
                                NewValue   = newValue
                            });
                        }
                    }
                }
            }

            return(auditDetails);
        }
Ejemplo n.º 23
0
 public IEnumerable <string> GetModifiedProperties()
 {
     return(_stateEntry.GetModifiedProperties());
 }
Ejemplo n.º 24
0
        private void AuditEntity()
        {
            var modifieds   = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified || e.State == EntityState.Added);
            var currentUser = string.Empty;

            if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
            {
                currentUser = HttpContext.Current.User.Identity.Name;
            }

            DateTime now = DateTime.Now;

            foreach (DbEntityEntry item in modifieds)
            {
                if (item.Entity is IAuditable changedOrAddedItem)
                {
                    if (item.State == EntityState.Added)
                    {
                        changedOrAddedItem.CreatedDate = now;

                        // When using user manager Http context is null so not update the current user with string empty
                        if (!string.IsNullOrEmpty(currentUser))
                        {
                            changedOrAddedItem.CreatedBy = currentUser;
                        }
                    }
                    changedOrAddedItem.UpdatedDate = now;

                    // When using user manager Http context is null so not update the current user with string empty
                    if (!string.IsNullOrEmpty(currentUser))
                    {
                        changedOrAddedItem.UpdatedBy = currentUser;
                    }

                    if (item.State == EntityState.Modified && item.Entity is IFieldChangeLog logItem)
                    {
                        ObjectContext    objContext     = ((IObjectContextAdapter)this).ObjectContext;
                        ObjectStateEntry objState       = objContext.ObjectStateManager.GetObjectStateEntry(item.Entity);
                        string           primaryKeyName = objState.EntitySet.ElementType.KeyMembers.Select(k => k.Name).FirstOrDefault();
                        string           id             = !string.IsNullOrEmpty(primaryKeyName) ? item.CurrentValues[primaryKeyName].ToString() : string.Empty;

                        List <FieldChangeLogDetail> changeLogs = new List <FieldChangeLogDetail>();

                        IEnumerable <string> modifiedProperties = objState.GetModifiedProperties();
                        foreach (var propName in modifiedProperties)
                        {
                            changeLogs.Add(new FieldChangeLogDetail
                            {
                                Field         = propName,
                                PreviousValue = objState.OriginalValues[propName].ToString(),
                                UpdatedValue  = objState.CurrentValues[propName].ToString()
                            });
                        }

                        string changeLog = JsonConvert.SerializeObject(changeLogs);

                        this.FieldChangeLogs.Add(new FieldChangeLog
                        {
                            Entity      = ObjectContext.GetObjectType(item.Entity.GetType()).Name,
                            EntityId    = id,
                            ChangeLog   = changeLog,
                            Action      = logItem.LatestAction,
                            CreatedBy   = currentUser,
                            CreatedDate = now,
                            UpdatedBy   = currentUser,
                            UpdatedDate = now
                        });
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private void LoadModifiedEntityEntry(ObjectStateEntry source, IDictionary <EntityKey, DbSyncEntry> cache)
        {
            Contract.Assert(source.IsRelationship == false);
            Contract.Assert(source.State == EntityState.Modified);

            var entry  = GetDbSyncEntry(source.EntityKey, cache);
            var entity = entry.TargetEntity;

            foreach (var property in source.GetModifiedProperties())
            {
                entry.PropertiesInternal.Add(property, new DbSyncPropertyEntry(property)
                {
                    CurrentValue  = source.CurrentValues[property],
                    OriginalValue = source.OriginalValues[property]
                });
            }

            foreach (var reference in GetReferences(source).Where(reference => IsSourceReference(reference) && IsSourceReferenceChanged(source, reference)))
            {
                var property = GetNavigationProperty(GetEntityType(source), reference);
                if (property == null)
                {
                    continue;
                }

                var currentKey  = reference.EntityKey;
                var originalKey = GetEntityTypeKeyOriginalValue(source, reference);

                DbSyncEntry original = null;
                DbSyncEntry current  = null;

                entry.ReferencesInternal.Add(property.Name, new DbSyncReferenceEntry(property.Name)
                {
                    CurrentValue  = currentKey != null && TryGetDbSyncEntry(currentKey, cache, out current) ? current.TargetEntity : null,
                    OriginalValue = originalKey != null && TryGetDbSyncEntry(originalKey, cache, out original) ? original.TargetEntity : null
                });

                var inverse = GetNavigationPropertyForTarget(reference);
                if (inverse == null)
                {
                    continue;
                }

                if (original != null && (EntityState.Modified | EntityState.Unchanged).HasFlag(original.SourceState))
                {
                    switch (inverse.ToEndMember.RelationshipMultiplicity)
                    {
                    case RelationshipMultiplicity.Many:

                        if (original.CollectionsInternal.TryGetValue(inverse.Name, out var collection))
                        {
                            collection.OriginalValuesInternal.Add(entity);
                        }
                        else
                        {
                            original.CollectionsInternal.Add(inverse.Name, new DbSyncCollectionEntry(inverse.Name)
                            {
                                OriginalValuesInternal = { entity }
                            });
                        }

                        break;

                    case RelationshipMultiplicity.One:
                    case RelationshipMultiplicity.ZeroOrOne:

                        if (original.ReferencesInternal.TryGetValue(inverse.Name, out var target))
                        {
                            target.OriginalValue = entity;
                        }
                        else
                        {
                            original.ReferencesInternal.Add(inverse.Name, new DbSyncReferenceEntry(inverse.Name)
                            {
                                OriginalValue = entity
                            });
                        }

                        break;
                    }
                }

                if (current != null && (EntityState.Modified | EntityState.Unchanged).HasFlag(current.SourceState))
                {
                    switch (inverse.ToEndMember.RelationshipMultiplicity)
                    {
                    case RelationshipMultiplicity.Many:
                        if (current.CollectionsInternal.TryGetValue(inverse.Name, out var collection))
                        {
                            collection.CurrentValuesInternal.Add(entity);
                        }
                        else
                        {
                            current.CollectionsInternal.Add(inverse.Name, new DbSyncCollectionEntry(inverse.Name)
                            {
                                CurrentValuesInternal = { entity }
                            });
                        }
                        break;

                    case RelationshipMultiplicity.One:
                    case RelationshipMultiplicity.ZeroOrOne:
                        if (current.ReferencesInternal.TryGetValue(inverse.Name, out var target))
                        {
                            target.OriginalValue = entity;
                        }
                        else
                        {
                            current.ReferencesInternal.Add(inverse.Name, new DbSyncReferenceEntry(inverse.Name)
                            {
                                OriginalValue = entity
                            });
                        }
                        break;
                    }
                }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="RoleObj"></param>
        /// <returns></returns>
        public bool Update(tblRole RoleNew)
        {
            tblRole RoleOld;
            int     counts = 0;//影响行数标记

            using (MWDatabaseEntities MWDB = new MWDatabaseEntities())
            {
                try
                {
                    RoleOld = MWDB.tblRole.First(t => t.RoleID == RoleNew.RoleID);
                    //更新数据字段
                    RoleOld.RoleName = RoleNew.RoleName;
                    RoleOld.RoleCode = RoleNew.RoleCode;
                    RoleOld.State    = RoleNew.State;
                    RoleOld.Desc     = RoleNew.Desc;

                    //获取当前登录用户的ID(Cookies)
                    string strUserID = HttpContext.Current.User.Identity.Name;
                    if (string.IsNullOrEmpty(strUserID))
                    {
                        FormsAuthentication.RedirectToLoginPage();
                        return(false);
                    }
                    System.Guid guidUserID = new Guid(strUserID);
                    RoleOld.LastModifiedByID = guidUserID;
                    RoleOld.LastModifiedDate = System.DateTime.Now;
                    RoleOld.SystemModstamp   = System.DateTime.Now;

                    //日志处理
                    ObjectStateEntry     ose  = MWDB.ObjectStateManager.GetObjectStateEntry(RoleOld);
                    IEnumerable <string> list = ose.GetModifiedProperties();
                    string logBody            = string.Empty;
                    foreach (string pr in list)
                    {
                        string strs   = pr;                                  //更新实体的属性名
                        string strNew = ose.CurrentValues[strs].ToString();  //实体的新值
                        string strOld = ose.OriginalValues[strs].ToString(); //实体的旧值
                        if (strNew != strOld)
                        {
                            strNew = string.IsNullOrEmpty(strNew) ? "null" : strNew;//如果字符串为空,则将null赋给字符串
                            strOld = string.IsNullOrEmpty(strOld) ? "null" : strOld;
                            switch (strs)
                            {
                            case "LastModifiedByID":
                                //系统字段不进行发送
                                break;

                            case "LastModifiedDate":
                                //系统字段不进行发送
                                break;

                            case "SystemModstamp":
                                //系统字段不进行发送
                                break;

                            default:
                                logBody += ", " + strs + ": '" + strOld + "'" + " had been changed '" + strNew + "'";
                                break;
                            }
                        }
                    }

                    counts = MWDB.SaveChanges();
                    if (counts > 0)
                    {
                        string userHostAddress = HttpContext.Current.Request.UserHostAddress;
                        DbLoggerBLL.SysLogger.Info("Update role info failed! Role update log: '"
                                                   + logBody + "'. User host address: '" + userHostAddress + "' .");
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    string userHostAddress = HttpContext.Current.Request.UserHostAddress;
                    DbLoggerBLL.SysLogger.Error("Update role info failed! Role ID: '"
                                                + RoleNew.RoleID + "'. User host address: '" + userHostAddress + "' . Exception info:" + ex.Message);
                    return(false);
                }
            }
            return(false);
        }
Ejemplo n.º 27
0
        public static void VisualizeEntityState(this ObjectContext context, object entity)
        {
            ObjectStateEntry ose = null;

            //If object is Detached, then there will be no Entry in the ObjectStateManager
            //new entities that are not attached will not even have an entitykey
            if (!context.ObjectStateManager.TryGetObjectStateEntry(entity, out ose))
            {
                MessageBox.Show("Object is not currently being change tracked " +
                                " and no ObjectStateEntry exists.",
                                "ObjectState Visualizer", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                var currentValues = ose.CurrentValues;
                //If Object is Added, there will be no Original values and it will throw an exception
                DbDataRecord originalValues = null;
                if (ose.State != EntityState.Added)
                {
                    originalValues = ose.OriginalValues;
                }

                //walk through arrays to get the values
                var valueArray = new System.Collections.ArrayList();
                for (var i = 0; i < currentValues.FieldCount; i++)
                {
                    //metadata provides field names
                    var    sName          = currentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;
                    bool   isdbDataRecord = false;
                    var    sCurrVal       = currentValues[i];
                    object sOrigVal       = null;

                    //test for complex type
                    if (currentValues[i] is DbDataRecord)
                    {
                        isdbDataRecord = true;
                    }

                    if (isdbDataRecord == false)
                    {//normal scalar data
                        sCurrVal = currentValues[i];
                    }
                    else
                    {
                        //complex type, anything else?
                        sCurrVal = ComplexTypeString((DbDataRecord)currentValues[i]);
                    }

                    if (ose.State == EntityState.Added)
                    {
                        sOrigVal = "n/a"; //this will be for Added entities
                    }
                    else
                    if (isdbDataRecord == false)
                    {//normal scalar data
                        sOrigVal = originalValues[i];
                    }
                    else
                    {
                        //complex type
                        sOrigVal = ComplexTypeString((DbDataRecord)originalValues[i]);
                    }
                    string changedProp = (
                        from prop in ose.GetModifiedProperties()
                        where prop == sName
                        select prop).FirstOrDefault();

                    string propModified;

                    if (changedProp == null)
                    {
                        propModified = "";
                    }
                    else
                    {
                        propModified = "X";
                    }
                    valueArray.Add(new { Index    = i.ToString(), Property = sName,
                                         Original = sOrigVal, Current = sCurrVal, ValueModified = propModified });
                }
                var form = new VisualizerForm();
                form.dataGridView1.DataSource = valueArray;
                form.lblState.Text            = ose.State.ToString();
                form.lblType.Text             = ose.Entity.ToString();
                form.ShowDialog();
            }
        }
Ejemplo n.º 28
0
        private List <Tuple <string, object, object> > GetForeignKeyLabels(ObjectContext context, ObjectStateEntry oce)
        {
            List <Tuple <string, object, object> > items = new List <Tuple <string, object, object> >();

            //FIND FOREIGN KEYS,GET THOSE FOREIGN KEY ENTITY, GET THEIR ENTITY LABELS
            var navigations = ((EntityType)oce.EntitySet.ElementType).DeclaredNavigationProperties;

            //INCLUDE THESE ENTITY LABELS IN MODIFIED PROPERTIES, SO THAT IT GETS LOGGED
            foreach (var navigation in navigations)
            {
                var rel = oce.RelationshipManager.GetRelatedEnd(navigation.RelationshipType.FullName, navigation.ToEndMember.Name);

                //&& rel.IsLoaded
                if (rel != null && rel is EntityReference)
                {
                    var reference = (rel as EntityReference);
                    //for added, deleted entities, we need to retrieve all the foreign objects
                    //but for changed entities, we only need to retrieve the foreign objects
                    //if the foreign key it self has changed on the object
                    if (oce.State == EntityState.Modified)
                    {
                        //check if any of the modified property is part of this foreign key
                        if (reference.EntityKey.EntityKeyValues.Select(kv => kv.Key).Intersect(oce.GetModifiedProperties().Where(prop => oce.IsPropertyChanged(prop))).Count() <= 0)
                        {
                            continue;
                        }
                    }

                    object entity;
                    //if the object is being deleted, retrieve with a special call to TryGetObjectByKey
                    if (oce.State == EntityState.Deleted)
                    {
                        context.TryGetObjectByKey(oce, rel, out entity);
                    }
                    else
                    {
                        rel.Load();
                        entity = reference.GetType().GetProperty("Value").GetValue(reference);
                    }

                    object oldEntity;
                    //IF THE OBJECT IS ADDED OR DETACHED THERE IS NO ORIGINAL VALUES
                    var gotOldEntity = !(oce.State == EntityState.Added || oce.State == EntityState.Detached || oce.State == EntityState.Deleted);
                    if (gotOldEntity)
                    {
                        //CHECK IF WE CAN GET BACK ORIGINAL VALUES
                        var originalKeys = reference.EntityKey.EntityKeyValues.Select(kv => new EntityKeyMember(kv.Key, oce.OriginalValues[kv.Key]));
                        gotOldEntity = context.TryGetObjectByKey(new System.Data.Entity.Core.EntityKey(reference.EntityKey.EntityContainerName + "." + reference.EntityKey.EntitySetName, originalKeys), out oldEntity);
                        //WRITE ORIGINAL VALUES, ONLY IF WE GOT BACK IT SUCCESSFULLY
                        entity.GetType().GetProperties().Where(y => y.GetCustomAttributes(true).Any(z => z is EntityLabelAttribute)).ToList().ForEach(r => items.Add(new Tuple <string, object, object>(r.Name, gotOldEntity ? r.GetValue(oldEntity) : "", r.GetValue(entity))));
                    }
                    else if (oce.State == EntityState.Deleted)
                    {
                        entity.GetType().GetProperties().Where(y => y.GetCustomAttributes(true).Any(z => z is EntityLabelAttribute)).ToList().ForEach(r => items.Add(new Tuple <string, object, object>(r.Name, r.GetValue(entity), "")));
                    }
                    else
                    {
                        //IF NOT, WRITE EMPTY STRINGS FOR ORIGINAL VALUES
                        entity.GetType().GetProperties().Where(y => y.GetCustomAttributes(true).Any(z => z is EntityLabelAttribute)).ToList().ForEach(r => items.Add(new Tuple <string, object, object>(r.Name, "", r.GetValue(entity))));
                    }
                }
            }
            return(items);
        }
Ejemplo n.º 29
0
        private List <ColumnInfo> GetEntityInfo(ObjectStateEntry objectEntry)
        {
            var type = objectEntry.Entity.GetType();

            ColumnInfo        columnInfo = null;
            List <ColumnInfo> columnList = new List <ColumnInfo>();

            // 获取变化的列
            List <string> changeColumns = objectEntry.GetModifiedProperties().ToList();

            // 历史值列表
            object[] originalValues = null;
            // 当前值列表
            object[] currentValues = null;
            foreach (var item in type.GetProperties())
            {
                if (item.GetCustomAttributes(typeof(NotMappedAttribute), false).Any())
                {
                    continue;
                }

                columnInfo = new ColumnInfo();

                // 物理列名
                var colatts = (ColumnAttribute[])item.GetCustomAttributes(typeof(ColumnAttribute), false);
                if (colatts.Count() > 0 && !string.IsNullOrWhiteSpace(colatts[0].Name))
                {
                    columnInfo.DbName = colatts[0].Name;
                }
                else
                {
                    columnInfo.DbName = item.Name;
                }

                // 主键
                var keyatts = (KeyAttribute[])item.GetCustomAttributes(typeof(KeyAttribute), false);
                if (keyatts.Count() > 0)
                {
                    columnInfo.IsKey = true;
                }
                else
                {
                    columnInfo.IsKey = false;
                }

                // 列名
                columnInfo.ColumnName = item.Name;

                // 数据类型
                columnInfo.DbType = GetOracleDbType(item.PropertyType);

                // 当前值
                if (objectEntry.State != EntityState.Deleted)
                {
                    var i    = 0;
                    var name = objectEntry.EntitySet.ElementType.FullName;
                    if (EntityOrdinal.ContainsKey(name))
                    {
                        if (!EntityOrdinal[name].ContainsKey(item.Name))
                        {
                            i = objectEntry.CurrentValues.GetOrdinal(item.Name);

                            EntityOrdinal[name].Add(item.Name, i);
                        }
                        else
                        {
                            i = EntityOrdinal[name][item.Name];
                        }
                    }
                    else
                    {
                        i = objectEntry.CurrentValues.GetOrdinal(item.Name);

                        var ko = new Dictionary <string, int>();
                        ko.Add(item.Name, i);

                        EntityOrdinal.Add(name, ko);
                    }

                    if (currentValues == null)
                    {
                        currentValues = new object[objectEntry.CurrentValues.FieldCount];
                        objectEntry.CurrentValues.GetValues(currentValues);
                    }

                    columnInfo.CurrentValue = currentValues[i];
                }

                // 原始值
                if (objectEntry.State != EntityState.Added)
                {
                    var i    = 0;
                    var name = objectEntry.EntitySet.ElementType.FullName;
                    if (EntityOrdinal.ContainsKey(name))
                    {
                        if (!EntityOrdinal[name].ContainsKey(item.Name))
                        {
                            i = objectEntry.OriginalValues.GetOrdinal(item.Name);
                            EntityOrdinal[name].Add(item.Name, i);
                        }
                        else
                        {
                            i = EntityOrdinal[name][item.Name];
                        }
                    }
                    else
                    {
                        i = objectEntry.OriginalValues.GetOrdinal(item.Name);

                        var ko = new Dictionary <string, int>();
                        ko.Add(item.Name, i);

                        EntityOrdinal.Add(name, ko);
                    }

                    if (originalValues == null)
                    {
                        originalValues = new object[objectEntry.OriginalValues.FieldCount];
                        objectEntry.OriginalValues.GetValues(originalValues);
                    }

                    columnInfo.OriginalValue = originalValues[i];
                }

                // 值是否被修改
                if (objectEntry.State == EntityState.Modified)
                {
                    if (changeColumns.Contains(columnInfo.ColumnName))
                    {
                        columnInfo.IsChanged = true;
                    }
                    else
                    {
                        columnInfo.IsChanged = false;
                    }
                }

                columnList.Add(columnInfo);
            }
            return(columnList);
        }