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);
            }
        }
        public static void ResetProperties(
            this ObjectContext oc,
            object targetObject)
        {
            EntityType entityType = oc.MetadataWorkspace.GetItem <EntityType>(
                targetObject.GetType().FullName,
                DataSpace.CSpace);

            ObjectStateEntry objectStateEntry = oc
                                                .ObjectStateManager
                                                .GetObjectStateEntry(targetObject);

            CurrentValueRecord currentValues = objectStateEntry.CurrentValues;

            object dummy = Activator.CreateInstance(targetObject.GetType());

            foreach (EdmProperty p in entityType.Properties.Where(x => x.IsPrimitiveType || x.IsComplexType))
            {
                bool isKey = entityType.KeyProperties.Any(x => x.Name == p.Name);

                if (!isKey)
                {
                    object v = ReflectionHelper.GetProperty(dummy, p.Name);
                    int    propertyOrdinal = currentValues.GetOrdinal(p.Name);
                    currentValues.SetValue(propertyOrdinal, v);
                }
            }
        }
        public override int SaveChanges()
        {
            ObjectContext context = ((IObjectContextAdapter)this).ObjectContext;

            foreach (ObjectStateEntry entry in
                     (context.ObjectStateManager
                      .GetObjectStateEntries(EntityState.Added | EntityState.Modified)))
            {
                if (!entry.IsRelationship)
                {
                    CurrentValueRecord entryValues = entry.CurrentValues;
                    if (entryValues.GetOrdinal("ModifiedBy") > 0)
                    {
                        HttpContext currentContext = HttpContext.Current;
                        string      userId         = "nazrul";
                        DateTime    now            = DateTime.Now;

                        if (currContext.User.Identity.IsAuthenticated)
                        {
                            if (currentContext.Session["userId"] != null)
                            {
                                userId = (string)currentContext.Session["userId"];
                            }
                            else
                            {
                                userId = UserAuthentication.GetUserId(currentContext.User.Identity.UserCode);
                            }
                        }

                        if (entry.State == EntityState.Modified)
                        {
                            entryValues.SetString(entryValues.GetOrdinal("ModifiedBy"), userId);
                            entryValues.SetDateTime(entryValues.GetOrdinal("ModifiedDate"), now);
                        }

                        if (entry.State == EntityState.Added)
                        {
                            entryValues.SetString(entryValues.GetOrdinal("CreatedBy"), userId);
                            entryValues.SetDateTime(entryValues.GetOrdinal("CreatedDate"), now);
                        }
                    }
                }
            }

            return(base.SaveChanges());
        }
예제 #4
0
        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);
            }
        }
예제 #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));
            }
        }
        public static void SetValue(
            this ObjectContext oc,
            object target,
            string propertyName,
            object propertyValue)
        {
            ObjectStateEntry objectStateEntry = oc
                                                .ObjectStateManager
                                                .GetObjectStateEntry(target);

            CurrentValueRecord currentValues = objectStateEntry.CurrentValues;
            int propertyOrdinal = currentValues.GetOrdinal(propertyName);

            currentValues.SetValue(propertyOrdinal, propertyValue);
        }
예제 #7
0
        public new void SaveChanges()
        {
            //For audit fields
            ObjectContext context = ((IObjectContextAdapter)this).ObjectContext;
            //Find all Entities that are Added/Modified that inherit from my EntityBase
            IEnumerable <ObjectStateEntry> objectStateEntries =
                from e in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                where
                e.IsRelationship == false &&
                e.Entity != null
                select e;

            var currentTime = DateTime.Now;

            foreach (var entry in objectStateEntries)
            {
                var entityBase = entry.Entity;
                CurrentValueRecord entryValues = entry.CurrentValues;

                //Only do if the entities have the audit columns (to be on the safer side)
                int ordinalValue = 0;
                try
                {
                    ordinalValue = entryValues.GetOrdinal("CreatedDate");
                }
                catch (Exception)
                {
                    ordinalValue = 0;
                }
                if (ordinalValue > 0)
                {
                    //Getting the user ID
                    string userID = "9999"; // string.Empty;
                                            //try
                                            //{
                                            //	userID = HelperService.ContextObject.UserID.ToString();
                                            //}
                                            //catch (Exception)
                                            //{

                    //	userID = "9999";
                    //}
                    //string userID = Convert.ToString(HelperService.ContextObject.UserID);
                    //string userID = HelperService.ContextObject.UserID.ToString();
                    //Irrespective of update or insert always the updated columns are updated
                    //To be doubly sure, put try catch
                    try
                    {
                        entryValues.SetDateTime(entryValues.GetOrdinal("UpdatedDate"), DateTime.Now);
                        entryValues.SetString(entryValues.GetOrdinal("UpdatedBy"), userID);
                        //If insert, update the other two audit columns as well
                        if (entry.State == EntityState.Added)
                        {
                            entryValues.SetDateTime(entryValues.GetOrdinal("CreatedDate"), DateTime.Now);
                            entryValues.SetString(entryValues.GetOrdinal("CreatedBy"), userID);
                        }
                        // as there is no deletion so we assume that entity state can only be modified -- siddharth (as discussed with brahma on 24th Jan 2014)
                        else
                        {
                            var dbValueOfEntity = this.Entry(entry.Entity).GetDatabaseValues();
                            //var createdDate = this.Entry(entry.Entity).GetDatabaseValues().GetValue<DateTime?>("CreatedDate");
                            var createdDate = dbValueOfEntity.GetValue <DateTime?>("CreatedDate");
                            var createdBy   = dbValueOfEntity.GetValue <string>("CreatedBy");
                            if (createdDate != null)
                            {
                                entryValues.SetDateTime(entryValues.GetOrdinal("CreatedDate"), createdDate.Value);
                            }
                            if (createdBy != null)
                            {
                                var createdByOrdinal = entryValues.GetOrdinal("CreatedBy");
                                //if (createdByOrdinal.GetType() == typeof(string))
                                //{
                                // entryValues.SetString(createdByOrdinal, createdBy);
                                //}
                                //else // the value createdby is of integer type
                                //{
                                // entryValues.SetInt32(createdByOrdinal, Convert.ToInt32(createdBy));
                                //}
                                entryValues.SetString(createdByOrdinal, createdBy);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //Do nothing
                    }
                }
            }
            //End audit fields
            base.SaveChanges();
        }
예제 #8
0
        private static void context_SavingChanges(object sender, EventArgs e)
        {
            // Find any new or modified entities using our user/timestampting
            // fields and update them accordingly.
            foreach (ObjectStateEntry entry in
                     ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries
                         (EntityState.Added | EntityState.Modified))
            {
                // Only work with entities that have our user/timestamp records in them.
                try
                {
                    if (!entry.IsRelationship)
                    {
                        CurrentValueRecord entryValues = entry.CurrentValues;
                        System.Collections.Specialized.NameValueCollection updateField = CheckEntityUpdateField(entry.CurrentValues);

                        HttpContext currContext = HttpContext.Current;
                        int         userId      = -1;
                        DateTime    now         = DateTime.Now;

                        if (currContext != null)
                        {
                            if (currContext.User.Identity.IsAuthenticated)
                            {
                                if (currContext.Session != null && currContext.Session["userId"] != null)
                                {
                                    userId = (int)currContext.Session["userId"];
                                }
                                else
                                {
                                    //userId = Security.GetUserId(currContext.User.Identity.Name);
                                }
                            }
                        }

                        if (entry.State == EntityState.Modified)
                        {
                            if (updateField["updater_id"] == "true")
                            {
                                entryValues.SetInt32(entryValues.GetOrdinal("updater_id"), userId);
                            }

                            if (updateField["updated_at"] == "true")
                            {
                                entryValues.SetDateTime(entryValues.GetOrdinal("updated_at"), now);
                            }
                        }

                        if (entry.State == EntityState.Added)
                        {
                            // If creator/updater values have not already been set,
                            // default them to the current user/time. We will already have
                            // creator/updater for version records.

                            for (int x = 0; x < updateField.Count; x++)
                            {
                                string key = updateField.Keys[x];
                                if (key.Contains("_id") && updateField[x] == "true")
                                {
                                    // Sometimes when a new object is created, the creator_id is defaulted
                                    // to 0. This is invalid for our processing.
                                    if (entryValues.IsDBNull(entryValues.GetOrdinal(key)) ||
                                        entryValues.GetInt32(entryValues.GetOrdinal(key)) == 0
                                        )
                                    {
                                        entryValues.SetInt32(entryValues.GetOrdinal(key), userId);
                                    }
                                }
                                else if (updateField.Keys[x].Contains("_at") && updateField[x] == "true")
                                {
                                    // Sometimes when a new object is created, the year is defaulted to
                                    // 1/1/0001. This is an invalid year or our processing
                                    if (entryValues.IsDBNull(entryValues.GetOrdinal(key)) ||
                                        entryValues.GetDateTime(entryValues.GetOrdinal(key)).Year == 1
                                        )
                                    {
                                        entryValues.SetDateTime(entryValues.GetOrdinal(key), now);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                }
            }
        }
예제 #9
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;
        }
예제 #10
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);
                        }
                    }
                }
            }
        }
예제 #11
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);
                        }
                    }
                }
            }
        }
예제 #12
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());
        }
예제 #13
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());
        }