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());
        }
예제 #2
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();
        }
예제 #3
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);
                }
            }
        }