Exemplo n.º 1
0
        public virtual XElement Write(IConceptUsecase usecase)
        {
            var result = new XElement(NodeNames.Usecase);

            result.Add(new MeshXmlSerializer().Write(Mesh));

            var splitView = new XElement(NodeNames.SplitView);
            var displays  = new XElement(NodeNames.Displays);

            Action <IGraphSceneDisplay <IVisual, IVisualEdge>, string> writeSplitDisplays = (d, n) => {
                BeforeSave?.Invoke(d, n);
                var display = new XElement(GraphSceneDisplayXmlSerializer.NodeNames.Display);
                display.Add(Write(NodeNames.Name, n));
                display.Add(Write(SceneInfoXmlSerializer.NodeNames.Id, d.DataId.ToString("X")));
                displays.Add(display);
            };

            writeSplitDisplays(usecase.SplitView.Display1, NodeNames.SplitViewDisplay1);
            writeSplitDisplays(usecase.SplitView.Display2, NodeNames.SplitViewDisplay2);

            splitView.Add(displays);
            result.Add(splitView);

            var favorites = new XElement(NodeNames.Favorites);

            favorites.Add(Write(NodeNames.HomeId, usecase.FavoriteManager.HomeId.ToString("X")));
            result.Add(favorites);

            return(result);
        }
Exemplo n.º 2
0
 public bool Save()
 {
     // ---------------------------------------------------------
     // Save the contents of this apsim document to the specified
     // file - formatted nicely.
     // ---------------------------------------------------------
     if (!ReadOnly && RootComponent != null && FileName != "Untitled")
     {
         if (BeforeSave != null)
         {
             BeforeSave.Invoke();
         }
         XmlDocument doc      = new XmlDocument();
         XmlNode     RootNode = doc.AppendChild(doc.CreateElement(RootComponent.Type));
         XmlHelper.SetAttribute(RootNode, "version", APSIMChangeTool.CurrentVersion.ToString());
         XmlHelper.SetAttribute(RootNode, "creator", "Apsim " + Configuration.Instance.ApsimVersion() + "-" + Configuration.Instance.ApsimBuildNumber());
         RootComponent.Write(RootNode);
         try { doc.Save(FileName); } //Win 7 - do not allow saving to Program Files directory
         catch (Exception e)
         {
             if (!FileName.Contains("UserInterface")) //do not try to save files in UserInterface directory as it's write protected in the default install (old versions of APSIM toolboxes will try to do this).
             {
                 System.Windows.Forms.MessageBox.Show("Error: " + e.Message + " Try saving in a different location.");
             }
             return(false);
         }
         Dirty = true;
         SetDirty(false);
         return(true);
     }
     return(false);
 }
Exemplo n.º 3
0
 public void invoke_BeforeSave(object sender, EventArgs args)
 {
     if (BeforeSave != null)
     {
         BeforeSave.Invoke(sender, args);
     }
 }
Exemplo n.º 4
0
 public virtual int Commit()
 {
     BeforeSave?.Invoke(this, new Interceptors.Events.BeforeSave());
     ProcessCommitQueues();
     repo.Commit();
     AfterSave?.Invoke(this, new Interceptors.Events.AfterSave());
     return(0);
 }
Exemplo n.º 5
0
        public int Commit()
        {
            BeforeSave?.Invoke(this, new BeforeSave());
            var changes = this.SaveChanges();

            AfterSave?.Invoke(this, new AfterSave());
            return(changes);
        }
Exemplo n.º 6
0
 public Task <int> CommitAsync()
 {
     BeforeSave?.Invoke(this, new BeforeSave());
     return(this.SaveChangesAsync().ContinueWith(task => {
         AfterSave?.Invoke(this, new AfterSave());
         return task.Result;
     }));
 }
Exemplo n.º 7
0
 public void ClearAndSave()
 {
     BeforeSave?.Invoke();
     currentData = new Dictionary <string, object>();
     Serializer.SerializeData(currentData, fileName, folderName);
     Debug.Log(debugPrefix + "Cleared " + currentData.Count + " entries in " + Path.Combine(Application.persistentDataPath, folderName) + " in " + fileName);
     AfterSave?.Invoke();
 }
Exemplo n.º 8
0
        protected virtual void OnBeforeSave(BeforeSave e)
        {
            EventHandler <BeforeSave> handler = BeforeSave;

            if (handler != null)
            {
                handler(this, e);
            }
        }
        protected virtual void OnBeforeSave(BeforeSave e)
        {
            var handler = BeforeSave;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///     Commits all currently tracked entity changes asynchronously
        /// </summary>
        /// <returns>the number of rows affected</returns>
        public virtual Task <int> CommitAsync()
        {
            _log.Trace("\tCommit");
            BeforeSave?.Invoke(this, new Interceptors.Events.BeforeSave());
            ChangeTracker.DetectChanges();
            Task <int> result = SaveChangesAsync();

            AfterSave?.Invoke(this, new Interceptors.Events.AfterSave());
            result.ContinueWith(x => _log.DebugFormat("\tCommited {0} Changes", result));
            return(result);
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Commits all currently tracked entity changes
        /// </summary>
        /// <returns>the number of rows affected</returns>
        public virtual int Commit()
        {
            _log.Trace("\tCommit");
            BeforeSave?.Invoke(this, new Interceptors.Events.BeforeSave());
            ChangeTracker.DetectChanges();
            int result = SaveChanges();

            AfterSave?.Invoke(this, new Interceptors.Events.AfterSave());
            _log.DebugFormat("\tCommited {0} Changes", result);
            return(result);
        }
Exemplo n.º 12
0
        private void HandleEvent(object sender, BeforeSave e)
        {
            var events = _interceptors.OfType <IEventInterceptor <BeforeSave> >().OrderBy(x => x.Priority);

            foreach (var eventInterceptor in events)
            {
                var result = eventInterceptor.Apply(_repository.DomainContext, e);
                if (!result.ContinueExecution)
                {
                    break;
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Handles the command provided to the method, will update the DbSet based on the EntitySet provided in the command.
        /// This overload allows to supply own transaction reference.
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="tx"></param>
        /// <returns></returns>
        public UpdateEntityCommand <T> Handle(UpdateEntityCommand <T> cmd, DbContextTransaction tx)
        {
            var item = db.Set(cmd.EntityType).Find(cmd.Id);

            if (item == null)
            {
                throw new NullReferenceException("Resource not found");
            }

            var version = DefaultVersion;

            try
            {
                var original = UpdateEntity(cmd, item);
                version = UpdateVersion(item as IHaveVersion, DefaultVersion);
                BeforeSave?.Invoke(this, new BeforeSaveEventArgs <T, TContext>
                {
                    Context  = db,
                    Command  = cmd,
                    Original = original.From,
                    Version  = version
                });
                db.SaveChanges();

                tx.Commit();
                return(cmd);
            }
            catch (DbEntityValidationException ex)
            {
                tx.Rollback();
                DbEntityValidationException?.Invoke(this, new DbEntityValidationExceptionEventArgs <T>(cmd, ex, version));
                throw;
            }
            catch (Exception ex)
            {
                tx.Rollback();
                Exception?.Invoke(this, new ExceptionEventArgs <T>(cmd, ex, version));
                throw;
            }
            finally
            {
                Complete?.Invoke(this, new EntityUpdatedEventArgs <T>
                {
                    Command = cmd,
                    Version = version
                });
            }
        }
Exemplo n.º 14
0
 IObservable <UnityWebRequest> DoDownload(IProgress <float> progress) => Observable.Defer(() =>
 {
     string tempPath         = TempPath ?? SavePath + ".tmp";
     var request             = new UnityWebRequest(Url);
     var handler             = new DownloadHandlerFile(tempPath);
     request.downloadHandler = handler;
     return(request.SendAsObservable(progress).Do(req =>
     {
         req.downloadHandler.Dispose();
         BeforeSave?.Invoke(new CallbackParam(this, req));
         File.Delete(SavePath);
         File.Move(tempPath, SavePath);
         AfterSave?.Invoke(new CallbackParam(this, req));
         OnDownloaded(req);
     }));
 });
Exemplo n.º 15
0
        /// <summary>
        /// 新增对象
        /// </summary>
        /// <param name="t"></param>
        public void Add(T t)
        {
            if (!CheckValidName(t))
            {
                throw new JException(t.Name + "的名称重复。");
            }

            BeforeSave?.Invoke(t);
            if (Provider.Add(t) > 0)
            {
                DataList.Add(t);
                AfterSaved?.Invoke(t);
            }
            if (t.Id == null)
            {
                throw new JException("ID is empty");
                //t.Id = CreateId();
            }
        }
Exemplo n.º 16
0
        /// <param name="sameRecord">Compare key properties, determining the records that should be inserted or deleted.
        /// Typical implementation:
        /// <code>
        ///     class CompareName : IComparer&lt;ISomeEntity&gt;
        ///     {
        ///         public int Compare(ISomeEntity x, ISomeEntity y) { return string.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase); }
        ///     }
        /// </code></param>
        /// <param name="sameValue">Compare other properties, determining the records that should be updated.
        /// Comparison may also include key properties with stricter constraints (such as case sensitivity).
        /// Typical implementation:
        /// <code>(x, y) =&gt; x.Name == y.Name &amp;&amp; x.SomeValue == y.SomeValue;</code></param>
        /// <param name="filterLoad">For supported filters types see <see cref="Load{TParameter}(TParameter)"/> function.</param>
        /// <param name="assign">Typical implementation:
        /// <code>(destination, source) =&gt; {
        ///     destination.Property1 = source.Property1;
        ///     destination.Property2 = source.Property2; }</code></param>
        /// <param name="beforeSave"><code>(toInsert, toUpdate, toDelete) => { some code; } </code></param>
        public void InsertOrUpdateOrDelete(
            IEnumerable <TEntityInterface> newItems,
            IComparer <TEntityInterface> sameRecord,
            Func <TEntityInterface, TEntityInterface, bool> sameValue,
            object filterLoad,
            Action <TEntityInterface, TEntityInterface> assign,
            BeforeSave beforeSave = null)
        {
            var stopwatch = Stopwatch.StartNew();

            // Initialize new items:

            CsUtility.Materialize(ref newItems);
            _performanceLogger.Write(stopwatch, () => string.Format("{0}.InsertOrUpdateOrDelete: Initialize new items ({1})",
                                                                    _repositoryName, newItems.Count()));

            // Load old items:

            IEnumerable <TEntityInterface> oldItems = this.Load(filterLoad);

            _performanceLogger.Write(stopwatch, () => string.Format("{0}.InsertOrUpdateOrDelete: Load old items ({1})",
                                                                    _repositoryName, oldItems.Count()));

            // Compare new and old items:

            IEnumerable <TEntityInterface> toInsert, toUpdate, toDelete;

            Diff(oldItems, newItems, sameRecord, sameValue, assign, out toInsert, out toUpdate, out toDelete);
            _performanceLogger.Write(stopwatch, () => string.Format("{0}.InsertOrUpdateOrDelete: Diff ({1} new items, {2} old items, {3} to insert, {4} to update, {5} to delete)",
                                                                    _repositoryName, newItems.Count(), oldItems.Count(), toInsert.Count(), toUpdate.Count(), toDelete.Count()));

            // Modify old items to match new items:

            if (beforeSave != null)
            {
                beforeSave(ref toInsert, ref toUpdate, ref toDelete);
            }
            Save(toInsert, toUpdate, toDelete);
            _performanceLogger.Write(stopwatch, () => string.Format("{0}.InsertOrUpdateOrDelete: Save ({1} new items, {2} old items, {3} to insert, {4} to update, {5} to delete)",
                                                                    _repositoryName, newItems.Count(), oldItems.Count(), toInsert.Count(), toUpdate.Count(), toDelete.Count()));
        }
Exemplo n.º 17
0
        public virtual void Save()
        {
            gather();

            if (!executeValidations())
            {
                return;
            }

            beforeSave();

            BeforeSave?.Invoke();

            var result = _context.SaveChanges();

            afterSave();

            AfterSave?.Invoke();

            scatter();
        }
Exemplo n.º 18
0
        /// <summary>
        /// 修改对象
        /// </summary>
        /// <param name="t"></param>
        /// <returns>修改成功与否</returns>
        public bool Change(T t)
        {
            var old = DataList.FirstOrDefault(d => d.Id.Equals(t.Id));

            if (old == null)
            {
                throw new JException(t.Name + "Not found。");
            }
            old.Name = t.Name;
            if (!CheckValidName(old))
            {
                throw new JException(t.Name + " duplicated。");
            }

            BeforeSave?.Invoke(t);
            if (Provider.Change(t) > 0)
            {
                DataList[DataList.IndexOf(old)] = t;
                AfterSaved?.Invoke(t);
                return(true);
            }
            return(false);
        }
Exemplo n.º 19
0
        /// <param name="sameRecord">Compare key properties, determining the records that should be inserted or deleted.
        /// If set to null, the items will be compared by the ID property.
        /// Typical implementation:
        /// <code>
        ///     class CompareName : IComparer&lt;ISomeEntity&gt;
        ///     {
        ///         public int Compare(ISomeEntity x, ISomeEntity y) { return string.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase); }
        ///     }
        /// </code></param>
        /// <param name="sameValue">Compare other properties, determining the records that should be updated.
        /// Comparison may also include key properties with stricter constraints (such as case sensitivity).
        /// Typical implementation:
        /// <code>(x, y) =&gt; x.Name == y.Name &amp;&amp; x.SomeValue == y.SomeValue;</code></param>
        /// <param name="filterLoad">For supported filters types see <see cref="Load"/> function.</param>
        /// <param name="assign">Typical implementation:
        /// <code>(destination, source) =&gt; {
        ///     destination.Property1 == source.Property1;
        ///     destination.Property2 == source.Property2; }</code></param>
        /// <param name="filterDeactivateDeleted">A filter that selects items that should be deactivated instead of deleted.
        /// Typical implementation:
        /// <code>(Func&lt;IEntity, bool&gt;)(item =&gt; ItemsInUseHashSet.Contains(item.ID))</code>
        /// <br/>For supported filters types see <see cref="Filter"/> function.
        /// </param>
        /// <param name="beforeSave"><code>(toInsert, toUpdate, toDelete) => { some code; } </code></param>
        public void InsertOrUpdateOrDeleteOrDeactivate(
            IEnumerable <TEntityInterface> newItems,
            IComparer <TEntityInterface> sameRecord,
            Func <TEntityInterface, TEntityInterface, bool> sameValue,
            object filterLoad,
            Action <TEntityInterface, TEntityInterface> assign,
            object filterDeactivateDeleted,
            BeforeSave beforeSave = null)
        {
            var stopwatch = Stopwatch.StartNew();

            // Initialize new items:

            CsUtility.Materialize(ref newItems);
            foreach (var newItem in newItems.Cast <IDeactivatable>())
            {
                if (newItem.Active == null)
                {
                    newItem.Active = true;
                }
            }
            _performanceLogger.Write(stopwatch, () => $"InsertOrUpdateOrDeleteOrDeactivate: Initialize new items ({newItems.Count()})");

            // Load old items:

            IEnumerable <TEntityInterface> oldItems = this.Load(filterLoad);

            _performanceLogger.Write(stopwatch, () => $"InsertOrUpdateOrDeleteOrDeactivate: Load old items ({oldItems.Count()})");

            // Compare new and old items:

            IEnumerable <TEntityInterface> toInsert, toUpdate, toDelete;

            Diff(oldItems, newItems, sameRecord, sameValue, assign, out toInsert, out toUpdate, out toDelete);
            _performanceLogger.Write(stopwatch, () => $"InsertOrUpdateOrDeleteOrDeactivate: Diff ({newItems.Count()} new items, {oldItems.Count()} old items, {toInsert.Count()} to insert, {toUpdate.Count()} to update, {toDelete.Count()} to delete)");

            // Deactivate some items instead of deleting:

            IEnumerable <TEntityInterface> toDeactivate = Filter(toDelete, filterDeactivateDeleted);
            int activeToDeactivateCount = 0;

            if (toDeactivate.Any())
            {
                int oldDeleteCount = toDelete.Count();

                // Don't delete items that should be deactivated:
                if (toDeactivate.Count() == oldDeleteCount)
                {
                    toDelete = CreateList(0);
                }
                else
                {
                    var toDeactivateIndex = new HashSet <TEntityInterface>(toDeactivate, new InstanceComparer());
                    toDelete = Reflection.ToListOfEntity(toDelete.Where(item => !toDeactivateIndex.Contains(item)));
                }
                if (toDelete.Count() + toDeactivate.Count() != oldDeleteCount)
                {
                    throw new FrameworkException($"Invalid number of items to deactivate for '{_genericRepositoryName}'." +
                                                 $" Verify if the deactivation filter ({filterDeactivateDeleted.GetType().FullName}) on that data structure returns a valid subset of the given items." +
                                                 $" {oldDeleteCount} items to remove: {toDeactivate.Count()} items to deactivate and {toDelete.Count()} items remaining to delete (should be {oldDeleteCount - toDeactivate.Count()}).");
                }

                // Update the items to deactivate (unless already deactivated):
                var activeToDeactivate = toDeactivate.Cast <IDeactivatable>().Where(item => item.Active == null || item.Active == true).ToList();
                foreach (var item in activeToDeactivate)
                {
                    item.Active = false;
                }
                Reflection.AddRange(toUpdate, Reflection.CastAsEntity(activeToDeactivate));
                activeToDeactivateCount = activeToDeactivate.Count;
            }
            _performanceLogger.Write(stopwatch, () => $"InsertOrUpdateOrDeleteOrDeactivate: Deactivate ({activeToDeactivateCount} to deactivate, {toDeactivate.Count() - activeToDeactivateCount} already deactivated)");

            // Modify old items to match new items:

            if (beforeSave != null)
            {
                beforeSave(ref toInsert, ref toUpdate, ref toDelete);
                CsUtility.Materialize(ref toInsert);
                CsUtility.Materialize(ref toUpdate);
                CsUtility.Materialize(ref toDelete);
            }
            Save(toInsert, toUpdate, toDelete);
            _performanceLogger.Write(stopwatch, () => $"InsertOrUpdateOrDeleteOrDeactivate: Save ({newItems.Count()} new items, {oldItems.Count()} old items, {toInsert.Count()} to insert, {toUpdate.Count()} to update, {toDelete.Count()} to delete)");
        }
Exemplo n.º 20
0
 protected virtual void OnBeforeSave(BeforeSave e)
 {
     BeforeSave?.Invoke(this, e);
 }
Exemplo n.º 21
0
        public virtual TransactionResult Save(T entity, bool edit, string headerkeyvalue = null, bool useLog = true)
        {
            if (Context.Database.Connection.State != ConnectionState.Open)
            {
                Context.Database.Connection.Open();
            }

            TransactionScope scope = new TransactionScope();

            try
            {
                T o;
                if (Exists(entity))
                {
                    if (!edit)
                    {
                        return(TransactionResult.IsExists);
                    }
                    o = Find(entity);

                    if (entity.GetType().GetProperties().Any(p => p.Name.Equals("CreatedBy", StringComparison.OrdinalIgnoreCase)))
                    {
                        entity.SetValue("CreatedBy", o.GetValue("CreatedBy"));
                        entity.SetValue("CreatedAt", o.GetValue("CreatedAt"));
                        entity.SetValue("UpdatedBy", o.GetValue("UpdatedBy"));
                        entity.SetValue("UpdatedAt", o.GetValue("UpdatedAt"));
                    }

                    Context.Entry(o).CurrentValues.SetValues(entity);

                    if (Context.Entry(o).State == EntityState.Modified && entity.GetType().GetProperties().Any(p => p.Name.Equals("UpdatedBy", StringComparison.OrdinalIgnoreCase)))
                    {
                        //o.SetValue("UpdatedBy", _user.UserId.ToInt());
                        o.SetValue("UpdatedAt", DateTime.Now);
                    }
                }
                else
                {
                    if (entity.GetType().GetProperties().Any(p => p.Name.Equals("CreatedBy", StringComparison.OrdinalIgnoreCase)))
                    {
                        //entity.SetValue("CreatedBy", _user.UserId.ToInt());
                        entity.SetValue("CreatedAt", DateTime.Now);
                    }
                    Context.Entry(entity).State = EntityState.Added;
                    o = entity;
                }
                if (BeforeSave != null)
                {
                    var eventUseData = new EventUseData();
                    BeforeSave.Invoke(o, Context, eventUseData);
                    if (eventUseData.Cancel)
                    {
                        scope.Dispose();
                        return(eventUseData.Message);
                    }
                }
                //if (_user.FollowUp && useLog)
                //{
                //    Context.LogEntity(o, _user, GetKeys[0], _formType, headerkeyvalue, headerkeyvalue);
                //}
                Context.SaveChanges();
                scope.Complete();
                if (AfterSave != null)
                {
                    var eventMessage = new EventBase {
                        Message = TransactionResult.None
                    };
                    AfterSave.Invoke(o, Context, eventMessage);
                    if (eventMessage.Message != TransactionResult.None)
                    {
                        return(eventMessage.Message);
                    }
                }

                return(TransactionResult.SaveSuccess);
            }
            catch (Exception ex)
            {
                HandleException(ex);
                scope.Dispose();
                Context.Database.Connection.Close();
                //Logger.LogSystemError(_user.UserId.ToString(), ex);
                return(TransactionResult.SaveFailed);
            }
            finally
            {
                scope.Dispose();
            }
        }
Exemplo n.º 22
0
 protected virtual void OnBeforeSave()
 {
     BeforeSave?.Invoke();
 }
Exemplo n.º 23
0
 public void RegisterBeforeSaveMothed(BeforeSave beforeSave)
 {
     BeforeSaveMothed = beforeSave;
 }