예제 #1
0
        public InsertComponent(ConflictMode conflictMode)
        {
            switch (conflictMode)
            {
            case ConflictMode.Abort:
                value = Constants.QueryComponents.INSERT_OR_ABORT;
                break;

            case ConflictMode.Fail:
                value = Constants.QueryComponents.INSERT_OR_FAIL;
                break;

            case ConflictMode.Ignore:
                value = Constants.QueryComponents.INSERT_OR_IGNORE;
                break;

            case ConflictMode.Replace:
                value = Constants.QueryComponents.INSERT_OR_REPLACE;
                break;

            case ConflictMode.Rollback:
                value = Constants.QueryComponents.INSERT_OR_ROLLBACK;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(conflictMode), conflictMode, "Unexpected value");
            }
        }
예제 #2
0
        public OnConflictComponent(ConflictMode mode)
        {
            value = Constants.QueryComponents.ON_CONFLICT + Constants.QueryComponents.SPACE;
            switch (mode)
            {
            case ConflictMode.Abort:
                value += Constants.QueryComponents.ABORT;
                break;

            case ConflictMode.Fail:
                value += Constants.QueryComponents.FAIL;
                break;

            case ConflictMode.Ignore:
                value += Constants.QueryComponents.IGNORE;
                break;

            case ConflictMode.Replace:
                value += Constants.QueryComponents.REPLACE;
                break;

            case ConflictMode.Rollback:
                value += Constants.QueryComponents.ROLLBACK;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }
        }
예제 #3
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     if (this._useCount == 0)
     {
         base.SubmitChanges(failureMode);
     }
 }
예제 #4
0
        private void Commit(TContext context, ConflictMode conflictMode)
        {
            if (context == null)
            {
                throw new ArgumentException("Context");
            }

            ChangeSet changeSet = context.GetChangeSet();

            if (changeSet.Inserts.Count > 0 || changeSet.Updates.Count > 0 || changeSet.Deletes.Count > 0)
            {
                if (conflictMode == ConflictMode.ContinueOnConflict)
                {
                    try
                    {
                        context.SubmitChanges(conflictMode);
                    }
                    catch (ChangeConflictException)
                    {
                        OnChangeConflict(context.ChangeConflicts);
                    }
                }
                else
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        context.SubmitChanges(conflictMode);
                        scope.Complete();
                    }
                }
            }
        }
예제 #5
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            if (OnBeforeSubmitChanges != null)
            {
                OnBeforeSubmitChanges(this, EventArgs.Empty);
            }

            base.SubmitChanges(failureMode);
        }
        protected void ApplyChanges(ConflictMode conflictMode)
        {
            foreach (Action <ConflictMode> action in _changeQueue)
            {
                action(conflictMode);
            }

            _changeQueue.Clear();
        }
 public override void SubmitChanges(ConflictMode failureMode)
 {
     ValidationResult[] = this.Validate();
     if (invalidResults.Length > 0)
     {
         // You should define this exception type
         throw new ValidationException(invalidResults);
     }
     base.SubmitChanges(failureMode);
 }
예제 #8
0
    public override void SubmitChanges(ConflictMode failureMode)
    {
        int inserts = base.GetChangeSet().Inserts.Count;
        int updates = base.GetChangeSet().Updates.Count;
        int deletes = base.GetChangeSet().Deletes.Count;

        Trace.WriteLine(string.Format("{0}  There are {1} inserts, {2} updates and {3} deletes.", DateTime.Now.ToLongTimeString(), inserts, updates, deletes));

        base.SubmitChanges(failureMode);
    }
예제 #9
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     try
     {
         base.SubmitChanges(failureMode);
     }
     catch (Exception ex)
     {
         log.Error("SubmitChanges is FAILED", ex);
     }
 }
예제 #10
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     try
     {
         base.SubmitChanges(failureMode);
     }
     catch (Exception ex)
     {
         // do whatever you would like with the exception
     }
 }
예제 #11
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            ApplyChanges(failureMode);

            _childNodesProperty.SetValue(_rootNode, _dataSource.ToArray());

            using (Stream stream = _streamFactory.CreateInstance(StreamMode.Write))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TRootNode));
                serializer.Serialize(stream, _rootNode);
            }
        }
예제 #12
0
    public override void SubmitChanges(ConflictMode failureMode)
    {
        ChangeSet changes = GetChangeSet();

        foreach (var entity in changes.Inserts())
        {
        }

        // you could do the same with updates and deletes

        base.SubmitChanges(failureMode);
    }
예제 #13
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            base.SubmitChanges(failureMode);

            if (HostingEnvironment.IsHosted)
            {
                HttpContext.Current.Items["Membresia_Context"] = null;
            }
            else
            {
                Context.instancia = null;
            }
        }
예제 #14
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     try
     {
         base.SubmitChanges(ConflictMode.ContinueOnConflict);
     }
     catch (ChangeConflictException)
     {
         foreach (var x in this.ChangeConflicts)
         {
             x.Resolve(RefreshMode.KeepCurrentValues);
         }
     }
 }
예제 #15
0
        /// <summary>
        /// Asynchronously sends changes that were made to retrieved objects to the underlying database,
        /// and specifies the action to be taken if the submission fails.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="failureMode">The action to be taken if the submission fails.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The task.</returns>
        public static Task SubmitChangesAsync(this DataContext dataContext, ConflictMode failureMode, CancellationToken cancellationToken)
        {
            if (dataContext == null)
            {
                throw new ArgumentNullException(nameof(dataContext));
            }

            // Using TaskBridge-based async polyfill as the best effort solution
            // (there is no better way without modifying the stock LINQ to SQL implementation).

            return(TaskBridge.ExecuteAsync(
                       () => dataContext.SubmitChanges(failureMode),
                       cancellationToken));
        }
예제 #16
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            ApplyChanges(failureMode);

            using (Stream stream = _streamFactory.CreateInstance(StreamMode.Write))
            {
                using (StreamWriter streamWriter = new StreamWriter(stream))
                {
                    _fileHelperEngine.WriteStream(streamWriter, _dataSource);

                    streamWriter.Flush();
                }
            }
        }
예제 #17
0
    public override void SubmitChanges(ConflictMode failureMode)     // don't worry, the parameterless version you know calls this one...
    {
        var changeSet = GetChangeSet();

        foreach (object insert in changeSet.Inserts)
        {
            // set LastUpdate property
        }
        foreach (object update in changeSet.Updates)
        {
            // set LastUpdate property
        }
        base.SubmitChanges();
    }
        public override void SubmitChanges(ConflictMode failureMode)
        {
            if (FlagFixtures == false)
            {

                // #region audited Department information
                // this.AuditInsert<LINQ.Department>(p => p.DepartmentId, "Department Added");
                // t/his.AuditUpdate<LINQ.Department>(p => p.DepartmentId, "Department Modified");
                //this.AuditDelete<LINQ.Department>(p => p.DepartmentId, "Department Deleted");
                //#endregion

            }
            base.SubmitChanges(failureMode);
        }
예제 #19
0
    public override void SubmitChanges(ConflictMode failureMode)
    {
        ChangeSet cs = base.GetChangeSet();

        foreach (object e in cs.Updates.Union(cs.Inserts))
        {
            if (typeof(IAuditable).IsAssignableFrom(e))
            {
                string tempValue = String.Format("{0}|{1}", ((IAuditable)e).UpdatedBy, DateTime.Ticks);
                ((IAuditable)e).UpdatedBy = tempValue;
                base.SubmitChanges(failureMode);
                ((IAuditable)e).UpdatedBy = tempValue.Substring(0, tempValue.LastIndexOf('|'));
                base.SubmitChanges(failureMode);
            }
        }
    }
예제 #20
0
 private void Commit(TContext context, ConflictMode conflictMode, bool systemUpdate)
 {
     if (conflictMode == ConflictMode.ContinueOnConflict)
     {
         try
         {
             context.SubmitChanges(conflictMode);
         }
         catch (ChangeConflictException)
         {
             OnChangeConflict(context.ChangeConflicts);
         }
     }
     else
     {
         context.SubmitChanges(conflictMode, systemUpdate);
     }
 }
예제 #21
0
 public static WxDatabaseMigrateJsonResult DatabaseMigrateImport(string accessTokenOrAppId, string env, string collection, string file_path, FileType file_type, bool stop_on_error,
                                                                 ConflictMode conflict_mode, int timeOut = Config.TIME_OUT)
 {
     return(WxOpenApiHandlerWapper.TryCommonApi(accessToken =>
     {
         string urlFormat = Config.ApiMpHost + "/tcb/databasemigrateimport?access_token={0}";
         var postBody = new
         {
             env,
             collection,
             file_path,
             file_type,
             stop_on_error,
             conflict_mode
         };
         return CommonJsonSend.Send <WxDatabaseMigrateJsonResult>(accessToken, urlFormat, postBody, timeOut: timeOut);
     }, accessTokenOrAppId));
 }
예제 #22
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            // get the changed entities before submitting the changes
            var changedEntities = GetChangeSet();

            base.SubmitChanges(failureMode);

            var allChanged = changedEntities.Inserts.Union(changedEntities.Updates);

            foreach (var entity in allChanged.Where(e => ((BaseEntity)e).Messages.Any()))
            {
                var baseEntity = ((BaseEntity)entity);
                foreach (var message in baseEntity.Messages)
                {
                    Logger.Instance.WriteLog(message);
                }
            }
        }
예제 #23
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            ProcessChanges();

            try
            {
                base.SubmitChanges(failureMode);
            }
            //catch(System.Data.SqlClient.SqlException sqlEx) {
            //    string s = sqlEx.Message;
            //}


            catch (ChangeConflictException e)
            {
                string s = e.Message;
                switch (failureMode)
                {
                case ConflictMode.ContinueOnConflict:
                    foreach (ObjectChangeConflict cc in this.ChangeConflicts)
                    {
                        cc.Resolve(RefreshMode.KeepChanges);
                    }
                    break;

                case ConflictMode.FailOnFirstConflict:
                    foreach (ObjectChangeConflict cc in this.ChangeConflicts)
                    {
                        //cc.Resolve(RefreshMode.KeepCurrentValues);
                        cc.Resolve(RefreshMode.KeepChanges);
                    }
                    break;

                default:
                    foreach (ObjectChangeConflict cc in this.ChangeConflicts)
                    {
                        cc.Resolve(RefreshMode.OverwriteCurrentValues);
                    }
                    break;
                }
            }

            CallPostSubmitChangesMethods();
        }
예제 #24
0
        public void SaveEntityNow(TEntity entity, ConflictMode conflictMode = ConflictMode.FailOnFirstConflict, bool systemUpdate = false)
        {
            if (entity == null)
            {
                return;
            }

            using (TContext context = CreateContext(CrossSite))
            {
                EntityList <TEntity> list = context.GetList <TEntity>(ListName);
                OnSaveEntity(context, list, entity);
                Commit(context, conflictMode, systemUpdate);
            }

            if (!this.Context.IsAttached(entity, ListName))
            {
                this.List.Attach(entity);
            }
        }
예제 #25
0
    public override void SubmitChanges(ConflictMode failureMode)
    {
        var invalidResults = (
            from entity in this.GetChangedEntities()
            let type = entity.GetType()
                       let validator = ValidationFactory.CreateValidator(type)
                                       let results = validator.Validate(entity)
                                                     where !results.IsValid
                                                     from result in results
                                                     select result).ToArray();

        if (invalidResults.Length > 0)
        {
            // You should define this exception type
            throw new ValidationException(invalidResults);
        }

        base.SubmitChanges(failureMode);
    }
예제 #26
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     ChangeSet cs = base.GetChangeSet();
     foreach (object e in cs.Updates.Union(cs.Inserts))
     {
         PropertyInfo updatedBy = e.GetType()
             .GetProperties()
             .FirstOrDefault(p => p.Name == "UpdatedBy");
         if (updatedBy == null)
         {
             base.SubmitChanges(failureMode);
             return;
         }
         string updatedByValue = updatedBy.GetValue(e, null);
         string tempValue = String.Format("{0}|{1}", updatedByValue, DateTime.Ticks;
         updatedBy.SetValue(e, tempValue);
         base.SubmitChanges(failureMode);
            
         updatedBy.SetValue(e, tempValue.Substring(0, tempValue.LastIndexOf('|')));
         base.SubmitChanges(failureMode);
     }
 }
예제 #27
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            try
            {
                this.Audit<Contract>(c => c.ContractId);
                this.Audit<Account>(a => a.AccountId);
                this.Audit<Company>(c => c.CompanyId);
                this.Audit<Contact>(c => c.ContactId);
                this.Audit<Network>(n => n.NetworkId);
                this.Audit<NetworkTariff>(nt => nt.NetworkTariffId);
                this.Audit<Plan>(p => p.PlanId);
                this.Audit<Tariff>(t => t.TariffId);
                this.Audit<Agent>(a => a.AgentId);

                base.SubmitChanges(failureMode);
            }
            catch (Exception ex)
            {
                LoggingUtility.LogException(ex);
                throw;
            }
        }
예제 #28
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            // Get the entities that are to be inserted / updated / deleted
            ChangeSet changeSet = GetChangeSet();

            // Get a single list of all the entities in the change set
            IEnumerable<object> changeSetEntities = changeSet.Deletes;
            changeSetEntities = changeSetEntities.Union(changeSet.Inserts);
            changeSetEntities = changeSetEntities.Union(changeSet.Updates);

            // Get a single list of all the enitities that inherit from EntityBase
            IEnumerable<ChangeEntity> entities =
                 from entity in changeSetEntities.Cast<EntityBase>()
                 select new ChangeEntity()
                 {
                     ChangeAction =
                          changeSet.Deletes.Contains(entity) ? ChangeAction.Delete
                        : changeSet.Inserts.Contains(entity) ? ChangeAction.Insert
                        : changeSet.Updates.Contains(entity) ? ChangeAction.Update
                        : ChangeAction.None,
                     Entity = entity as EntityBase
                 };

            // "Raise" the OnSaving event for the entities 
            foreach (ChangeEntity entity in entities)
            {
                entity.Entity.OnSaving(entity.ChangeAction);
            }

            // Save the changes
            base.SubmitChanges(failureMode);

            // "Raise" the OnSaved event for the entities
            foreach (ChangeEntity entity in entities)
            {
                entity.Entity.OnSaved();
            }
        }
예제 #29
0
        /// <summary>
        /// Submits the changes to the database: executes Insert, Update and Delete queries based on the changes found in the tracked entities.
        /// </summary>
        /// <param name="failureMode">The failure mode.</param>
        internal void SubmitChanges(ConflictMode failureMode)
        {
            this.TrackUntrackedObjects();
            // Must apply inferred deletions only after any untracked objects
            // are tracked
            this.ApplyInferredDeletions();
            this.BuildEdgeMaps();

            var list = this.GetOrderedList();

            ValidateAll(list);

            int numUpdatesAttempted = 0;
            ChangeConflictSession       conflictSession    = new ChangeConflictSession(this._context);
            List <ObjectChangeConflict> conflicts          = new List <ObjectChangeConflict>();
            List <TrackedObject>        deletedItems       = new List <TrackedObject>();
            List <TrackedObject>        insertedItems      = new List <TrackedObject>();
            List <TrackedObject>        syncDependentItems = new List <TrackedObject>();

            foreach (TrackedObject item in list)
            {
                try
                {
                    if (item.IsNew)
                    {
                        if (item.SynchDependentData())
                        {
                            syncDependentItems.Add(item);
                        }
                        _changeDirector.Insert(item);
                        // store all inserted items for post processing
                        insertedItems.Add(item);
                    }
                    else if (item.IsDeleted)
                    {
                        // Delete returns 1 if the delete was successfull, 0 if the row exists
                        // but wasn't deleted due to an OC conflict, or -1 if the row was
                        // deleted by another context (no OC conflict in this case)
                        numUpdatesAttempted++;
                        int ret = _changeDirector.Delete(item);
                        if (ret == 0)
                        {
                            conflicts.Add(new ObjectChangeConflict(conflictSession, item, false));
                        }
                        else
                        {
                            // store all deleted items for post processing
                            deletedItems.Add(item);
                        }
                    }
                    else if (item.IsPossiblyModified)
                    {
                        if (item.SynchDependentData())
                        {
                            syncDependentItems.Add(item);
                        }
                        if (item.IsModified)
                        {
                            CheckForInvalidChanges(item);
                            numUpdatesAttempted++;
                            if (_changeDirector.Update(item) <= 0)
                            {
                                conflicts.Add(new ObjectChangeConflict(conflictSession, item));
                            }
                        }
                    }
                }
                catch (ChangeConflictException)
                {
                    conflicts.Add(new ObjectChangeConflict(conflictSession, item));
                }
                if (conflicts.Count > 0 && failureMode == ConflictMode.FailOnFirstConflict)
                {
                    break;
                }
            }

            // if we have accumulated any failed updates, throw the exception now
            if (conflicts.Count > 0)
            {
                // First we need to rollback any value that have already been auto-[....]'d, since the values are no longer valid on the server
                _changeDirector.RollbackAutoSync();
                // Also rollback any dependent items that were [....]'d, since their parent values may have been rolled back
                foreach (TrackedObject syncDependentItem in syncDependentItems)
                {
                    Debug.Assert(syncDependentItem.IsNew || syncDependentItem.IsPossiblyModified, "SynchDependent data should only be rolled back for new and modified objects.");
                    syncDependentItem.SynchDependentData();
                }
                this._context.ChangeConflicts.Fill(conflicts);
                throw CreateChangeConflictException(numUpdatesAttempted, conflicts.Count);
            }
            else
            {
                // No conflicts occurred, so we don't need to save the rollback values anymore
                _changeDirector.ClearAutoSyncRollback();
            }

            // Only after all updates have been sucessfully processed do we want to make
            // post processing modifications to the objects and/or cache state.
            PostProcessUpdates(insertedItems, deletedItems);
        }
예제 #30
0
        internal void SubmitChanges(ConflictMode failureMode) {
            this.TrackUntrackedObjects();
            // Must apply inferred deletions only after any untracked objects
            // are tracked
            this.ApplyInferredDeletions();
            this.BuildEdgeMaps();

            var list = this.GetOrderedList();

            ValidateAll(list);

            int numUpdatesAttempted = 0;
            ChangeConflictSession conflictSession = new ChangeConflictSession(this.context);
            List<ObjectChangeConflict> conflicts = new List<ObjectChangeConflict>();
            List<TrackedObject> deletedItems = new List<TrackedObject>();
            List<TrackedObject> insertedItems = new List<TrackedObject>();
            List<TrackedObject> syncDependentItems = new List<TrackedObject>();
            
            foreach (TrackedObject item in list) {
                try {
                    if (item.IsNew) {
                        if (item.SynchDependentData()) {
                            syncDependentItems.Add(item);
                        }
                        changeDirector.Insert(item);
                        // store all inserted items for post processing
                        insertedItems.Add(item);
                    }
                    else if (item.IsDeleted) {
                        // Delete returns 1 if the delete was successfull, 0 if the row exists
                        // but wasn't deleted due to an OC conflict, or -1 if the row was
                        // deleted by another context (no OC conflict in this case)
                        numUpdatesAttempted++;
                        int ret = changeDirector.Delete(item);
                        if (ret == 0) {
                            conflicts.Add(new ObjectChangeConflict(conflictSession, item, false));
                        }
                        else {
                            // store all deleted items for post processing
                            deletedItems.Add(item);
                        }
                    }
                    else if (item.IsPossiblyModified) {
                        if (item.SynchDependentData()) {
                            syncDependentItems.Add(item);
                        }
                        if (item.IsModified) {
                            CheckForInvalidChanges(item);
                            numUpdatesAttempted++;
                            if (changeDirector.Update(item) <= 0) {
                                conflicts.Add(new ObjectChangeConflict(conflictSession, item));
                            }
                        }
                    }
                }
                catch (ChangeConflictException) {
                    conflicts.Add(new ObjectChangeConflict(conflictSession, item));
                }
                if (conflicts.Count > 0 && failureMode == ConflictMode.FailOnFirstConflict) {
                    break;
                }
            }

            // if we have accumulated any failed updates, throw the exception now
            if (conflicts.Count > 0) {
                // First we need to rollback any value that have already been auto-[....]'d, since the values are no longer valid on the server
                changeDirector.RollbackAutoSync();
                // Also rollback any dependent items that were [....]'d, since their parent values may have been rolled back
                foreach (TrackedObject syncDependentItem in syncDependentItems) {
                    Debug.Assert(syncDependentItem.IsNew || syncDependentItem.IsPossiblyModified, "SynchDependent data should only be rolled back for new and modified objects.");
                    syncDependentItem.SynchDependentData();
                }
                this.context.ChangeConflicts.Fill(conflicts);
                throw CreateChangeConflictException(numUpdatesAttempted, conflicts.Count);
            }
            else {
                // No conflicts occurred, so we don't need to save the rollback values anymore
                changeDirector.ClearAutoSyncRollback();
            }

            // Only after all updates have been sucessfully processed do we want to make
            // post processing modifications to the objects and/or cache state.
            PostProcessUpdates(insertedItems, deletedItems);
        }
예제 #31
0
        public override void SubmitChanges(ConflictMode failureMode)
        {
            if (_Busy)
                return; // no action & no error; just let this SubmitChanges handle all nested submissions.
            try {
                _Busy = true;
                BeginTransaction();
                // Before doing anything, notify objects of the impending changes...
                Dictionary<LinqedTable, bool> ltUpdates = new Dictionary<LinqedTable, bool>();
                Dictionary<LinqedTable, bool> ltInserts = new Dictionary<LinqedTable, bool>();
                Dictionary<LinqedTable, bool> ltDeletes = new Dictionary<LinqedTable, bool>();

                var changeSet = GetChangeSet();
                SynchronizeChanges(ltUpdates, changeSet.Updates);
                SynchronizeChanges(ltInserts, changeSet.Inserts);
                SynchronizeChanges(ltDeletes, changeSet.Deletes);

                while (ltInserts.Any(i => i.Value == false) || ltUpdates.Any(u => u.Value == false) || ltDeletes.Any(d => d.Value == false)) {
                    List<LinqedTable> tmp = ltInserts.Where(i => i.Value == false).Select(i => i.Key).ToList();
                    foreach (LinqedTable lt in tmp) {
                        lt.BeforeInsert();
                        ltInserts[lt] = true;
                        // auto-audit happens after the save, so that we can get the generated ID value
                    }
                    tmp = ltUpdates.Where(u => u.Value == false).Select(u => u.Key).ToList();
                    foreach (LinqedTable lt in tmp) {
                        lt.BeforeUpdate();
                        ltUpdates[lt] = true;
                        if (lt.AutoAudit) {
                            LinqedTable orig = (LinqedTable)GetTable(lt.GetType()).GetOriginalEntityState(lt);
                            AuditHeaderBase ah = GetNewAuditHeader();
                            ah.MyDataID = lt.IDValue;
                            ah.MyEventDescription = "Update";
                            ah.MyDataType = lt.GetType().Name;
                            foreach (PropertyInfo prop in LinqedTable.GetProperties(lt.GetType()).Values) {
                                object OldValue = prop.GetValue(orig, null);
                                object NewValue = prop.GetValue(lt, null);
                                if ((OldValue == null ^ NewValue == null) || (OldValue != null && NewValue != null && !OldValue.Equals(NewValue))) {
                                    AuditDetailBase ad = GetNewAuditDetail(ah);
                                    ad.MyField = prop.Name;
                                    ad.MyOldValue = DataUtils.BlankIfNull(OldValue).ToString();
                                    ad.MyNewValue = DataUtils.BlankIfNull(NewValue).ToString();
                                }
                            }
                        }
                    }
                    tmp = ltDeletes.Where(d => d.Value == false).Select(d => d.Key).ToList();
                    foreach (LinqedTable lt in tmp) {
                        lt.BeforeDelete();
                        ltDeletes[lt] = true;
                        if (lt.AutoAudit) {
                            LinqedTable orig = (LinqedTable)GetTable(lt.GetType()).GetOriginalEntityState(lt);
                            AuditHeaderBase ah = GetNewAuditHeader();
                            ah.MyDataID = lt.IDValue;
                            ah.MyEventDescription = "Delete";
                            ah.MyDataType = lt.GetType().Name;
                            foreach (PropertyInfo prop in LinqedTable.GetProperties(lt.GetType()).Values) {
                                AuditDetailBase ad = GetNewAuditDetail(ah);
                                ad.MyField = prop.Name;
                                ad.MyOldValue = DataUtils.BlankIfNull(prop.GetValue(orig, null)).ToString();
                            }
                        }
                    }
                    // before allowing us to proceed with the SubmitChanges, make sure that any LinqedTables with triggered changes also get BeforeUpdate() called.
                    changeSet = GetChangeSet();
                    SynchronizeChanges(ltUpdates, changeSet.Updates);
                    SynchronizeChanges(ltInserts, changeSet.Inserts);
                    SynchronizeChanges(ltDeletes, changeSet.Deletes);
                }
                // now submit the changes...
                try {
                    base.SubmitChanges(ConflictMode.ContinueOnConflict);
                } catch (ChangeConflictException) {
                    // Automerge database values for members that client
                    // has not modified.
                    foreach (ObjectChangeConflict occ in ChangeConflicts) {
                        var mc = occ.MemberConflicts.ToList();

                        occ.Resolve(RefreshMode.KeepChanges);
                    }
                }
                // Submit succeeds on second try.
                base.SubmitChanges(ConflictMode.FailOnFirstConflict);
                // ... and notify the child objects that they've been acted upon
                foreach (LinqedTable lt in ltInserts.Keys) {
                    lt.AfterInsert();
                    lt.RaiseSavedEvent();
                    if (lt.AutoAudit) {
                        AuditHeaderBase ah = GetNewAuditHeader();
                        ah.MyDataID = lt.IDValue;
                        ah.MyEventDescription = "Insert";
                        ah.MyDataType = lt.GetType().Name;
                        foreach (PropertyInfo prop in LinqedTable.GetProperties(lt.GetType()).Values) {
                            AuditDetailBase ad = GetNewAuditDetail(ah);
                            ad.MyField = prop.Name;
                            ad.MyNewValue = DataUtils.BlankIfNull(prop.GetValue(lt, null)).ToString();
                        }
                    }
                }
                foreach (LinqedTable lt in ltUpdates.Keys) {
                    lt.AfterUpdate();
                    lt.RaiseSavedEvent();
                }
                foreach (LinqedTable lt in ltDeletes.Keys) {
                    lt.AfterDelete();
                    lt.RaiseDeletedEvent();
                }
                CommitTransaction();
            } catch {
                RollbackTransaction();
                throw;
            } finally {
                _Busy = false;
            }
            // now, just in case any of the After... functions triggered a change:
            var cs = GetChangeSet();
            if (cs.Deletes.Count + cs.Inserts.Count + cs.Updates.Count > 0)
                SubmitChanges();
        }
예제 #32
0
        /// <summary>
        /// Add additional bcf info into the existing database
        /// </summary>
        /// <param name="bcfPath"></param>
        /// <returns></returns>
        public bool AddBCF(string bcfPath)
        {
            bool added = false;

            try
            {
                TaskDialogOption selectedOption = TaskDialogOption.NONE;
                var bcfExisting = from bcf in bcfFiles where bcf.ZipFilePath == bcfPath select bcf;
                if (bcfExisting.Count() > 0)
                {
                    TaskDialogWindow dialogWindow = new TaskDialogWindow("\"" + bcfPath + "\" already exists in the database.\nDo you want to replace it?");
                    if ((bool)dialogWindow.ShowDialog())
                    {
                        selectedOption = dialogWindow.SelectedOption;
                        switch (selectedOption)
                        {
                        case TaskDialogOption.REPLACE:
                            BCFZIP existingBCF = bcfExisting.First();
                            bool   deleted     = BCFDBWriter.BCFDBWriter.DeleteBCF(existingBCF);
                            if (deleted)
                            {
                                this.BCFFiles.Remove(existingBCF);
                            }
                            break;

                        case TaskDialogOption.MERGE:
                            break;

                        case TaskDialogOption.IGNORE:
                            return(false);

                        case TaskDialogOption.NONE:
                            return(false);
                        }
                    }
                }

                BCFZIP bcfzip = BCFReader.BCFReader.Read(bcfPath);
                if (bcfzip.Markups.Count > 0)
                {
                    ConflictMode mode = ConflictMode.IGNORE;
                    if (selectedOption == TaskDialogOption.MERGE)
                    {
                        int index = bcfFiles.IndexOf(bcfExisting.First());
                        if (index > -1)
                        {
                            BCFZIP mergedBCF = BCFDBWriter.BCFDBWriter.MergeDatabase(bcfzip, bcfFiles[index]);
                            if (null != mergedBCF)
                            {
                                this.BCFFiles[index] = mergedBCF;
                            }
                        }
                    }
                    else
                    {
                        bool written = BCFDBWriter.BCFDBWriter.WriteDatabase(bcfzip, mode);
                        if (written)
                        {
                            bcfzip.IsPrimary = false;
                            this.BCFFiles.Add(bcfzip);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to add BCF into the connected database.\n" + ex.Message, "Add BCF", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(added);
        }
예제 #33
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     try
     {
         base.SubmitChanges(failureMode);
     }
     catch (Exception ex)
     {
         log.Error("SubmitChanges is FAILED", ex);
     }
 }
예제 #34
0
        /// <summary>
        /// Function (overriden version of SubmitChanges) that notifies all child entities about it's change.
        /// </summary>
        /// <param name="failureMode"></param>
        public override void SubmitChanges(ConflictMode failureMode)
        {
            // Get the entities that are to be inserted / updated / deleted
            ChangeSet changeSet = GetChangeSet();

            // Get a single list of all the entities in the change set
            IEnumerable<object> changeSetEntities = changeSet.Deletes;
            changeSetEntities = changeSetEntities.Union(changeSet.Inserts);
            changeSetEntities = changeSetEntities.Union(changeSet.Updates);

            // Get a single list of all the enitities that inherit from EntityBase
            IEnumerable<ChangeEntity> entities =
                 from entity in changeSetEntities.Cast<EntityBase>()
                 select new ChangeEntity()
                 {
                     ChangeAction =
                          changeSet.Deletes.Contains(entity) ? ChangeAction.Delete
                        : changeSet.Inserts.Contains(entity) ? ChangeAction.Insert
                        : changeSet.Updates.Contains(entity) ? ChangeAction.Update
                        : ChangeAction.None,
                     Entity = entity as EntityBase
                 };

            // "Raise" the OnSaving event for the entities
            foreach (ChangeEntity entity in entities)
            {
                entity.Entity.OnSaving(entity.ChangeAction);
            }

            // Save the changes
            try
            {
                base.SubmitChanges(failureMode);
            }
            catch (ChangeConflictException ex)
            {
                trace.Value.TraceEvent(TraceEventType.Error, 0, "Optimistic concurrency error during Database.SubmitChanges(). Conflicting fiels: " + string.Join(", ", ChangeConflicts[0].MemberConflicts.Select(X => X.Member.Name).ToList()));

                /*
                foreach (ObjectChangeConflict changeConflict in base.ChangeConflicts)
                {
                    System.Data.Linq.Mapping.MetaTable metatable = base.Mapping.GetTable(changeConflict.Object.GetType());
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("Table name: {0}", metatable.TableName);
                    sb.AppendLine();

                    foreach (MemberChangeConflict col in changeConflict.MemberConflicts)
                    {
                        sb.AppendFormat("Column name :    {0}", col.Member.Name); sb.AppendLine();
                        if (col.Member.Name == "SpectrumYByte") { sb.AppendFormat("Original value : skipped"); sb.AppendLine(); sb.AppendFormat("Current value :  skipped"); sb.AppendLine(); sb.AppendFormat("Database value : skipped"); sb.AppendLine(); sb.AppendLine(); continue; }
                        sb.AppendFormat("Original value : {0}", col.OriginalValue.ToString()); sb.AppendLine();
                        sb.AppendFormat("Current value :  {0}", col.CurrentValue.ToString()); sb.AppendLine();
                        sb.AppendFormat("Database value : {0}", col.DatabaseValue.ToString()); sb.AppendLine(); sb.AppendLine();
                    }
                    Console.WriteLine(sb);
                    //changeConflict.Resolve(RefreshMode.KeepCurrentValues);
                }
                */

                base.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                this.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            // "Raise" the OnSaved event for the entities
            foreach (ChangeEntity entity in entities)
            {
                entity.Entity.OnSaved(entity.ChangeAction);
            }
        }
예제 #35
0
 /// <summary>
 /// Persists, to the content database, changes made by the current user to one
 /// or more lists using the specified failure mode and the specified indication
 /// of whether the versions of changed list items should be incremented; or,
 /// if a concurrency conflict is found, populates the Microsoft.SharePoint.Linq.DataContext.ChangeConflicts
 /// property.
 /// </summary>
 /// <param name="failureMode">A value that specifies when a concurrency conflict should stop the attempt
 /// to persist changes and roll back any changes already made.</param>
 /// <param name="systemUpdate">if set to true [system update].</param>
 /// <exception cref="System.NotImplementedException">Microsoft.SharePoint.Linq.DataContext.ObjectTrackingEnabled is false- or
 ///     -At least one conflict in Microsoft.SharePoint.Linq.DataContext.ChangeConflicts
 ///     from the last time Overload:Microsoft.SharePoint.Linq.DataContext.SubmitChanges
 ///     was called is not yet resolved.</exception>
 public void SubmitChanges(ConflictMode failureMode, bool systemUpdate)
 {
     throw new NotImplementedException();
 }
예제 #36
0
    public override void SubmitChanges(ConflictMode failureMode)
    {
        this.EmptyNullProperties();

        base.SubmitChanges(failureMode);
    }
        /// <summary>
        /// Sends changes that were made to retrieved objects to the underlying database, and specifies the action to be taken if the submission fails.
        /// </summary>
        /// <param name="failureMode">The action to be taken if the submission fails.</param>
        public override void SubmitChanges(ConflictMode failureMode)
        {
            ChangeSet changeSet = this.GetChangeSet();
            IEnumerable<object> entities = changeSet.Inserts.Union(changeSet.Updates);

            using (ValidationScope validationScope = new ValidationScope())
            {
                foreach (object entity in entities)
                {
                    IExtensionObject extensionObject = entity as IExtensionObject;
                    if (extensionObject != null && (extensionObject.HasChanged || extensionObject.ExtensionData == null))
                    {
                        IExtensionObjectSerializer serializer = SpringContext.Current.GetObject<IExtensionObjectSerializer>();
                        serializer.Serialize(extensionObject);
                    }
                }
            }

            base.SubmitChanges(failureMode);
        }
			public override void SubmitChanges(ConflictMode failureMode) 
			{
				ChangesSubmitted = true;
			}
예제 #39
0
 public override void SubmitChanges(ConflictMode failureMode)
 {
     EntityValidator.Validate(this.GetChangedEntities());
     base.SubmitChanges(failureMode);
 }