예제 #1
0
        private static IEnumerable<AuditLog> GetAuditLogs(DbEntityEntry entityEntry, string userName, EntityState entityState, ObjectContext objectContext,
            DateTime auditDateTime)
        {
            var returnValue = new List<AuditLog>();
            var keyRepresentation = BuildKeyRepresentation(entityEntry, KeySeperator, objectContext);

            var auditedPropertyNames = GetDeclaredPropertyNames(entityEntry.Entity.GetType(), objectContext.MetadataWorkspace);
            foreach (var propertyName in auditedPropertyNames)
            {
                var currentValue = Convert.ToString(entityEntry.CurrentValues.GetValue<object>(propertyName));
                var originalValue = Convert.ToString(entityEntry.GetDatabaseValues().GetValue<object>(propertyName));
                if (entityState == EntityState.Modified)
                    if (originalValue == currentValue) //Values are the same, don't log
                        continue;
                returnValue.Add(new AuditLog
                {
                    KeyNames = keyRepresentation.Key,
                    KeyValues = keyRepresentation.Value,
                    OriginalValue = entityState != EntityState.Added
                        ? originalValue
                        : null,
                    NewValue = entityState == EntityState.Modified || entityState == EntityState.Added
                        ? currentValue
                        : null,
                    ColumnName = propertyName,
                    EventDateTime = auditDateTime,
                    EventType = entityState.ToString(),
                    UserName = userName,
                    TableName = entityEntry.Entity.GetType().Name
                });
            }
            return returnValue;
        }
예제 #2
0
        /// <summary>
        /// Gets the entity key deleted.
        /// </summary>
        /// <param name="entry">The entry.</param>
        /// <param name="entitySetName">Name of the entity set.</param>
        /// <returns></returns>
        private string GetEntityKeyDeleted(DbEntityEntry entry, out string entitySetName)
        {
            var keyBuilder = new StringBuilder();
            var keys = entry.Entity.GetType().GetProperties().Where(w => w.GetCustomAttributes(typeof(KeyAttribute), true).Any()).Select(p => p.Name).ToArray();

            entitySetName = ResolveEntitySetName(entry.Entity.GetType());

            foreach (var key in keys)
            {
                var objectVal = entry.Property(key).CurrentValue;

                if (objectVal == null)
                {
                    continue;
                }

                var keyValue = objectVal.ToString();

                if (keyBuilder.Length > 0)
                {
                    keyBuilder.Append(",");
                }

                keyBuilder.Append(keyValue);
            }

            return keyBuilder.ToString();
        }
예제 #3
0
        public DbEntityEntryWrapper(DbEntityEntry entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            EntityEntry = entity;
        }
예제 #4
0
 private static void TrySetVersion(DbEntityEntry entry, Func<int, int> versionSet)
 {
     var v = entry.TryGetProperty("Version");
     if (v != null && v.CurrentValue is int) {
         v.CurrentValue = versionSet((int)v.CurrentValue);
     }
 }
        public static void ValidateEntity(DbContext context, DbEntityEntry entity, Type type)
        {
            if (entity.State == System.Data.EntityState.Modified)
            {
                if (!_parentAttributes.ContainsKey(type))
                {
                    var properties = from attributedProperty in type.GetProperties()
                                     select new
                                     {
                                         attributedProperty,
                                         attributes = attributedProperty.GetCustomAttributes(true)
                                             .Where(attribute => attribute is ParentAttribute)
                                     };
                    properties = properties.Where(p => p.attributes.Any());
                    _parentAttributes.Add(type,
                                          properties.Any()
                                              ? properties.First().attributedProperty.Name
                                              : string.Empty);
                }

                if (!string.IsNullOrEmpty(_parentAttributes[type]))
                {
                    if (entity.Reference(_parentAttributes[type]).CurrentValue == null)
                    {
                        context.Set(type).Remove(entity.Entity);
                    }
                }
            }
        }
예제 #6
0
파일: LogsHelper.cs 프로젝트: nntu/QLLoiWeb
        public static string GetRecordsForChange(DbEntityEntry dbEntry)
        {
            var returnvalue = "";
            var changeTime = DateTime.UtcNow;

            switch (dbEntry.State)
            {
                case System.Data.Entity.EntityState.Added:
                    returnvalue = string.Format("Add:{0};Value:{1} ", dbEntry.CurrentValues, dbEntry.OriginalValues);
                    break;

                case System.Data.Entity.EntityState.Modified:
                    foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
                    {
                        // For updates, we only want to capture the columns that actually changed
                        if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName)))
                        {
                            returnvalue += string.Format("Modified:{0};OriginalValue:{1};NewValue:{2}|", propertyName, dbEntry.CurrentValues.GetValue<object>(propertyName), dbEntry.OriginalValues.GetValue<object>(propertyName));
                        }
                    }
                    break;
            }

            return returnvalue;
        }
예제 #7
0
        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
            var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>());

            if (entityEntry.Entity is Application && entityEntry.State == EntityState.Added)
            {
                Application app = entityEntry.Entity as Application;

                if (!app.IsValid)
                {
                    foreach (ValidationError ve in app.GetValidationErrors())
                    {
                        result.ValidationErrors.Add(new DbValidationError(ve.PropertyName, ve.ErrorMessage));
                    }
                }
            }

            if (result.ValidationErrors.Count > 0)
            {
                return result;
            }
            else
            {
                return base.ValidateEntity(entityEntry, items);
            }
        }
예제 #8
0
        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry,
                                                                   IDictionary<object, object> items)
        {
            if (entityEntry.State != EntityState.Added)
            {
                return base.ValidateEntity(entityEntry,
                                           items);
            }

            var user = entityEntry.Entity as User;
            // Check for uniqueness of user name
            if (user == null || !Users.Any(u => String.Equals(u.UserName,
                                                              user.UserName,
                                                              StringComparison.CurrentCultureIgnoreCase)))
            {
                return base.ValidateEntity(entityEntry,
                                           items);
            }

            var result = new DbEntityValidationResult(entityEntry,
                                                      new List<DbValidationError>());
            result.ValidationErrors.Add(new DbValidationError("User",
                                                              "User name must be unique."));
            return result;
        }
예제 #9
0
        public void Remove(DbEntityEntry entry)
        {
            var id = GetId(entry.Entity);

            var existing = Data.FirstOrDefault(x => x.Key.Equals(id));
            Data.Remove(existing);
        }
예제 #10
0
        /// <summary>
        /// <see cref="DbContext.ValidateEntity"/>
        /// </summary>
        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry,
            IDictionary<object, object> items)
        {
            if(entityEntry != null && entityEntry.State == EntityState.Added)
            {
                // Validation for duplicate email
                UserBase user = entityEntry.Entity as UserBase;
                if(user != null)
                {
                    if(Users.Any(u => u.Email.ToUpper() == user.Email.ToUpper()))
                    {
                        return new DbEntityValidationResult(entityEntry, new List<DbValidationError>())
                        {
                            ValidationErrors =
                            {
                                new DbValidationError("User",
                                    string.Format(CultureInfo.CurrentCulture, "Duplicate Email. Email: {0}", user.Email))
                            }
                        };
                    }
                }
            }

            return base.ValidateEntity(entityEntry, items);
        }
예제 #11
0
 private static void HandleSoftDelete(DbEntityEntry entry)
 {
     if (entry.Entity is ISoftDelete)
     {
         entry.State = EntityState.Unchanged;
         entry.Cast<ISoftDelete>().Entity.IsDeleted = true;
     }
 }
예제 #12
0
 /// <summary>
 /// 初始化创建审计信息
 /// </summary>
 private void InitCreationAudited(DbEntityEntry entry)
 {
     if ((entry.Entity is ICreationAudited) == false)
         return;
     var result = entry.Cast<ICreationAudited>().Entity;
     result.CreationTime = DateTime.Now;
     result.CreatorUserId = GetApplicationSession().Name;
 }
예제 #13
0
        protected virtual void AdjustTimestamps(DbEntityEntry<IPersistenceAudit> entity)
        {
            if (entity.State == EntityState.Added)
                entity.Entity.CreatedTimestamp = entity.Entity.ModifiedTimestamp = DateTime.Now;

            if (entity.State == EntityState.Modified)
                entity.Entity.ModifiedTimestamp = DateTime.Now;
        }
예제 #14
0
        protected virtual void AdjustUsers(DbEntityEntry<IPersistenceAudit> entity)
        {
            if (entity.State == EntityState.Added)
                entity.Entity.CreatedBy = entity.Entity.ModifiedBy = CurrentUser.GetCurrentUserName();

            if (entity.State == EntityState.Modified)
                entity.Entity.ModifiedBy = CurrentUser.GetCurrentUserName();
        }
 /// <summary>
 /// Looks at everything that has changed and applies any further action if required.
 /// </summary>
 /// <param name="entityEntry"></param>
 /// <returns></returns>
 private static void UpdateTrackedEntity(DbEntityEntry entityEntry)
 {
     var trackUpdateClass = entityEntry.Entity as IModifiedEntity;
     if (trackUpdateClass == null) return;
     trackUpdateClass.ModifiedDate = DateTime.UtcNow;
     if (entityEntry.State == EntityState.Added)
         trackUpdateClass.rowguid = Guid.NewGuid();
 }
        /// <summary>
        ///     Creates an instance of <see cref = "DbEntityValidationResult" /> class.
        /// </summary>
        /// <param name = "entry">
        ///     Entity entry the results applies to. Never null.
        /// </param>
        /// <param name = "validationErrors">
        ///     List of <see cref = "DbValidationError" /> instances. Never null. Can be empty meaning the entity is valid.
        /// </param>
        public DbEntityValidationResult(DbEntityEntry entry, IEnumerable<DbValidationError> validationErrors)
        {
            Contract.Requires(entry != null);
            Contract.Requires(validationErrors != null);

            _entry = entry.InternalEntry;
            _validationErrors = validationErrors.ToList();
        }
예제 #17
0
 public string GetTypeKey(DbEntityEntry entry)
 {
     var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
     string type = string.Empty;
     if (objectStateEntry.EntityKey.EntityKeyValues != null)
         type = objectStateEntry.EntityKey.EntityKeyValues[0].Value.GetType().ToString();
     return type;
 }
예제 #18
0
        public void OnInsert(DbEntityEntry entityEntry)
        {
            if (entityEntry.Entity is EntityWithCreatedDate)
                entityEntry.Cast<EntityWithCreatedDate>().Entity.Created = DateTime.Now;

            if (entityEntry.Entity is Entity)
                entityEntry.Cast<Entity>().Entity.Modified = DateTime.Now;
        }
        /// <summary>
        /// Creates an instance of <see cref="DbEntityValidationResult" /> class.
        /// </summary>
        /// <param name="entry"> Entity entry the results applies to. Never null. </param>
        /// <param name="validationErrors">
        /// List of <see cref="DbValidationError" /> instances. Never null. Can be empty meaning the entity is valid.
        /// </param>
        public DbEntityValidationResult(DbEntityEntry entry, IEnumerable<DbValidationError> validationErrors)
        {
            Check.NotNull(entry, "entry");
            Check.NotNull(validationErrors, "validationErrors");

            _entry = entry.InternalEntry;
            _validationErrors = validationErrors.ToList();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionRequestChangeTransaction"/> class.
        /// </summary>
        /// <param name="entry">The entry.</param>
        public ConnectionRequestChangeTransaction( DbEntityEntry entry )
        {
            // If entity was a connection request, save the values
            var connectionRequest = entry.Entity as ConnectionRequest;
            if ( connectionRequest != null )
            {
                State = entry.State;

                // If this isn't a deleted connection request, get the connection request guid
                if ( State != EntityState.Deleted )
                {
                    ConnectionRequestGuid = connectionRequest.Guid;
                    PersonId = connectionRequest.PersonAlias != null ? connectionRequest.PersonAlias.PersonId : (int?)null;
                    if ( connectionRequest.ConnectionOpportunity != null )
                    {
                        ConnectionTypeId = connectionRequest.ConnectionOpportunity.ConnectionTypeId;
                    }
                    ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId;
                    ConnectorPersonAliasId = connectionRequest.ConnectorPersonAliasId;
                    ConnectionState = connectionRequest.ConnectionState;
                    ConnectionStatusId = connectionRequest.ConnectionStatusId;
                    AssignedGroupId = connectionRequest.AssignedGroupId;

                    if ( State == EntityState.Modified )
                    {
                        var dbOpportunityIdProperty = entry.Property( "ConnectionOpportunityId" );
                        if ( dbOpportunityIdProperty != null )
                        {
                            PreviousConnectionOpportunityId = dbOpportunityIdProperty.OriginalValue as int?;
                        }

                        var dbConnectorPersonAliasIdProperty = entry.Property( "ConnectorPersonAliasId" );
                        if ( dbConnectorPersonAliasIdProperty != null )
                        {
                            PreviousConnectorPersonAliasId = dbConnectorPersonAliasIdProperty.OriginalValue as int?;
                        }

                        var dbStateProperty = entry.Property( "ConnectionState" );
                        if ( dbStateProperty != null )
                        {
                            PreviousConnectionState = (ConnectionState)dbStateProperty.OriginalValue;
                        }
                        var dbStatusProperty = entry.Property( "ConnectionStatusId" );
                        if ( dbStatusProperty != null )
                        {
                            PreviousConnectionStatusId = (int)dbStatusProperty.OriginalValue;
                        }

                        var dbAssignedGroupIdProperty = entry.Property( "AssignedGroupId" );
                        if ( dbAssignedGroupIdProperty != null )
                        {
                            PreviousAssignedGroupId = dbAssignedGroupIdProperty.OriginalValue as int?;
                        }
                    }
                }
            }
        }
예제 #21
0
 protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
 {
     //Replace "DataClass" with the class that needs to store large data types
     if (entityEntry.Entity is Content)
     {
         return false;
     }
     return base.ShouldValidateEntity(entityEntry);
 }
예제 #22
0
 public void OnInsert(DbEntityEntry entityEntry)
 {
     var item = entityEntry.Entity as Item;
     if (item != null)
     {
         item.Created = DateTime.Now;
         item.Modified = DateTime.Now;
     }
 }
예제 #23
0
        public override void OnPostInsert(DbContext context, DbEntityEntry entry)
        {
            if (!this.ShouldAudit(entry))
                return;

            this.currentInsert.EntityId = this.GetEntityId(context, entry);
            this.OnAuditStoreInsert(this.currentInsert, context, entry);
            base.OnPostInsert(context, entry);
        }
예제 #24
0
        public string GetKeyValue(DbEntityEntry entry)
        {
            var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
            string id = string.Empty;
            if (objectStateEntry.EntityKey.EntityKeyValues != null)
                id = objectStateEntry.EntityKey.EntityKeyValues[0].Value.ToString();

            return id;
        }
예제 #25
0
        private static void UpdateTimeStamp(DbEntityEntry<IAuditInfo> entry)
        {
            if (entry.State == EntityState.Added)
            {
                entry.Entity.CreationDate = DateTime.Now;
            }

            entry.Entity.LastModified = DateTime.Now;
        }
예제 #26
0
        public LogEntry(DbEntityEntry e, string _userid, IEnumerable<KeyValuePair<string, object>> keys = null)
            : this()
        {
            userid = trimToLength(_userid, 64);
            action = trimToLength(e.State.ToString());
            object_name = trimToLength(e.Entity.GetType().ToString());

            SetKeyValues(keys);
        }
        private static string GetEntityName(DbEntityEntry input)
        {
            var type = input.Entity.GetType();

            if (type.FullName.StartsWith("System.Data.Entity.DynamicProxies") && type.BaseType != null)
                return type.BaseType.Name;

            return type.FullName;
        }
        /// <summary>
        /// Treat unchanged entries as added entries when creating audit records.
        /// </summary>
        /// <param name="dbEntry"></param>
        /// <returns></returns>
        protected override EntityState StateOf(DbEntityEntry dbEntry)
        {
            if (dbEntry.State == EntityState.Unchanged)
            {
                return EntityState.Added;
            }

            return base.StateOf(dbEntry);
        }
예제 #29
0
 private void SetModificationAuditProperties(DbEntityEntry entry)
 {
     if (entry.Entity is IModificationAudited)
     {
         var auditedEntry = entry.Cast<IModificationAudited>();
         auditedEntry.Entity.LastModificationTime = DateTime.Now; //TODO: UtcNow?
         auditedEntry.Entity.LastModifierUserId = AbpSession.UserId;
     }
 }
예제 #30
0
        private IEnumerable<AuditLog> GetAuditRecordsForChange(DbEntityEntry dbEntityEntry)
        {
            List<AuditLog> auditLogs = new List<AuditLog>();

            // get table attribute
            var tableAttribute = dbEntityEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
            var tableName = tableAttribute != null ? tableAttribute.Name : dbEntityEntry.Entity.GetType().Name;
            var keyName = dbEntityEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

            if (dbEntityEntry.State == System.Data.EntityState.Added)
            {
                auditLogs.Add(new AuditLog
                {
                    Id = Guid.NewGuid(),
                    UserName = System.Environment.UserName,
                    EventDateUTC = DateTime.Now.ToUniversalTime(),
                    EventType = "Added",
                    TableName = tableName,
                    ObjectID = dbEntityEntry.CurrentValues.GetValue<object>(keyName).ToString(),
                    ColumnName = "ALL",
                    NewValue = JsonConvert.SerializeObject(dbEntityEntry.CurrentValues, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
                });
            }

            else if (dbEntityEntry.State == System.Data.EntityState.Deleted)
            {
                auditLogs.Add(new AuditLog
                {
                    Id = Guid.NewGuid(),
                    UserName = System.Environment.UserName,
                    EventDateUTC = DateTime.Now.ToUniversalTime(),
                    EventType = "Deleted",
                    TableName = tableName,
                    ObjectID = dbEntityEntry.OriginalValues.GetValue<object>(keyName).ToString(),
                    ColumnName = "ALL",
                    OriginalValue = JsonConvert.SerializeObject(dbEntityEntry.OriginalValues, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
                });
            }

            else if (dbEntityEntry.State == System.Data.EntityState.Modified)
            {
                auditLogs.Add(new AuditLog
                {
                    Id = Guid.NewGuid(),
                    UserName = System.Environment.UserName,
                    EventDateUTC = DateTime.Now.ToUniversalTime(),
                    EventType = "Modified",
                    TableName = tableName,
                    ObjectID = dbEntityEntry.CurrentValues.GetValue<object>(keyName).ToString(),
                    ColumnName = "ALL",
                    NewValue = JsonConvert.SerializeObject(dbEntityEntry.CurrentValues, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
                });
            }

            return auditLogs;
        }
 public abstract IEnumerable <AuditLog> ProcessEvents(DbEntityEntry obj, TDataContext db, ApiIdentity identity, bool read);
예제 #32
0
 protected abstract void OnBefore(DbEntityEntry item);
예제 #33
0
        /// <summary>
        /// Method that will be called on an entity immediately before the item is saved by context
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="entry">The database entity entry.</param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, DbEntityEntry entry)
        {
            var rockContext = (RockContext)dbContext;

            HistoryChangeList = new History.HistoryChangeList();

            switch (entry.State)
            {
            case EntityState.Added:
            {
                HistoryChangeList.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Transaction");

                string person = History.GetValue <PersonAlias>(AuthorizedPersonAlias, AuthorizedPersonAliasId, rockContext);

                History.EvaluateChange(HistoryChangeList, "Authorized Person", string.Empty, person);
                History.EvaluateChange(HistoryChangeList, "Gateway", string.Empty, History.GetValue <FinancialGateway>(FinancialGateway, FinancialGatewayId, rockContext));
                History.EvaluateChange(HistoryChangeList, "Gateway Schedule Id", string.Empty, GatewayScheduleId);
                History.EvaluateChange(HistoryChangeList, "Transaction Code", string.Empty, TransactionCode);
                History.EvaluateChange(HistoryChangeList, "Summary", string.Empty, Summary);
                History.EvaluateChange(HistoryChangeList, "Type", (null as int?), TransactionTypeValue, TransactionTypeValueId);
                History.EvaluateChange(HistoryChangeList, "Source", (null as int?), SourceTypeValue, SourceTypeValueId);
                History.EvaluateChange(HistoryChangeList, "Frequency", (null as int?), TransactionFrequencyValue, TransactionFrequencyValueId);
                History.EvaluateChange(HistoryChangeList, "Start Date", (null as DateTime? ), StartDate);
                History.EvaluateChange(HistoryChangeList, "End Date", (null as DateTime? ), EndDate);
                History.EvaluateChange(HistoryChangeList, "Number of Payments", (null as int?), NumberOfPayments);
                History.EvaluateChange(HistoryChangeList, "Is Active", (null as bool?), IsActive);
                History.EvaluateChange(HistoryChangeList, "Card Reminder Date", (null as DateTime? ), CardReminderDate);
                History.EvaluateChange(HistoryChangeList, "Last Reminded Date", (null as DateTime? ), LastRemindedDate);
                var isOrganizationCurrency = new RockCurrencyCodeInfo(ForeignCurrencyCodeValueId).IsOrganizationCurrency;
                if (!isOrganizationCurrency)
                {
                    History.EvaluateChange(HistoryChangeList, "Currency Code", (null as int?), ForeignCurrencyCodeValue, ForeignCurrencyCodeValueId);
                }

                break;
            }

            case EntityState.Modified:
            {
                string origPerson = History.GetValue <PersonAlias>(null, entry.OriginalValues["AuthorizedPersonAliasId"].ToStringSafe().AsIntegerOrNull(), rockContext);
                string person     = History.GetValue <PersonAlias>(AuthorizedPersonAlias, AuthorizedPersonAliasId, rockContext);
                History.EvaluateChange(HistoryChangeList, "Authorized Person", origPerson, person);

                int?origGatewayId = entry.OriginalValues["FinancialGatewayId"].ToStringSafe().AsIntegerOrNull();
                if (!FinancialGatewayId.Equals(origGatewayId))
                {
                    History.EvaluateChange(HistoryChangeList, "Gateway", History.GetValue <FinancialGateway>(null, origGatewayId, rockContext), History.GetValue <FinancialGateway>(FinancialGateway, FinancialGatewayId, rockContext));
                }

                History.EvaluateChange(HistoryChangeList, "Gateway Schedule Id", entry.OriginalValues["GatewayScheduleId"].ToStringSafe(), GatewayScheduleId);
                History.EvaluateChange(HistoryChangeList, "Transaction Code", entry.OriginalValues["TransactionCode"].ToStringSafe(), TransactionCode);
                History.EvaluateChange(HistoryChangeList, "Summary", entry.OriginalValues["Summary"].ToStringSafe(), Summary);
                History.EvaluateChange(HistoryChangeList, "Type", entry.OriginalValues["TransactionTypeValueId"].ToStringSafe().AsIntegerOrNull(), TransactionTypeValue, TransactionTypeValueId);
                History.EvaluateChange(HistoryChangeList, "Source", entry.OriginalValues["SourceTypeValueId"].ToStringSafe().AsIntegerOrNull(), SourceTypeValue, SourceTypeValueId);
                History.EvaluateChange(HistoryChangeList, "Frequency", entry.OriginalValues["TransactionFrequencyValueId"].ToStringSafe().AsIntegerOrNull(), TransactionFrequencyValue, TransactionFrequencyValueId);
                History.EvaluateChange(HistoryChangeList, "Start Date", entry.OriginalValues["StartDate"].ToStringSafe().AsDateTime(), StartDate);
                History.EvaluateChange(HistoryChangeList, "End Date", entry.OriginalValues["EndDate"].ToStringSafe().AsDateTime(), EndDate);
                History.EvaluateChange(HistoryChangeList, "Number of Payments", entry.OriginalValues["EndDate"].ToStringSafe().AsIntegerOrNull(), NumberOfPayments);
                History.EvaluateChange(HistoryChangeList, "Is Active", entry.OriginalValues["IsActive"].ToStringSafe().AsBooleanOrNull(), IsActive);
                History.EvaluateChange(HistoryChangeList, "Card Reminder Date", entry.OriginalValues["CardReminderDate"].ToStringSafe().AsDateTime(), CardReminderDate);
                History.EvaluateChange(HistoryChangeList, "Last Reminded Date", entry.OriginalValues["LastRemindedDate"].ToStringSafe().AsDateTime(), LastRemindedDate);
                History.EvaluateChange(HistoryChangeList, "Currency Code", entry.OriginalValues["ForeignCurrencyCodeValueId"].ToStringSafe().AsIntegerOrNull(), ForeignCurrencyCodeValue, ForeignCurrencyCodeValueId);

                break;
            }

            case EntityState.Deleted:
            {
                HistoryChangeList.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Transaction");

                // If a FinancialPaymentDetail was linked to this FinancialScheduledTransaction and is now orphaned, delete it.
                var financialPaymentDetailService = new FinancialPaymentDetailService(rockContext);
                financialPaymentDetailService.DeleteOrphanedFinancialPaymentDetail(entry);

                break;
            }
            }

            base.PreSaveChanges(dbContext, entry);
        }
예제 #34
0
 protected virtual void HandleModify(DbEntityEntry entry)
 {
     HandleState.Modify(entry);
 }
예제 #35
0
        public virtual void Add(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);

            this.DbSet.Add(entity);
        }
예제 #36
0
        protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary <object, object> items)
        {
            if (entityEntry.Entity is BSEntityInterface)
            {
                var Gnd = (BSEntityInterface)entityEntry.Entity;

                return(new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, Gnd.IsValid()));
            }
            return(base.ValidateEntity(entityEntry, items));
        }
예제 #37
0
 protected virtual void HandleAdd(DbEntityEntry entry)
 {
     HandleState.Add(entry);
 }
예제 #38
0
        public virtual void Edit(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry <T>(entity);

            dbEntityEntry.State = EntityState.Modified;
        }
예제 #39
0
        public virtual void Add(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry <T>(entity);

            DbContext.Set <T>().Add(entity);
        }
        public bool MeesageParsing(string msgType, string msg_body, int msg_idnum)
        {
            bool result = false;

            try
            {
                #region Initialize values
                string[] msgBody;
                string[] rowLine;
                string   header;

                EDI315                      dbEDI315                   = new EDI315();
                EDI315_Detail               dbEDI315_Detail            = new EDI315_Detail();
                List <EDI315_Detail_N9>     dbEDI315_Detail_N9List     = new List <EDI315_Detail_N9>();
                List <EDI315_Detail_R4>     dbEDI315_Detail_R4List     = new List <EDI315_Detail_R4>();
                List <EDI315_Detail_R4_DTM> dbEDI315_Detail_R4_DTMList = new List <EDI315_Detail_R4_DTM>();

                int     convertToInt     = 0;
                decimal convertToDecimal = 0;
                #endregion

                msg_body = Regex.Replace(msg_body, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
                msgBody  = msg_body.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

                foreach (string row in msgBody)
                {
                    if (row != null && row.Length > 0)
                    {
                        rowLine = row.Split('*');

                        header = "";
                        if (EDI315_HEADERS.Any(x => x.ToUpper() == rowLine[0]))
                        {
                            header = rowLine[0];
                        }

                        switch (header)
                        {
                        case "ISA":
                            #region ISA
                            if (rowLine.Count() == 17)      // header 1 + element 16 == 17
                            {
                                dbEDI315 = new EDI315()
                                {
                                    ISA_auth_info_qualifier                = SubstringValue(rowLine[1] ?? "", 2),
                                    ISA_auth_info                          = SubstringValue(rowLine[2] ?? "", 10),
                                    ISA_security_info_qualifier            = SubstringValue(rowLine[3] ?? "", 2),
                                    ISA_security_info                      = SubstringValue(rowLine[4] ?? "", 10),
                                    ISA_interchange_id_qualifier_1         = SubstringValue(rowLine[5] ?? "", 2),
                                    ISA_interchange_sender_id              = SubstringValue(rowLine[6] ?? "", 15),
                                    ISA_interchange_id_qualifier_2         = SubstringValue(rowLine[7] ?? "", 2),
                                    ISA_interchange_receiver_id            = SubstringValue(rowLine[8] ?? "", 15),
                                    ISA_interchage_date                    = SubstringValue(rowLine[9] ?? "", 8),
                                    ISA_interchange_time                   = SubstringValue(rowLine[10] ?? "", 4),
                                    ISA_interchange_control_standards_id   = SubstringValue(rowLine[11] ?? "", 1),
                                    ISA_interchange_control_version_number = SubstringValue(rowLine[12] ?? "", 5),
                                    ISA_interchange_control_number         = SubstringValue(rowLine[13] ?? "", 9),
                                    ISA_ack_requested                      = SubstringValue(rowLine[14] ?? "", 1),
                                    ISA_usage_indicator                    = SubstringValue(rowLine[15] ?? "", 1),
                                    ISA_component_element_separator        = SubstringValue(rowLine[16] ?? "", 1),
                                };
                            }
                            else
                            {
                                throw new Exception("ISA element should be 16.\r\n");
                            }
                            #endregion
                            break;

                        case "GS":                    // insert DB
                            #region GS
                            if (rowLine.Count() == 9) // header 1 + element 8 == 9
                            {
                                dbEDI315.GS_functional_id_code = SubstringValue(rowLine[1] ?? "", 2);
                                dbEDI315.GS_app_sender_code    = SubstringValue(rowLine[2] ?? "", 15);
                                dbEDI315.GS_app_receiver_code  = SubstringValue(rowLine[3] ?? "", 15);
                                dbEDI315.GS_date = SubstringValue(rowLine[4] ?? "", 8);
                                dbEDI315.GS_time = SubstringValue(rowLine[5] ?? "", 8);
                                dbEDI315.GS_group_control_number   = SubstringValue(rowLine[6] ?? "", 9);
                                dbEDI315.GS_reponsible_agency_code = SubstringValue(rowLine[7] ?? "", 2);
                                dbEDI315.GS_industry_id_code       = SubstringValue(rowLine[8] ?? "", 12);

                                /* Insert table EDI315 after done with ISA & GS */
                                if (msg_idnum != 0)
                                {
                                    if (util.dbConnectionCheck())
                                    {
                                        using (DBContext context = new DBContext())
                                        {
                                            dbEDI315.msg_idnum    = msg_idnum;
                                            dbEDI315.created_date = DateTime.Now;
                                            context.EDI315.Add(dbEDI315);
                                            context.SaveChanges();
                                            context.Dispose();
                                        }
                                    }
                                    else
                                    {
                                        string logMsg = "Date: " + DateTime.Now.ToString();
                                        logMsg += "\r\nFunction: MeesageParsing - Table EDI315";
                                        logMsg += "\r\nError Message: Not able to access DB. Process rollbacked.";
                                        logMsg += "\r\nValues Info:";
                                        logMsg += "\r\nmstType: 315";

                                        if (msg_idnum != 0)
                                        {
                                            logMsg += "\r\nmsg_idnum: " + msg_idnum;
                                        }

                                        if (dbEDI315.EDI315_idnum != 0)
                                        {
                                            logMsg += "\r\nEDI_idnum: " + dbEDI315.EDI315_idnum;
                                        }

                                        util.insertLog_TextFile(msgType, msg_idnum, dbEDI315.EDI315_idnum, 0, logMsg);

                                        rollbackProcess(msg_idnum, msgType);
                                        return(false);
                                    }
                                }
                            }

                            #endregion
                            break;

                        case "ST":
                            #region ST
                            /* Detail start. Init. */
                            dbEDI315_Detail            = new EDI315_Detail();
                            dbEDI315_Detail_N9List     = new List <EDI315_Detail_N9>();
                            dbEDI315_Detail_R4List     = new List <EDI315_Detail_R4>();
                            dbEDI315_Detail_R4_DTMList = new List <EDI315_Detail_R4_DTM>();
                            #endregion
                            break;

                        case "SE":
                            /* Detail End. Insert into Tables. */
                            #region SE
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            convertToInt = 0;
                            if (rowLine[1] != null && rowLine[1].Trim() != string.Empty && Int32.TryParse(rowLine[1], out convertToInt))
                            {
                                dbEDI315_Detail.SE_included_segments_number = convertToInt;
                            }

                            dbEDI315_Detail.SE_transaction_set_control_number = SubstringValue(rowLine[2] ?? "", 9);


                            /* insert Table EDI315_Detail, EDI315_Detail_N9, EDI315_Detail_R4 & EDI315_Detail_R4_DTM */
                            if (util.dbConnectionCheck())
                            {
                                using (DBContext context = new DBContext())
                                {
                                    /* EDI315_Detail Insert */
                                    dbEDI315_Detail.msg_idnum    = msg_idnum;
                                    dbEDI315_Detail.EDI315_idnum = dbEDI315.EDI315_idnum;
                                    context.EDI315_Detail.Add(dbEDI315_Detail);
                                    context.SaveChanges();

                                    /* EDI315_Detail_N9 Insert */
                                    foreach (EDI315_Detail_N9 dbN9Row in dbEDI315_Detail_N9List)
                                    {
                                        dbN9Row.msg_idnum           = msg_idnum;
                                        dbN9Row.EDI315_Detail_idnum = dbEDI315_Detail.EDI315_Detail_idnum;
                                    }
                                    context.EDI315_Detail_N9.AddRange(dbEDI315_Detail_N9List);
                                    context.SaveChanges();

                                    /* EDI315_Detail_R4 & EDI315_Detail_R4_DTM Insert */
                                    foreach (EDI315_Detail_R4 dbR4Row in dbEDI315_Detail_R4List)
                                    {
                                        List <EDI315_Detail_R4_DTM> dtmList = dbEDI315_Detail_R4_DTMList.Where(x => x.Detail_R4_idnum == dbR4Row.Detail_R4_idnum).ToList();

                                        dbR4Row.msg_idnum           = msg_idnum;
                                        dbR4Row.EDI315_Detail_idnum = dbEDI315_Detail.EDI315_Detail_idnum;
                                        context.EDI315_Detail_R4.Add(dbR4Row);
                                        context.SaveChanges();

                                        foreach (EDI315_Detail_R4_DTM dtmRow in dtmList)
                                        {
                                            dtmRow.msg_idnum       = msg_idnum;
                                            dtmRow.Detail_R4_idnum = dbR4Row.Detail_R4_idnum;
                                        }
                                        context.EDI315_Detail_R4_DTM.AddRange(dtmList);
                                        context.SaveChanges();
                                    }
                                    context.Dispose();
                                }
                            }
                            else
                            {
                                string logMsg = "Date: " + DateTime.Now.ToString();
                                logMsg += "\r\nFunction: MeesageParsing - Table EDI315_Detail, EDI315_Detail_N9, EDI315_Detail_R4, EDI315_Detail_R4_DTM";
                                logMsg += "\r\nError Message: Not able to access DB. Process rollbacked.";

                                logMsg += "\r\nValues Info:";
                                logMsg += "\r\nmstType: 315";

                                if (msg_idnum != 0)
                                {
                                    logMsg += "\r\nmsg_idnum: " + msg_idnum;
                                }

                                if (dbEDI315.EDI315_idnum != 0)
                                {
                                    logMsg += "\r\nEDI_idnum: " + dbEDI315.EDI315_idnum;
                                }

                                if (dbEDI315_Detail.EDI315_Detail_idnum != 0)
                                {
                                    logMsg += "\r\nDetail_idnum: " + dbEDI315_Detail.EDI315_Detail_idnum;
                                }

                                util.insertLog_TextFile(msgType, msg_idnum, dbEDI315.EDI315_idnum, dbEDI315_Detail.EDI315_Detail_idnum, logMsg);

                                rollbackProcess(msg_idnum, msgType);
                                return(false);
                            }
                            #endregion
                            break;

                        case "B4":
                            #region B4
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            dbEDI315_Detail.B4_SHC = SubstringValue(rowLine[1], 3);

                            convertToInt = 0;
                            if (rowLine[2] != null && rowLine[2].Trim() != string.Empty && Int32.TryParse(rowLine[2], out convertToInt))
                            {
                                dbEDI315_Detail.B4_request_number = convertToInt;
                            }

                            dbEDI315_Detail.B4_status_code     = SubstringValue(rowLine[3], 2);
                            dbEDI315_Detail.B4_date            = SubstringValue(rowLine[4] ?? "", 8);
                            dbEDI315_Detail.B4_status_time     = SubstringValue(rowLine[5] ?? "", 4);
                            dbEDI315_Detail.B4_status_location = SubstringValue(rowLine[6] ?? "", 5);

                            dbEDI315_Detail.B4_equip_initial     = SubstringValue(rowLine[7], 4);
                            dbEDI315_Detail.B4_equip_number      = SubstringValue(rowLine[8], 10);
                            dbEDI315_Detail.B4_equip_status_code = SubstringValue(rowLine[9], 2);
                            dbEDI315_Detail.B4_equip_type        = SubstringValue(rowLine[10], 4);
                            dbEDI315_Detail.B4_location_code     = SubstringValue(rowLine[11], 30);
                            dbEDI315_Detail.B4_location_id       = SubstringValue(rowLine[12], 2);

                            if (rowLine.Count() > 13)
                            {
                                convertToInt = 0;
                                if (rowLine[13] != null && rowLine[13].Trim() != string.Empty && Int32.TryParse(rowLine[13], out convertToInt))
                                {
                                    dbEDI315_Detail.B4_equip_check_digit = convertToInt;
                                }
                            }
                            #endregion
                            break;

                        case "Q2":
                            #region Q2
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            dbEDI315_Detail.Q2_vessel_code  = SubstringValue(rowLine[1], 8);
                            dbEDI315_Detail.Q2_country_code = SubstringValue(rowLine[2], 3);
                            dbEDI315_Detail.Q2_date_1       = SubstringValue(rowLine[3], 8);
                            dbEDI315_Detail.Q2_date_2       = SubstringValue(rowLine[4], 8);
                            dbEDI315_Detail.Q2_date_3       = SubstringValue(rowLine[5], 8);

                            convertToInt = 0;
                            if (rowLine[6] != null && rowLine[6].Trim() != string.Empty && Int32.TryParse(rowLine[6], out convertToInt))
                            {
                                dbEDI315_Detail.Q2_lading_quantity = convertToInt;
                            }

                            convertToDecimal = 0;
                            if (rowLine[7] != null && rowLine[7].Trim() != string.Empty && Decimal.TryParse(rowLine[7], out convertToDecimal))
                            {
                                dbEDI315_Detail.Q2_weight = convertToDecimal;
                            }

                            dbEDI315_Detail.Q2_weight_qualifier       = SubstringValue(rowLine[8], 2);
                            dbEDI315_Detail.Q2_voyage_number          = SubstringValue(rowLine[9], 10);
                            dbEDI315_Detail.Q2_reference_id_qualifier = SubstringValue(rowLine[10], 3);
                            dbEDI315_Detail.Q2_reference_id           = SubstringValue(rowLine[11], 30);
                            dbEDI315_Detail.Q2_vessel_code_qualifier  = SubstringValue(rowLine[12], 1);
                            dbEDI315_Detail.Q2_vessel_name            = SubstringValue(rowLine[13], 28);

                            convertToDecimal = 0;
                            if (rowLine[14] != null && rowLine[14].Trim() != string.Empty && Decimal.TryParse(rowLine[14], out convertToDecimal))
                            {
                                dbEDI315_Detail.Q2_volume = convertToDecimal;
                            }

                            dbEDI315_Detail.Q2_volume_unit_qualifier = SubstringValue(rowLine[15], 1);
                            dbEDI315_Detail.Q2_weight_unit_code      = SubstringValue(rowLine[16], 1);
                            #endregion
                            break;

                        case "N9":
                            #region N9
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            {
                                EDI315_Detail_N9 dbTemp = new EDI315_Detail_N9();

                                dbTemp.reference_id_qualifier = SubstringValue(rowLine[1] ?? "", 3);

                                if (rowLine.Count() > 2)
                                {
                                    dbTemp.reference_id = SubstringValue(rowLine[2], 30);
                                }

                                if (rowLine.Count() > 3)
                                {
                                    dbTemp.free_form_description = SubstringValue(rowLine[3], 45);
                                }

                                if (rowLine.Count() > 4)
                                {
                                    dbTemp.date = SubstringValue(rowLine[4], 8);
                                }

                                if (rowLine.Count() > 5)
                                {
                                    dbTemp.time = SubstringValue(rowLine[5], 8);
                                }

                                if (rowLine.Count() > 6)
                                {
                                    dbTemp.time_code = SubstringValue(rowLine[6], 2);
                                }

                                dbEDI315_Detail_N9List.Add(dbTemp);
                            }
                            #endregion
                            break;

                        case "R4":
                            #region R4
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            {
                                EDI315_Detail_R4 dbTemp = new EDI315_Detail_R4();

                                dbTemp.Detail_R4_idnum    = dbEDI315_Detail_R4List.Count() + 1;
                                dbTemp.port_function_code = SubstringValue(rowLine[1] ?? "", 1);

                                if (rowLine.Count() > 2)
                                {
                                    dbTemp.location_qualifier = SubstringValue(rowLine[2], 2);
                                }

                                if (rowLine.Count() > 3)
                                {
                                    dbTemp.location_id = SubstringValue(rowLine[3], 30);
                                }

                                if (rowLine.Count() > 4)
                                {
                                    dbTemp.port_name = SubstringValue(rowLine[4], 24);
                                }

                                if (rowLine.Count() > 5)
                                {
                                    dbTemp.country_code = SubstringValue(rowLine[5], 3);
                                }

                                if (rowLine.Count() > 6)
                                {
                                    dbTemp.terminal_name = SubstringValue(rowLine[6], 30);
                                }

                                if (rowLine.Count() > 7)
                                {
                                    dbTemp.pier_number = SubstringValue(rowLine[7], 4);
                                }

                                if (rowLine.Count() > 8)
                                {
                                    dbTemp.province_code = SubstringValue(rowLine[8], 2);
                                }

                                dbEDI315_Detail_R4List.Add(dbTemp);
                            }
                            #endregion
                            break;

                        case "DTM":
                            #region DTM
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            {
                                EDI315_Detail_R4_DTM dbTemp = new EDI315_Detail_R4_DTM();

                                dbTemp.Detail_R4_idnum = dbEDI315_Detail_R4List.Count();

                                if (rowLine.Count() > 1)
                                {
                                    dbTemp.datetime_qualifier = SubstringValue(rowLine[1] ?? "", 3);
                                }

                                if (rowLine.Count() > 2)
                                {
                                    dbTemp.date = SubstringValue(rowLine[2], 8);
                                }

                                if (rowLine.Count() > 3)
                                {
                                    dbTemp.time = SubstringValue(rowLine[3], 4);
                                }

                                if (rowLine.Count() > 4)
                                {
                                    dbTemp.time_code = SubstringValue(rowLine[4], 2);
                                }

                                dbEDI315_Detail_R4_DTMList.Add(dbTemp);
                            }
                            #endregion
                            break;
                        }
                    }
                }
                result = true;
            }
            catch (DbEntityValidationException ex)
            {
                #region Exception
                string logMsg = "Date: " + DateTime.Now.ToString();
                logMsg += "\r\nFunction: MeesageParsing";
                logMsg += "\r\nProcess rollbacked.";

                logMsg += "\r\nError Message: ";
                foreach (DbEntityValidationResult item in ex.EntityValidationErrors)
                {
                    // Get entry
                    DbEntityEntry entry          = item.Entry;
                    string        entityTypeName = entry.Entity.GetType().Name;

                    foreach (DbValidationError subItem in item.ValidationErrors)
                    {
                        logMsg += string.Format("\r\nError '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName);
                    }
                }

                util.insertLog(msgType, msg_idnum, 0, 0, logMsg);

                rollbackProcess(msg_idnum, msgType);
                result = false;
                #endregion
            }
            catch (Exception ex)
            {
                #region Exception
                string logMsg = "Date: " + DateTime.Now.ToString();
                logMsg += "\r\nFunction: MeesageParsing";
                logMsg += "\r\nProcess rollbacked.";
                logMsg += "\r\nError Message:\r\n" + ex.ToString();

                util.insertLog(msgType, msg_idnum, 0, 0, logMsg);

                rollbackProcess(msg_idnum, msgType);
                result = false;
                #endregion
            }
            return(result);
        }
예제 #41
0
        object GetPrimaryKeyValue(DbEntityEntry entry)
        {
            var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);

            return(objectStateEntry.EntityKey.EntityKeyValues[0].Value);
        }
예제 #42
0
        public virtual void Delete(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry <T>(entity);

            dbEntityEntry.State = EntityState.Deleted;
        }
예제 #43
0
        /// <summary>
        /// Updates each entry in the ChangeSet with its corresponding conflict info.
        /// </summary>
        /// <param name="operationConflictMap">Map of conflicts to their corresponding operations entries.</param>
        private void SetChangeSetConflicts(Dictionary <DbEntityEntry, ChangeSetEntry> operationConflictMap)
        {
            object    storeValue;
            EntityKey refreshEntityKey;

            ObjectContext      objectContext      = ((IObjectContextAdapter)DbContext).ObjectContext;
            ObjectStateManager objectStateManager = objectContext.ObjectStateManager;

            if (objectStateManager == null)
            {
                throw Error.InvalidOperation(Resource.ObjectStateManagerNotFoundException, DbContext.GetType().Name);
            }

            foreach (var conflictEntry in operationConflictMap)
            {
                DbEntityEntry    entityEntry = conflictEntry.Key;
                ObjectStateEntry stateEntry  = objectStateManager.GetObjectStateEntry(entityEntry.Entity);

                if (stateEntry.State == EntityState.Unchanged)
                {
                    continue;
                }

                // Note: we cannot call Refresh StoreWins since this will overwrite Current entity and remove the optimistic concurrency ex.
                ChangeSetEntry operationInConflict = conflictEntry.Value;
                refreshEntityKey = RefreshContext.CreateEntityKey(stateEntry.EntitySet.Name, stateEntry.Entity);
                RefreshContext.TryGetObjectByKey(refreshEntityKey, out storeValue);
                operationInConflict.StoreEntity = storeValue;

                // StoreEntity will be null if the entity has been deleted in the store (i.e. Delete/Delete conflict)
                bool isDeleted = (operationInConflict.StoreEntity == null);
                if (isDeleted)
                {
                    operationInConflict.IsDeleteConflict = true;
                }
                else
                {
                    // Determine which members are in conflict by comparing original values to the current DB values
                    PropertyDescriptorCollection propDescriptors = TypeDescriptor.GetProperties(operationInConflict.Entity.GetType());
                    List <string>      membersInConflict         = new List <string>();
                    object             originalValue;
                    PropertyDescriptor pd;
                    for (int i = 0; i < stateEntry.OriginalValues.FieldCount; i++)
                    {
                        originalValue = stateEntry.OriginalValues.GetValue(i);
                        if (originalValue is DBNull)
                        {
                            originalValue = null;
                        }

                        string propertyName = stateEntry.OriginalValues.GetName(i);
                        pd = propDescriptors[propertyName];
                        if (pd == null)
                        {
                            // This might happen in the case of a private model
                            // member that isn't mapped
                            continue;
                        }

                        if (!Object.Equals(originalValue, pd.GetValue(operationInConflict.StoreEntity)))
                        {
                            membersInConflict.Add(pd.Name);
                        }
                    }
                    operationInConflict.ConflictMembers = membersInConflict;
                }
            }
        }
예제 #44
0
        public HttpResponseMessage ConfirmWarnings([FromUri] string warnIds, [FromBody] ConfirmModel model)
        {
            int[] warnArray = warnIds.Split(',').Select(s => Convert.ToInt32(s)).ToArray();

            if (model == null)
            {
                return(Request.CreateResponse(
                           System.Net.HttpStatusCode.BadRequest,
                           StringHelper.GetMessageString("参数无效,缺少确认信息")));
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("共{0}条:", warnArray.Length);

            using (SecureCloud_Entities entity = new SecureCloud_Entities())
            {
                foreach (var warnId in warnArray)
                {
                    var warn = entity.T_WARNING_SENSOR.FirstOrDefault(w => w.Id == warnId);
                    if (warn.DealFlag == WarningSupportProcessed || warn.DealFlag == WarningClientProcessed)
                    {
                        return(Request.CreateResponse(
                                   System.Net.HttpStatusCode.BadRequest,
                                   StringHelper.GetMessageString("告警已被处理!")));
                    }

                    int roleId = 5;
                    if (Request.Properties.ContainsKey("AuthorizationInfo"))
                    {
                        var info = Request.Properties["AuthorizationInfo"] as AuthorizationInfo;
                        roleId = info != null && info.RoleId != null ? (int)info.RoleId : 5;
                    }

                    warn.DealFlag = roleId == 5 ? WarningClientProcessed : WarningSupportProcessed; // update DealFlag for Client or Support.

                    var entry1 = entity.Entry(warn);
                    entry1.State = EntityState.Modified;

                    #region 日志信息
                    var stc =
                        entity.T_DIM_STRUCTURE.Where(s => s.ID == warn.StructId)
                        .Select(s => s.STRUCTURE_NAME_CN)
                        .FirstOrDefault();
                    string type = warn.DeviceTypeId == 1 ? "dtu" : "传感器";
                    string name = string.Empty;
                    if (warn.DeviceTypeId == 1)
                    {
                        string dtuId = warn.DeviceId.ToString();
                        name =
                            entity.T_DIM_REMOTE_DTU.Where(
                                d => d.ID == warn.DeviceId || d.REMOTE_DTU_NUMBER == dtuId)
                            .Select(d => d.REMOTE_DTU_NUMBER)
                            .FirstOrDefault();
                    }
                    else
                    {
                        name =
                            entity.T_DIM_SENSOR.Where(s => s.SENSOR_ID == warn.DeviceId)
                            .Select(s => s.SENSOR_LOCATION_DESCRIPTION)
                            .FirstOrDefault();
                    }
                    sb.AppendFormat("{0}.{1}:{2}-{3};", stc, type, name, warn.Content);
                    #endregion

                    var dealDetails = new T_WARNING_DEALDETAILS();
                    dealDetails.WarningId   = warnId;
                    dealDetails.UserNo      = model.Confirmor;
                    dealDetails.Suggestion  = model.Suggestion;
                    dealDetails.ConfirmTime = DateTime.Now;

                    DbEntityEntry <T_WARNING_DEALDETAILS> entry2 = entity.Entry <T_WARNING_DEALDETAILS>(dealDetails);
                    entry2.State = EntityState.Added;
                }

                #region 日志信息
                this.Request.Properties["ActionParameter"]     = JsonConvert.SerializeObject(model);
                this.Request.Properties["ActionParameterShow"] = sb.ToString();
                #endregion

                try
                {
                    entity.SaveChanges();
                    return(Request.CreateResponse(
                               System.Net.HttpStatusCode.Accepted,
                               StringHelper.GetMessageString("处理成功!")));
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(
                               System.Net.HttpStatusCode.BadRequest,
                               StringHelper.GetMessageString("处理失败!")));
                }
            }
        }
예제 #45
0
        public virtual void Detach(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);

            entry.State = EntityState.Detached;
        }
예제 #46
0
        public virtual void Delete <T>(T entity) where T : class
        {
            DbEntityEntry dbEntityEntry = _dbContext.Entry <T>(entity);

            dbEntityEntry.State = EntityState.Deleted;
        }
예제 #47
0
        public void Detach(Bloggpost entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);

            entry.State = EntityState.Detached;
        }
예제 #48
0
        public virtual void Update <T>(T entity) where T : class
        {
            DbEntityEntry dbEntityEntry = _dbContext.Entry <T>(entity);

            dbEntityEntry.State = EntityState.Modified;
        }
예제 #49
0
 protected virtual void HandleDelete(DbEntityEntry entry)
 {
     HandleState.Delete(entry);
 }
예제 #50
0
 private static bool IsState(DbEntityEntry entity, EntityState state)
 {
     return((entity.State & state) == state);
 }
예제 #51
0
 protected virtual void HandleDefault(DbEntityEntry entry)
 {
     HandleState.Default(entry);
 }
예제 #52
0
 private static bool HasChanged(DbEntityEntry entity)
 {
     return(IsState(entity, EntityState.Added) ||
            IsState(entity, EntityState.Deleted) ||
            IsState(entity, EntityState.Modified));
 }
예제 #53
0
        public virtual void Update(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);

            this.DbSet.Attach(entity);
        }
예제 #54
0
 public virtual void OnPostDelete(DbContext context, DbEntityEntry entry)
 {
 }
예제 #55
0
 protected abstract void OnAfter(DbEntityEntry item, EntityState state);
예제 #56
0
 public virtual void OnPreUpdate(DbContext context, DbEntityEntry entry)
 {
 }
예제 #57
0
 public virtual bool IsTargetEntity(DbEntityEntry item)
 {
     return(item.State != EntityState.Detached &&
            TargetType.IsInstanceOfType(item.Entity));
 }
예제 #58
0
 public virtual void OnPostInsert(DbContext context, DbEntityEntry entry)
 {
 }
        public void Delete(T entity)
        {
            DbEntityEntry dbEntityEntry = studentContext.Entry(entity);

            dbEntityEntry.State = EntityState.Deleted;
        }
예제 #60
0
        public bool dbConnectionCheck()
        {
            bool isConnected = false;

            int checkCount = 0;

            while (checkCount < 5)
            {
                try
                {
                    using (DBContext context = new DBContext())
                    {
                        context.Database.Connection.Open();
                        context.Dispose();

                        isConnected = true;
                        break;
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    checkCount++;

                    string logMsg = "Date: " + DateTime.Now.ToString();
                    logMsg += "\r\nFunction: dbConnectionCheck";
                    logMsg += "\r\nAttempt Count: " + checkCount + " / 5";

                    foreach (DbEntityValidationResult item in ex.EntityValidationErrors)
                    {
                        // Get entry
                        DbEntityEntry entry          = item.Entry;
                        string        entityTypeName = entry.Entity.GetType().Name;

                        foreach (DbValidationError subItem in item.ValidationErrors)
                        {
                            logMsg += string.Format("\r\nError '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName);
                        }
                    }

                    insertLog_TextFile(logMsg);

                    // 30 min wait
                    System.Threading.Thread.Sleep((1000 * 60) * 30);
                }
                catch (Exception ex)
                {
                    checkCount++;

                    // create text file
                    string logMsg = "Date: " + DateTime.Now.ToString();
                    logMsg += "\r\nFunction: dbConnectionCheck";
                    logMsg += "\r\nAttempt Count: " + checkCount + " / 5";
                    logMsg += "\r\nError Message: \r\n" + ex.ToString();
                    insertLog_TextFile(logMsg);

                    // 30 min wait
                    System.Threading.Thread.Sleep((1000 * 60) * 30);
                }
            }
            return(isConnected);
        }