internal void RegisterKeyValueForAddedEntity(IEntityStateEntry addedEntry)
        {
            EntityKey entityKey = addedEntry.EntityKey;
            ReadOnlyMetadataCollection <EdmMember> keyMembers = addedEntry.EntitySet.ElementType.KeyMembers;
            CurrentValueRecord currentValues = addedEntry.CurrentValues;

            object[] compositeKeyValues = new object[keyMembers.Count];
            bool     flag  = false;
            int      index = 0;

            for (int count = keyMembers.Count; index < count; ++index)
            {
                int ordinal = currentValues.GetOrdinal(keyMembers[index].Name);
                if (currentValues.IsDBNull(ordinal))
                {
                    flag = true;
                    break;
                }
                compositeKeyValues[index] = currentValues.GetValue(ordinal);
            }
            if (flag)
            {
                return;
            }
            EntityKey key = compositeKeyValues.Length == 1 ? new EntityKey(addedEntry.EntitySet, compositeKeyValues[0]) : new EntityKey(addedEntry.EntitySet, compositeKeyValues);

            if (this._valueKeyToTempKey.ContainsKey(key))
            {
                this._valueKeyToTempKey[key] = (EntityKey)null;
            }
            else
            {
                this._valueKeyToTempKey.Add(key, entityKey);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Checks to see if the specified <see cref="EntityObject"/> has modified properties.
        /// If all properties have the same values, set the state to Unchanged.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entity">The entity.</param>
        public static void CheckIfModified(this ObjectContext context, EntityObject entity)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.EntityState == EntityState.Modified)
            {
                ObjectStateEntry   state          = context.ObjectStateManager.GetObjectStateEntry(entity);
                DbDataRecord       originalValues = state.OriginalValues;
                CurrentValueRecord currentValues  = state.CurrentValues;

                for (int i = 0; i < originalValues.FieldCount; i++)
                {
                    object original = originalValues.GetValue(i);
                    object current  = currentValues.GetValue(i);
                    if (!original.Equals(current))// && (!(original is byte[]) || !((byte[])original).SequenceEqual((byte[])current)))
                    {
                        // Something has actually changed.  We can return now.
                        return;
                    }
                }

                // We made it through the loop without finding any changed properties
                state.ChangeState(EntityState.Unchanged);
            }
        }
        public override void Hook(IIdentifiable entity, HookEntityMetadata metadata)
        {
            //// Check is auditable context, contains auditlog table
            IAuditableContext context = metadata.CurrentContext as IAuditableContext;

            if (context == null)
            {
                return;
            }

            //// Get current username
            var userName = "******";

            if (this.HttpContext != null)
            {
                userName = this.HttpContext.User.Identity.Name;
            }

            //// Get entry, entity type and associate etadata
            var entry      = ((IObjectContextAdapter)metadata.CurrentContext).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);
            var entityType = entity.GetType();

            TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(entityType), entityType);

            //// Get is entity modified property contains requireAudit Field, and add auditlog
            var properties = TypeDescriptor.GetProperties(entityType);

            foreach (string propertyName in entry.GetModifiedProperties())
            {
                //// Check is property need io
                var propertyDescriptor = properties.Find(propertyName, true);
                var propRequireAudit   = propertyDescriptor.Attributes.OfType <RequireAuditAttribute>().FirstOrDefault();
                if (propRequireAudit == null)
                {
                    continue;
                }

                //// Get original value
                DbDataRecord original = entry.OriginalValues;
                string       oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();

                //// Get new value
                CurrentValueRecord current  = entry.CurrentValues;
                string             newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();

                //// Write Audit Log
                AuditLog auditLog = new AuditLog();
                auditLog.IdentifyKey  = entity.IdentifyKey;
                auditLog.IdentifyName = entityType.Name;
                auditLog.OriginValue  = oldValue;
                auditLog.NewValue     = newValue;
                auditLog.CreatedAt    = DateTime.Now;
                auditLog.CreatedBy    = userName;

                context.AuditLogs.Add(auditLog);
            }
        }
        private void SetAddedProperties(ObjectStateEntry entry, StringBuilder newData)
        {
            CurrentValueRecord currentValues = entry.CurrentValues;

            for (int i = 0; i < currentValues.FieldCount; i++)
            {
                newData.AppendFormat("{0}={1} || ", currentValues.GetName(i), currentValues.GetValue(i));
            }
        }
Esempio n. 5
0
        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            //EntityState.Added
            foreach (var entry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Added))
            {
                string NewEmplNo, NewEmplName;
                NewEmplNo   = ((Transfer)(entry.Entity)).TransferID;
                NewEmplName = ((Transfer)(entry.Entity)).Description;
                listBox1.Items.Add(String.Format(
                                       "員工代碼{0}為Added,目前的員工名稱:{1} ",
                                       NewEmplNo, NewEmplName));
            }

            //EntityState.Modified
            foreach (var entry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Modified))
            {
                string NewEmplName, OldEmplName, OrginalEmplNo;
                //取得員工名稱目前值
                CurrentValueRecord curr = entry.CurrentValues;
                NewEmplName = (string)(curr.GetValue(curr.GetOrdinal("Description")));
                //取得員工名稱原來值
                OriginalValueRecord org = entry.GetUpdatableOriginalValues();
                OldEmplName   = (string)(org.GetValue(org.GetOrdinal("Description")));
                OrginalEmplNo = ((Transfer)(entry.Entity)).TransferID;
                listBox1.Items.Add(String.Format("員工代碼{0}為Modified, " +
                                                 "目前的員工名稱:{1},原來的員工名稱:{2} ",
                                                 OrginalEmplNo, NewEmplName, OldEmplName));
            }

            //EntityState.Deleted
            foreach (var entry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Deleted))
            {
                string OldEmplNo, OldEmplName;
                OldEmplNo   = ((Transfer)(entry.Entity)).TransferID;
                OldEmplName = ((Transfer)(entry.Entity)).Description;
                listBox1.Items.Add(String.Format("員工代碼{0}為Deleted, " +
                                                 "原來的員工名稱:{1} ", OldEmplNo, OldEmplName));
            }

            //EntityState.Unchanged
            foreach (var entry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Unchanged))
            {
                string currEmplNo, currEmplName;
                currEmplNo   = ((Transfer)(entry.Entity)).TransferID;
                currEmplName = ((Transfer)(entry.Entity)).Description;
                listBox1.Items.Add(String.Format("員工代碼{0}為Unchanged, " +
                                                 "目前的員工名稱:{1} ", currEmplNo, currEmplName));
            }
        }
Esempio n. 6
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;
        }
Esempio n. 7
0
        private void context_SavingChanges(Object sender, EventArgs e)
        {
            string NewProductID, OldProductID;
            int    NewQuantity, OldQuantity;

            //取得所有新增的存貨異動單明細
            foreach (var AddedEntry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Added))
            {
                if (!AddedEntry.IsRelationship)
                {
                    if (AddedEntry.Entity is TransferDetails)
                    {
                        NewProductID = ((TransferDetails)(AddedEntry.Entity)).ProductID;
                        //判斷異動別
                        if (transferTypeTextBox.Text == "1")
                        {
                            //異動別=入庫,要更新庫存量
                            XIN.IncStock(context, NewProductID,
                                         ((TransferDetails)(AddedEntry.Entity)).Quantity);
                        }
                        else
                        {
                            //異動別=出庫,要更新庫存量
                            XIN.DecStock(context, NewProductID,
                                         ((TransferDetails)(AddedEntry.Entity)).Quantity);
                        }
                    }
                }
            }
            //取得所有修改的存貨異動單明細
            foreach (var ModifiedEntry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Modified))
            {
                if (!ModifiedEntry.IsRelationship)
                {
                    if (ModifiedEntry.Entity is TransferDetails)
                    {
                        //取得目前的商品編號與數量
                        CurrentValueRecord curr = ModifiedEntry.CurrentValues;
                        NewProductID = (string)(curr.GetValue(
                                                    curr.GetOrdinal("ProductID")));
                        NewQuantity = (int)
                                      (curr.GetValue(curr.GetOrdinal("Quantity")));
                        //取得原來的商品編號與數量
                        OriginalValueRecord org =
                            ModifiedEntry.GetUpdatableOriginalValues();
                        OldProductID = (string)
                                       (org.GetValue(curr.GetOrdinal("ProductID")));
                        OldQuantity = (int)(org.GetValue(curr.GetOrdinal("Quantity")));
                        //判斷異動別
                        if (transferTypeTextBox.Text == "1")
                        {
                            //異動別=入庫
                            //增加目前的商品編號的庫存量
                            XIN.IncStock(context, NewProductID, NewQuantity);
                            //減少原來的商品編號的庫存量
                            XIN.DecStock(context, OldProductID, OldQuantity);
                        }
                        else
                        {
                            //異動別=出庫
                            //增加原來的商品編號的庫存量
                            XIN.IncStock(context, OldProductID, OldQuantity);
                            //減少目前的商品編號的庫存量
                            XIN.DecStock(context, NewProductID, NewQuantity);
                        }
                    }
                }
            }
            //取得所有刪除的存貨異動單明細
            foreach (var DeletedEntry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Deleted))
            {
                if (!DeletedEntry.IsRelationship)
                {
                    if (DeletedEntry.Entity is TransferDetails)
                    {
                        OldProductID = ((TransferDetails)
                                        (DeletedEntry.Entity)).ProductID;
                        //判斷異動別
                        if (DeleteTransferType == "1")
                        {
                            //異動別=入庫,更新庫存量
                            XIN.DecStock(context, OldProductID,
                                         ((TransferDetails)(DeletedEntry.Entity)).Quantity);
                        }
                        else
                        {
                            //異動別=出庫,更新庫存量
                            XIN.IncStock(context, OldProductID,
                                         ((TransferDetails)(DeletedEntry.Entity)).Quantity);
                        }
                    }
                }
            }
        }
Esempio n. 8
0
        private void context_SavingChanges(Object sender, EventArgs e)
        {
            string NewProductID, OldProductID;
            int    NewQuantity, OldQuantity;

            //取得所有新增的出貨單明細
            foreach (var AddedEntry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Added))
            {
                if (!AddedEntry.IsRelationship)
                {
                    if (AddedEntry.Entity is DeliveryDetails)
                    {
                        NewProductID = ((DeliveryDetails)(AddedEntry.Entity)).ProductID;
                        //判斷出貨別
                        if (deliveryTypeTextBox.Text == "1")
                        {
                            //出貨別=出貨,要更新庫存量與更新商品的最近出貨日
                            //更新庫存量
                            XIN.DecStock(context, NewProductID,
                                         ((DeliveryDetails)(AddedEntry.Entity)).Quantity);
                            //更新商品的最近出貨日
                            var qry = (from P in context.Product
                                       where P.ProductID == NewProductID
                                       select P).FirstOrDefault();
                            qry.LastDeliveryDate = Convert.ToDateTime(
                                deliveryDateTextBox.Text);
                        }
                        else
                        {
                            //出貨別=出貨退回,只要更新庫存量
                            XIN.IncStock(context, NewProductID,
                                         ((DeliveryDetails)(AddedEntry.Entity)).Quantity);
                        }
                    }
                }
            }
            //取得所有修改的出貨單明細
            foreach (var ModifiedEntry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Modified))
            {
                if (!ModifiedEntry.IsRelationship)
                {
                    if (ModifiedEntry.Entity is DeliveryDetails)
                    {
                        //取得目前的商品編號與數量
                        CurrentValueRecord curr = ModifiedEntry.CurrentValues;
                        NewProductID = (string)(curr.GetValue(
                                                    curr.GetOrdinal("ProductID")));
                        NewQuantity = (int)
                                      (curr.GetValue(curr.GetOrdinal("Quantity")));
                        //取得原來的商品編號與數量
                        OriginalValueRecord org =
                            ModifiedEntry.GetUpdatableOriginalValues();
                        OldProductID = (string)
                                       (org.GetValue(curr.GetOrdinal("ProductID")));
                        OldQuantity = (int)(org.GetValue(curr.GetOrdinal("Quantity")));
                        //判斷出貨別
                        if (deliveryTypeTextBox.Text == "1")
                        {
                            //出貨別=出貨,要更新庫存量與更新商品的最近出貨日
                            //增加原來的商品編號的庫存量
                            XIN.IncStock(context, OldProductID, OldQuantity);
                            //減少目前的商品編號的庫存量
                            XIN.DecStock(context, NewProductID, NewQuantity);
                            //更新商品的最近出貨日
                            var qry = (from P in context.Product
                                       where P.ProductID == NewProductID
                                       select P).FirstOrDefault();
                            qry.LastDeliveryDate = Convert.ToDateTime(
                                deliveryDateTextBox.Text);
                        }
                        else
                        {
                            //出貨別=出貨退回,只要更新庫存量
                            //增加目前的商品編號的庫存量
                            XIN.IncStock(context, NewProductID, NewQuantity);
                            //減少原來的商品編號的庫存量
                            XIN.DecStock(context, OldProductID, OldQuantity);
                        }
                    }
                }
            }
            //取得所有刪除的出貨單明細
            foreach (var DeletedEntry in context.ObjectStateManager
                     .GetObjectStateEntries(EntityState.Deleted))
            {
                if (!DeletedEntry.IsRelationship)
                {
                    if (DeletedEntry.Entity is DeliveryDetails)
                    {
                        OldProductID = ((DeliveryDetails)
                                        (DeletedEntry.Entity)).ProductID;
                        //判斷出貨別
                        if (DeleteDeliveryType == "1")
                        {
                            //出貨別=出貨,要更新庫存量
                            //更新庫存量
                            XIN.IncStock(context, OldProductID,
                                         ((DeliveryDetails)(DeletedEntry.Entity)).Quantity);
                        }
                        else
                        {
                            //出貨別=出貨退回,只要更新庫存量
                            XIN.DecStock(context, OldProductID,
                                         ((DeliveryDetails)(DeletedEntry.Entity)).Quantity);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        public override int SaveChanges()
        {
            //int result = -1;
            DateTime eventDateTime = DateTime.Now;
            //string eventUser = HttpContext.Current.User.Identity.Name;
            User   u         = GetUserByLoginName(HttpContext.Current.User.Identity.Name.Split('\\').Last(), false);
            string eventUser = u.DisplayName;

            ChangeTracker.DetectChanges(); // Important!

            ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;

            List <ObjectStateEntry> objectStateEntryList =
                ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added
                                                             | EntityState.Modified
                                                             | EntityState.Deleted)
                .ToList();


            foreach (ObjectStateEntry entry in objectStateEntryList)
            {
                AuditEvent auditRecord = new AuditEvent();
                auditRecord.EventDate = DateTime.Now;
                auditRecord.UserID    = eventUser;
                if (entry.Entity == null)
                {
                    continue;
                }
                string   objModel = entry.Entity.ToString();
                string[] objArray = objModel.Split('.');
                string   objType  = objArray.Last();;
                if (objType.Contains("_"))
                {
                    objType = objType.Substring(0, objType.IndexOf('_'));
                    var testAuditType = this.AuditDescriptions.Where(a => a.AuditDescription.StartsWith(objType));
                    if (testAuditType.Count() == 0)
                    {
                        objType = entry.EntitySet.ToString();
                    }
                    else
                    {
                        string newObjType = testAuditType.First().AuditDescription.ToString();
                        int    spaceLoc   = newObjType.IndexOf(' ');
                        if (spaceLoc > 0)
                        {
                            objType = newObjType.Substring(0, spaceLoc);
                        }
                    }
                }
                if (!entry.IsRelationship && !objType.StartsWith("Audit") && objType != "EdmMetadata")
                {
                    switch (entry.State)
                    {
                    case EntityState.Added:
                    {
                        //result = base.SaveChanges();
                        string objName   = string.Format("{0} Added", objType);
                        int    AuditType = this.AuditDescriptions.Where(a => a.AuditDescription.ToLower() == objName.ToLower()).Take(1).Single().idAuditEventDescription;
                        auditRecord.EventDescription        = objName;
                        auditRecord.idAuditEventDescription = AuditType;
                        auditRecord.RecordChanged           = entry.CurrentValues.GetValue(0).ToString();
                        try
                        {
                            int    ord   = entry.CurrentValues.GetOrdinal("tipstaffRecordID");
                            string value = entry.CurrentValues.GetValue(ord).ToString();
                            auditRecord.RecordAddedTo = Int32.Parse(value);
                        }
                        catch
                        {
                            try
                            {
                                int    ord   = entry.CurrentValues.GetOrdinal("warrantID");
                                string value = entry.CurrentValues.GetValue(ord).ToString();
                                auditRecord.RecordAddedTo = Int32.Parse(value);
                            }
                            catch
                            {
                                try
                                {
                                    int    ord   = entry.CurrentValues.GetOrdinal("childAbductionID");
                                    string value = entry.CurrentValues.GetValue(ord).ToString();
                                    auditRecord.RecordAddedTo = Int32.Parse(value);
                                }
                                catch
                                {
                                    auditRecord.RecordAddedTo = null;
                                }
                            }
                        }
                        break;
                    }

                    case EntityState.Deleted:
                    {
                        string objName   = string.Format("{0} Deleted", objType);
                        int    AuditType = this.AuditDescriptions.Where(a => a.AuditDescription.ToLower() == objName.ToLower()).Take(1).Single().idAuditEventDescription;
                        auditRecord.EventDescription        = objName;
                        auditRecord.idAuditEventDescription = AuditType;
                        auditRecord.RecordChanged           = entry.OriginalValues.GetValue(0).ToString();
                        try
                        {
                            int    ord   = entry.OriginalValues.GetOrdinal("tipstaffRecordID");
                            string value = entry.OriginalValues.GetValue(ord).ToString();
                            auditRecord.RecordAddedTo = Int32.Parse(value);
                        }
                        catch
                        {
                            try
                            {
                                int    ord   = entry.OriginalValues.GetOrdinal("warrantID");
                                string value = entry.OriginalValues.GetValue(ord).ToString();
                                auditRecord.RecordAddedTo = Int32.Parse(value);
                            }
                            catch
                            {
                                try
                                {
                                    int    ord   = entry.OriginalValues.GetOrdinal("childAbductionID");
                                    string value = entry.OriginalValues.GetValue(ord).ToString();
                                    auditRecord.RecordAddedTo = Int32.Parse(value);
                                }
                                catch
                                {
                                    auditRecord.RecordAddedTo = null;
                                }
                            }
                        }
                        // Iterate over the members (i.e. properties (including complex properties), references, collections) of the entity type
                        List <AuditEventDataRow> data = new List <AuditEventDataRow>();
                        foreach (EdmMember member in entry.EntitySet.ElementType.Members)
                        {
                            string           propertyName = member.Name.ToString();
                            DbPropertyValues oldData      = this.Entry(entry.Entity).GetDatabaseValues();
                            string           oldValue     = "";
                            string           newValue     = "deleted";
                            try
                            {
                                oldValue = (oldData.GetValue <object>(propertyName) != null) ? oldData.GetValue <object>(propertyName).ToString() : "Empty";
                                if (oldValue == "")
                                {
                                    oldValue = "Empty";
                                }
                            }
                            catch
                            { oldValue = "Could not be mapped"; }

                            if ((oldValue != newValue) && (oldValue != "Could not be mapped"))         // probably not necessary
                            {
                                AuditEventDataRow newAuditRow = new AuditEventDataRow();
                                newAuditRow.ColumnName = propertyName;
                                newAuditRow.Was        = oldValue.Length <= 199 ? oldValue : oldValue.Substring(0, 199);
                                newAuditRow.Now        = newValue.Length <= 199 ? newValue : newValue.Substring(0, 199);
                                data.Add(newAuditRow);
                            }
                        }
                        if (data.Count() > 0)
                        {
                            auditRecord.AuditEventDataRows = data;
                        }
                        break;
                    }

                    case EntityState.Modified:
                    {
                        string objName   = string.Format("{0} Amended", objType);
                        int    AuditType = this.AuditDescriptions.Where(a => a.AuditDescription.ToLower() == objName.ToLower()).Take(1).Single().idAuditEventDescription;
                        auditRecord.EventDescription        = objName;
                        auditRecord.idAuditEventDescription = AuditType;
                        auditRecord.RecordChanged           = entry.CurrentValues.GetValue(0).ToString();
                        List <AuditEventDataRow> data = new List <AuditEventDataRow>();
                        foreach (string propertyName in entry.GetModifiedProperties())
                        {
                            DbPropertyValues oldData  = this.Entry(entry.Entity).GetDatabaseValues();
                            string           oldValue = (oldData.GetValue <object>(propertyName) != null) ? oldData.GetValue <object>(propertyName).ToString() : "Empty";
                            if (oldValue == "")
                            {
                                oldValue = "Empty";
                            }

                            CurrentValueRecord current  = entry.CurrentValues;
                            string             newValue = (current.GetValue(current.GetOrdinal(propertyName)) != null) ? current.GetValue(current.GetOrdinal(propertyName)).ToString() : "Empty";
                            if (newValue == "")
                            {
                                newValue = "Empty";
                            }

                            if (objType == "Template" && propertyName == "templateXML")
                            {
                                oldValue = "XML";
                                newValue = "XML - Too long to record new version";
                            }

                            if (oldValue != newValue)         // probably not necessary
                            {
                                AuditEventDataRow newAuditRow = new AuditEventDataRow();
                                newAuditRow.ColumnName = propertyName;
                                newAuditRow.Was        = oldValue.Length <= 199 ? oldValue : oldValue.Substring(0, 199);
                                newAuditRow.Now        = newValue.Length <= 199 ? newValue : newValue.Substring(0, 199);
                                data.Add(newAuditRow);
                            }
                        }
                        if (data.Count() > 0)
                        {
                            auditRecord.AuditEventDataRows = data;
                        }
                        break;
                    }
                    }
                }

                if (auditRecord.RecordChanged == "0" && auditRecord.RecordAddedTo == 0 && auditRecord.EventDescription.Contains("Added"))
                {
                    //New TipstaffRecord derivative record added, so...
                    //save the record
                    base.SaveChanges();
                    //extract the new identity
                    auditRecord.RecordChanged = entry.CurrentValues.GetValue(0).ToString();
                    //update the audit event
                    this.AuditEvents.Add(auditRecord);
                    //and savechanges at the end of the code block
                }
                else if (auditRecord.RecordChanged == "0" && auditRecord.RecordAddedTo != 0 && auditRecord.EventDescription.Contains("Added"))
                {
                    //New record added, so...
                    //save the record
                    base.SaveChanges();
                    //extract the new identity
                    auditRecord.RecordChanged = entry.CurrentValues.GetValue(0).ToString();
                    //update the audit event
                    this.AuditEvents.Add(auditRecord);
                    //and savechanges at the end of the code block
                }
                else if (auditRecord.RecordChanged != "0" && auditRecord.RecordChanged != null && (auditRecord.AuditEventDataRows != null && auditRecord.AuditEventDataRows.Count > 0))
                {
                    this.AuditEvents.Add(auditRecord);
                    //base.SaveChanges();
                }
                try
                {
                    //base.SaveChanges();
                    //only uncomment for error handling
                }
                catch (DbEntityValidationException ex)
                {
                    System.Diagnostics.Debug.Print(ex.Message);
                }
                catch (DbUpdateException ex)
                {
                    System.Diagnostics.Debug.Print(ex.Message);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Print(ex.Message);
                }
            }
            return(base.SaveChanges());
        }
Esempio n. 10
0
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges(); // Important!

            ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;

            List <ObjectStateEntry> objectStateEntryList =
                ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added
                                                             | EntityState.Modified
                                                             | EntityState.Deleted)
                .ToList();

            foreach (ObjectStateEntry entry in objectStateEntryList)
            {
                if (!entry.IsRelationship)
                {
                    switch (entry.State)
                    {
                    case EntityState.Added:
                        // write log...
                        break;

                    case EntityState.Deleted:
                        // write log...
                        break;

                    case EntityState.Modified:
                    {
                        if (ObjectContext.GetObjectType(entry.Entity.GetType()) == typeof(DeviceParameter))
                        {
                            DbDataRecord original = entry.OriginalValues;
                            string       oldValue = original.GetValue(
                                original.GetOrdinal("Value"))
                                                    .ToString();

                            CurrentValueRecord current  = entry.CurrentValues;
                            string             newValue = current.GetValue(
                                current.GetOrdinal("Value"))
                                                          .ToString();

                            if (oldValue != newValue)     // probably not necessary
                            {
                                ParameterChangeHistory hist = new ParameterChangeHistory();
                                hist.Date     = DateTime.Now;
                                hist.Property = (DeviceParameter)(object)entry.Entity;
                                hist.Value    = newValue;
                                this.ParameterChanges.Add(hist);
                            }

                            if (this.ParamUpdateEvent != null)
                            {
                                Task.Factory.StartNew(() => this.ParamUpdateEvent((DeviceParameter)entry.Entity));
                            }
                        }
                        else if (ObjectContext.GetObjectType(entry.Entity.GetType()) == typeof(DeviceActionResult))
                        {
                            DbDataRecord original = entry.OriginalValues;
                            string       oldValue = original.GetValue(
                                original.GetOrdinal("Value"))
                                                    .ToString();

                            CurrentValueRecord current  = entry.CurrentValues;
                            string             newValue = current.GetValue(
                                current.GetOrdinal("Value"))
                                                          .ToString();

                            if (oldValue != newValue)     // probably not necessary
                            {
                                ActionChangeHistory hist = new ActionChangeHistory();
                                hist.Date     = DateTime.Now;
                                hist.Property = (DeviceActionResult)(object)entry.Entity;
                                hist.Value    = newValue;
                                this.ActionChangeHistory.Add(hist);
                            }

                            if (this.ActionUpdateEvent != null)
                            {
                                Task.Factory.StartNew(() => this.ActionUpdateEvent((DeviceActionResult)entry.Entity));
                            }
                        }
                        else if (ObjectContext.GetObjectType(entry.Entity.GetType()) == typeof(Device))
                        {
                            Task.Factory.StartNew(() => this.DeviceUpdateEvent((Device)entry.Entity));
                        }
                        break;
                    }
                    }
                }
            }
            return(base.SaveChanges());
        }