예제 #1
0
 /// <summary>
 /// Register parent object as candidate foster parent for obj
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="obj"></param>
 /// <param name="godparent"></param>
 public void RegisterPossibleOrphan(IStateObject parent, IStateObject obj, IStateObject godparent = null)
 {
     lock (orphanInformationTables)
     {
         orphanInformationTables.RegisterPossibleOrphan(parent, obj, godparent);
     }
 }
예제 #2
0
        /// <summary>
        ///     Given the property Index and its instance, it sets in the corresponding bit array at
        ///     the corresponding index (of the property) the value to true (modified)
        ///     Assumming that model is not a dirty model
        /// </summary>
        /// <param name="model">The instance of IChangesTrackeable</param>
        /// <param name="property">The name of the property</param>
        public void MarkAsModified(IStateObject model, int index)
        {
            if (model.UniqueID == null ||
                IsDirtyModel(model) ||
                !StateManager.AllBranchesAttached(model))
            {
                return;
            }
            BitArray data;

            lock (modifiedLock)
            {
                if (!bitArrays.TryGetValue(model, out data))
                {
                    int typePropertiesLength = TypePropertiesCache.GetArrayPropertiesCount(model.GetType());
                    bitArrays.Add(model, data = new BitArray(typePropertiesLength));
                }
                if (data == null)
                {
                    int typePropertiesLength = TypePropertiesCache.GetArrayPropertiesCount(model.GetType());
                    bitArrays[model] = data = new BitArray(typePropertiesLength);
                }
            }
            data.Set(index, true);
        }
예제 #3
0
            public void RegisterPossibleOrphan(IStateObject parent, IStateObject obj, IStateObject godparent)
            {
                Dictionary <IStateObject, IStateObject> godParentDict;

                if (!parentToGodParentsAndOrphans.TryGetValue(parent, out godParentDict))
                {
                    godParentDict = new Dictionary <IStateObject, IStateObject>(ComparerByReference.CommonInstance);
                    parentToGodParentsAndOrphans.Add(parent, godParentDict);
                }
                if (godparent == null)
                {
                    godparent = new Dummy()
                    {
                        UniqueID = (seed++).ToString()
                    };
                }
                IStateObject storedOrphan;

                if (godParentDict.TryGetValue(godparent, out storedOrphan))
                {
                    if (!Object.ReferenceEquals(storedOrphan, obj))
                    {
                        godParentDict[godparent] = obj;
                    }
                }
                else
                {
                    godParentDict.Add(godparent, obj);
                }
            }
예제 #4
0
        /// <summary>
        /// Sometimes while serializing a "DisplayClass" we might find fields that reference
        /// IStateObjects.
        /// Promises are persisted using the Surrogates mechanism, and we also are aware that
        /// Surrogates are the last thing to be serialized.
        /// Processes like adoption occur even before StateManager.Persist is started.
        /// When the value for these fields are serialized, it might happen that there are still "unattached"
        /// so they need to be adopted
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="value"></param>
        internal StateObjectSurrogate GetOrphanHolder(object instance, IStateObject value, string fieldName)
        {
            if (!StateManager.AllBranchesAttached(value.UniqueID))
            {
                var displayClassSurrogate = _stateManager.surrogateManager.GetSurrogateFor(instance, generateIfNotFound: false);
                if (displayClassSurrogate == null)
                {
                    throw new InvalidOperationException("A surrogate is needed");
                }

                //Retrieve surrogate
                StateObjectSurrogate surrogate = (StateObjectSurrogate)_stateManager.surrogateManager.GetSurrogateFor(value, generateIfNotFound: true);
                if (surrogate == null)
                {
                    throw new Exception("Object must be instantiated/registered with resolve");
                }
                //Add reference if needed
                _stateManager.surrogateManager.AddSurrogateReference(surrogate, displayClassSurrogate.UniqueID);
                AddSurrogateHolder(surrogate);
                return(surrogate);
            }
            else
            {
                return(null);
            }
        }
        public IList <string> GetAllDependentKeys(IStateObject elementObj, List <string> result = null)
        {
            var dependentsContainer = elementObj as IDependentsContainer;

            if (dependentsContainer != null)
            {
                var dependents = dependentsContainer.Dependents;
                var count      = dependents != null ? dependents.Count : 0;
                if (count > 0)
                {
                    if (result == null)
                    {
                        result = new List <string>(50);
                    }

                    var uniqueIDPart = UniqueIDGenerator.UniqueIdSeparatorStr + elementObj.UniqueID;
                    for (int i = 0; i < count; i++)
                    {
                        var childKey      = dependents[i];
                        var childUniqueID = childKey + uniqueIDPart;
                        T   childValue;
                        if (cache.TryGetValue(childUniqueID, out childValue))
                        {
                            result.Add(childUniqueID);
                            GetAllDependentKeys((IStateObject)childValue, result);
                        }
                    }
                }
            }
            return(result ?? EMPTYDEPENDENKEYS);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowBase{TStatus, TActivity, TTask, TActor}"/> class.
        /// </summary>
        /// <param name="versionKey">Workflow instance version key</param>
        /// <param name="statusObject">The loan application.</param>
        /// <param name="actorProvider">The actor provider.</param>
        protected WorkflowBase(string versionKey, IStateObject <TStatus> statusObject, IActorProvider <TActor> actorProvider)
        {
            versionKey
            .ThrowIfNull("versionKey");

            // Init object version if it is empty
            if (String.IsNullOrWhiteSpace(statusObject.WorkflowVersionKey))
            {
                statusObject.WorkflowVersionKey = versionKey;
            }

            if (!versionKey.Equals(statusObject.WorkflowVersionKey))
            {
                throw new WrongWorkflowVersionException(statusObject.WorkflowVersionKey, versionKey);
            }

            VersionKey     = versionKey;
            StatusObject   = statusObject;
            _actorProvider = actorProvider;

            Machine = new StateMachine <TStatus, TActivity>(
                () => StatusObject.Status,
                s => StatusObject.Status = s);

            TaskRestrictionsByActor =
                new Dictionary <TActor, RestrictionList <TStatus, TTask> >();

            _triggersWithParameters =
                new Dictionary <string, StateMachine <TStatus, TActivity> .TriggerWithParameters>();

            Configure();

            Machine
            .OnTransitioned(LogTransition);
        }
 /// <summary>
 /// Recursive method to iterate in the controls obtained from the GetControlsIterator
 /// </summary>
 /// <param name="parent">The actual control in the search</param>
 /// <param name="control">The control to be searched</param>
 /// <param name="VisualParentDictionary">Stores the controls and their parent found previously</param>
 /// <returns></returns>
 public static IStateObject FindVisualParent(IControlsContainer parent, ControlViewModel control, Dictionary<string, IStateObject> VisualParentDictionary)
 {
     if (parent == null)
     {
         return null; // GetControlsIterator can return null controls
     }
     var Controls = parent.GetControlsIterator();
     IStateObject VisualParent = null;
     for (var i = 0; i < Controls.Count(); i++)
     {
         var ctl = Controls.ElementAt(i);
         if (ctl == control)
         {
             if (!VisualParentDictionary.ContainsKey(control.UniqueID)) VisualParentDictionary.Add(control.UniqueID, parent);
             return parent as IStateObject;
         }
         else
         {
             VisualParent = FindVisualParent(ctl, control, VisualParentDictionary);
             if (VisualParent != null)
             {
                 return VisualParent;
             }
         }
     }
     return VisualParent;
 }
        internal static void AssignUniqueIdToPointer(IStateObject parentInstance, string relativeUid,
                                                     StateObjectPointer pointer)
        {
            var stateManager = StateManager.Current;

            if (StateManager.AllBranchesAttached(parentInstance))
            {
                //at this point we have a new pointer with an attached parent
                //which means that it was born on the temp stateManager
                //we cannot just do a switchunique ids because switching
                //is only on the stateManager level
                //we need to promote it from temp to StateManager
                //to make sure that it will be persisted
                pointer.UniqueID = relativeUid;
                stateManager.AddNewAttachedObject(pointer);
            }
            else
            {
                //at this point we have a new pointer with an UNATTACHED parent
                //which means both the parent and the pointer are on the temp stateManager
                //we need to switchunique ids because
                //they are at the stateManager level
                //if the parent is promoted so will be the pointer
                pointer.UniqueID = relativeUid;
                stateManager.AddNewTemporaryObject(pointer);
            }
        }
예제 #9
0
        public IList <KeyValuePair <string, IStateObject> > GetAllDependentItems(IStateObject elementObj, List <KeyValuePair <string, IStateObject> > result = null)
        {
            var dependentsContainer = elementObj as IDependentsContainer;

            if (dependentsContainer != null)
            {
                var count = dependentsContainer.Dependents != null ? dependentsContainer.Dependents.Count : 0;
                if (count > 0)
                {
                    if (result == null)
                    {
                        result = new List <KeyValuePair <string, IStateObject> >(50);
                    }

                    var uniqueIDPart = UniqueIDGenerator.UniqueIdSeparatorStr + elementObj.UniqueID;
                    for (int i = 0; i < count; i++)
                    {
                        var childKey      = dependentsContainer.Dependents[i];
                        var childUniqueID = childKey;
                        if (!UniqueIDGenerator.IsListItem(childKey))
                        {
                            childUniqueID += uniqueIDPart;
                        }
                        T childValue;
                        if (cache.TryGetValue(childUniqueID, out childValue))
                        {
                            result.Add(new KeyValuePair <string, IStateObject>(childUniqueID, (IStateObject)childValue));
                            GetAllDependentItems((IStateObject)childValue, result);
                        }
                    }
                }
            }
            return(result ?? EMPTYDEPENDENTS2);
        }
예제 #10
0
        private void Parent_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            IStateObject parent = sender as IStateObject;

            if (parent == null)
            {
                return;
            }
            if (e.PropertyName == "State")
            {
                if (this.Dispatcher.CheckAccess())
                {
                    CheckVisibility(parent.State);
                }
                else
                {
                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => CheckVisibility(parent.State)));
                }
            }
            if (e.PropertyName == "Progress")
            {
                /*if (parent.Progress > 0)
                 *  Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() =>
                 *  {
                 *      progressBar.IsIndeterminate = false;
                 *      progressBar.Value = parent.Progress;
                 *  }));
                 * if (parent.Progress == 0)
                 *  Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => progressBar.IsIndeterminate = true));*/
            }
        }
예제 #11
0
        /// <summary>
        /// Within Dettach object, sometimes the dettached object and its dependants has a reference of a List ( a page )
        /// In this cases, since the object has been dettached, we have to update the page,
        /// marking the page as dirty
        /// </summary>
        internal void UpdateRefTableInDettachObject(IStateObject element, string uniqueID, string oldElementUid = "")
        {
            var referenceTable = this.GetReferenceTable(uniqueID);

            if (referenceTable != null && referenceTable.References.Count > 0)
            {
                for (var i = 0; i < referenceTable.References.Count; i++)
                {
                    var reference       = referenceTable.References[i];
                    var referenceAsPage = reference.Target as Page;
                    if (referenceAsPage != null)
                    {
                        if (oldElementUid != "")
                        {
                            var objects = referenceAsPage.StoredObjects;
                            foreach (var obj in objects)
                            {
                                var lazyObject = obj as LazyObject;
                                if (String.CompareOrdinal(lazyObject.TargetUniqueID, oldElementUid) == 0)
                                {
                                    lazyObject.Target = element;
                                }
                            }
                        }
                        this._stateManager.MarkAsDirty(referenceAsPage, "StoredObjects");
                    }
                }
            }
        }
예제 #12
0
        private bool TransferValueToReference(string branchRemoved, ReferencesTable referencesTable, IStateObject elementToAdoptObj = null, bool isDispose = false, IFormBaseViewModel formBaseViewModel = null)
        {
            if (isDispose && referencesTable.IsReferencedObjectAnIDisposableDependencyControl)
            {
                return(false);
            }
            //If the elementToAdopt was not sent as a parameter let's calculate it.
            if (elementToAdoptObj == null)
            {
                elementToAdoptObj = referencesTable.ReferencedObject;
            }
            string oldParentUniqueID = elementToAdoptObj.UniqueID;

            //Entire windows won't be preserved.
            if (elementToAdoptObj is IViewModel)
            {
                return(false);
            }
            //Let's get the reference candidate for the adoption.
            var reference = GetReferenceValidForAdoption(referencesTable, false);

            if (reference == null)
            {
                return(false);
            }
            var candidate = CalculateCandidateForAdoption(reference);

            //The cadidates parent was already removed...Ciao
            if (candidate == null)
            {
                return(false);
            }
            bool doNotRegisterIDSwitch = true;

            if (formBaseViewModel == null)
            {
                formBaseViewModel = ViewManager.Instance.GetTopLevelObject(elementToAdoptObj) as IFormBaseViewModel;
            }
            if (formBaseViewModel != null)
            {
                doNotRegisterIDSwitch = formBaseViewModel.IsDisposing;
            }

            if (!(elementToAdoptObj is IDisposableDependencyControl) || (!isDispose && !doNotRegisterIDSwitch))
            {
                //The element won't belong to the parent anymore.
                IStateObject elementsToBeAdopted = _stateManager.DettachObject(elementToAdoptObj, !doNotRegisterIDSwitch);
                //We need to promote the object and attach it to the first candidate.
                AdoptionInformation.StaticAdopt(candidate, elementsToBeAdopted);
                ////Let's update all the references
                UpdateReferencesTables(oldParentUniqueID, elementToAdoptObj.UniqueID);
                //Only foreign references allowed
                referencesTable.RemoveReference(reference);
                //We move the element to a substitute parent.
                referencesTable.AttachedToParent = false;
                //We had a succesfull adoption :)
                return(true);
            }
            return(false);
        }
예제 #13
0
        /// <summary>
        /// Creates a reference table to an Object.
        /// </summary>
        /// <param name="valueObject"></param>
        /// <returns></returns>
        private ReferencesTable CreateObjectReferencesTable(IStateObject valueObject)
        {
            var new_relativeUid = UniqueIDGenerator.GetReferenceTableRelativeUniqueID(valueObject.UniqueID);

            LazyBehaviours.AddDependent(valueObject, UniqueIDGenerator.REFTABLEPrefix);
            ReferencesTable referencesTable = new ReferencesTable();

            referencesTable.UniqueID = new_relativeUid;
            referencesTable.IsReferencedObjectAnIDisposableDependencyControl = valueObject is IDisposableDependencyControl;

            if (StateManager.AllBranchesAttached(valueObject))
            {
                //at this point we have a new pointer with an attached parent
                //which means that it was born on the temp stateManager
                //we cannot just do a switchunique ids because switching
                //is only on the stateManager level
                //we need to promote it from temp to StateManager
                //to make sure that it will be persisted
                _stateManager.AddNewAttachedObject(referencesTable);
            }
            else
            {
                //at this point we have a new pointer with an UNATTACHED parent
                //which means both the parent and the pointer are on the temp stateManager
                //we need to switchunique ids because
                //they are at the stateManager level
                //if the parent is promoted so will be the pointer
                _stateManager.AddNewTemporaryObject(referencesTable);
            }
            return(referencesTable);
        }
예제 #14
0
파일: StateMachine.cs 프로젝트: purtsi/game
        //public StateMachine()
        //{


        //}

        public void SetStateForObject <StateEnum>(T entity, Enum state) where StateEnum : struct
        {
            IStateObject   e          = entity as IStateObject;
            Transition <T> transition = Transitions.Where(t => t.FromState.Equals(StateUtils.GetStateStringAsEnum <StateEnum>(e.GetState())) && t.ToState.Equals(state)).FirstOrDefault();

            if (transition != null)
            {
                if (transition.Guards != null)
                {
                    foreach (Func <T, TryGuardResponse> guard in transition.Guards)
                    {
                        TryGuardResponse tgr = guard.Invoke(entity);
                        if (!tgr.Success)
                        {
                            throw new Exception("SetStateFailedError");
                        }
                    }
                }
                e.SetState(state.ToString());

                //Effect
                if (transition.Effect != null)
                {
                    transition.Effect.Invoke(entity);
                }
            }
            else
            {
                throw new Exception("Could not find transition from state " + e.GetState() + " to state " + state.ToString());
            }
        }
예제 #15
0
        public object ResolveDictionary(Type type, Func <object> lambdaCreation, object[] parameters = null, IIocContainerFlags flags = IIocContainerFlags.None)
        {
            var          stateManager = StateManager.Current;
            IStateObject newInstance  = (IStateObject)lambdaCreation();

            ((IObservableDictionaryEntries)newInstance).Initialize(stateManager, stateManager.ReferencesManager, stateManager.surrogateManager);
            stateManager.AddNewTemporaryObject(newInstance, true);
            if (newInstance is IDependentViewModel && (flags & IIocContainerFlags.NoBuild) != IIocContainerFlags.NoBuild)
            {
                ((IDependentViewModel)newInstance).Build(this);
                /* IDependants are now iLogic so this properties are injected in ILogic resolve code */
            }
            var isRecoveredFromStorage = (flags & IIocContainerFlags.RecoveredFromStorage) == IIocContainerFlags.RecoveredFromStorage;

            if (!isRecoveredFromStorage)
            {
                if ((flags & IIocContainerFlags.ExtraLean) != IIocContainerFlags.ExtraLean)
                {
                    InitializationHelpers.CallInitializeCommon(newInstance, type);
                }
                //First we check to avoid unnecessary calls to GetInitMethod
                if (newInstance is IInitializable && !isRecoveredFromStorage && ((flags & IIocContainerFlags.Lean) != IIocContainerFlags.Lean))
                {
                    //Get Init must be done on the instance type, because logicType might refer to an interface
                    InitializationHelpers.CallInitMethod((IInitializable)newInstance, parameters);
                }
            }
            return(newInstance);
        }
        internal void SyncDirtyModel(JToken jobj)
        {
            string       uniqueId = ((JProperty)(jobj)).Name;
            IStateObject obj      = StateManager.Current.GetObject(uniqueId);

            Debug.Assert(obj != null, "Model to sync was not found ID:" + uniqueId);
            JToken val = jobj.FirstOrDefault();

            if (val != null && (!(val is JArray) || (((JArray)val).Count > 0 && ((JArray)val)[0].HasValues)))
            {
                var  type          = obj.GetType();
                bool converterUsed = false;
                foreach (var converter in convertersForAppChanges)
                {
                    if (converter.CanConvert(type))
                    {
                        var ns = converter.GetType().Namespace;
                        if (ns != null && ns.Equals("UpgradeHelpers.BasicViewModels.SerializationAndStorage", StringComparison.Ordinal))
                        {
                            using (JsonReader reader = val.CreateReader())
                            {
                                reader.Read();
                                converter.ReadJson(reader, type, obj, syncDirtyModelsSerializer);
                                converterUsed = true;
                                break;
                            }
                        }
                    }
                }
                if (!converterUsed)
                {
                    syncDirtyModelsSerializer.Populate(val.CreateReader(), obj);
                }
            }
        }
        public void Serialize(object instance, BinaryWriter binaryWriter, MemoryStream ms, ISurrogateContext context)
        {
            Type         outType = null;
            IStateObject model   = null;

            PromiseUtils.SerializeStateForDelegate(StateManager.Current, instance, binaryWriter, _oType, out outType, out model);
        }
예제 #18
0
        /// <summary>
        ///     Given the property name and its instance, it sets in the corresponding bit array at
        ///     the corresponding index (of the property) the value to true (modified)
        ///     Assumming that model is not a dirty model
        /// </summary>
        /// <param name="model">The instance of IChangesTrackeable</param>
        /// <param name="property">The name of the property</param>
        public void MarkAsModified(IStateObject model, string property)
        {
            if (model.UniqueID == null ||
                IsDirtyModel(model) ||
                !StateManager.AllBranchesAttached(model))
            {
                return;
            }

            PropertiesExDictionary typeProperties = TypePropertiesCache.GetPropertiesIndexPositionOfType(model.GetType());
            int propertyIndex;

            if (!typeProperties.TryGetValue(property, out propertyIndex))
            {
                return;
            }
            BitArray data;

            lock (modifiedLock)
            {
                if (!bitArrays.TryGetValue(model, out data))
                {
                    bitArrays.Add(model, data = new BitArray(typeProperties.PropertiesList.Count));
                }
                if (data == null)
                {
                    bitArrays[model] = data = new BitArray(typeProperties.PropertiesList.Count);
                }
            }
            data.Set(propertyIndex, true);
        }
 public void RemoveSurrogateReference(StateObjectSurrogate surrogate, IStateObject oldReference)
 {
     if (oldReference != null && surrogate != null)
     {
         RemoveSurrogateReference(surrogate, oldReference.UniqueID);
     }
 }
예제 #20
0
        private static void ReportOwnerException(PropertyInfoEx propEx, IStateObject newValue, string old_Uid)
        {
            var stackTrace = new System.Diagnostics.StackTrace(4, true);

            var ownerInfo   = " Not owner info available";
            var ownerObject = StateManager.Current.GetParentEx(newValue);

            if (ownerObject != null)
            {
                var format =
                    " The owner of the object is an instance of class {0}, it is {1}. Look for property {2}. It could have been set during a Build call that is still of process or during an Initialize.Init which is the WebMap equivalent of a constructor. If it is used as parent reference reimplement the property as a non virtual, [StateManagement(None)] calculated property using ViewManager.GetParent(), you can also use [Reference] attribute or disable interception by removing virtual from the property";
                if (StateManager.AllBranchesAttached(ownerObject))
                {
                    ownerInfo = string.Format(format,
                                              TypeCacheUtils.GetOriginalTypeName(ownerObject.GetType()), " ATTACHED ",
                                              StateManager.GetLastPartOfUniqueID(newValue));
                }
                else
                {
                    ownerInfo = string.Format(format, "NOT ATTACHED",
                                              TypeCacheUtils.GetOriginalTypeName(ownerObject.GetType()),
                                              StateManager.GetLastPartOfUniqueID(newValue));
                }
            }
            throw new InvalidOperationException(
                      "LazyBehaviour::ProcessSetter object has already an Owner." + ownerInfo + "\r\n" +
                      "UniqueID: " + old_Uid + "\r\n" +
                      "Additional Info: \r\n" +
                      "ViewModel Type: " + newValue.GetType().FullName + "\r\n" +
                      "Property Type: " + propEx.prop.PropertyType.FullName + "\r\n" +
                      "Error Location: " + stackTrace.ToString());
        }
 internal void AddSurrogateReference(StateObjectSurrogate surrogate, IStateObject reference)
 {
     lock (surrogate)
     {
         surrogate.AddReference(new LazyStateObjectReference(_stateManager, reference));
     }
 }
 public void AddSurrogateReference(IStateObjectSurrogate surrogate, IStateObject reference)
 {
     lock (surrogate)
     {
         ((StateObjectSurrogate)surrogate).AddReference(new LazyStateObjectReference(_stateManager, reference));
     }
 }
        public Delegate PublishToDelegate(string eventId, IStateObject source)
        {
            eventId = eventId.ToUpper();
            var promisesInfo = HasSubscribers(eventId, source) as PromisesInfo;

            if (promisesInfo != null)
            {
                foreach (string eventsnameid in promisesInfo.GetListMethodsMame())
                {
                    var subscriptionId   = UniqueIDGenerator.GetEventRelativeUniqueID(source, eventsnameid);
                    var eventHandlerInfo = _stateManager.GetObject(subscriptionId) as EventPromiseInfo;
                    if (eventHandlerInfo != null)
                    {
                        var result = this.PublishInternal(eventHandlerInfo, eventId, source, true, null);
                        return(result);
                    }
                    else
                    {
                        TraceUtil.TraceError(string.Format("EventAggregator::PublishToMainSyncronizationContext. No Events found for EventId [{0}] on object [{1}]", subscriptionId, source == null ? "null" : source.UniqueID));
                    }
                }
            }
            else
            {
                TraceUtil.TraceError(string.Format("HandlersEventAggregator::PublishToMainSyncronizationContext. No Events found for EventId [{0}] on object [{1}]", eventId, source == null ? "null" : source.UniqueID));
            }
            return(null);
        }
        /// <summary>
        /// Will register a subscriber. Event will be recognized by "eventId" and will be attached to
        /// obj
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="obj"></param>
        /// <param name="handler"></param>
        public void Subscribe(string eventId, IStateObject obj, Delegate handler, out string eventSubscriptionId, bool isDynamic = false)
        {
            var result = String.Empty;

            if (handler != null)
            {
                //get/created subscribed promises info
                eventId = eventId.ToUpper();
                var handlerSubscriptionId = UniqueIDGenerator.GetEventRelativeUniqueID(obj, eventId);
                LazyBehaviours.AddDependent(obj, UniqueIDGenerator.EVENTPrefix + eventId);
                var promisesInfo = PromisesInfo.CreateInstance(handlerSubscriptionId);

                ////subscribe handler
                var eventMethodName = handler.Method.Name.ToUpper() + eventId;
                eventSubscriptionId = UniqueIDGenerator.GetEventRelativeUniqueID(obj, eventMethodName);
                LazyBehaviours.AddDependent(obj, UniqueIDGenerator.EVENTPrefix + eventMethodName);
                promisesInfo.Add(eventMethodName);
                if (isDynamic)
                {
                    EventPromiseInfoForClient.CreateEventInstance(_stateManager, handler, obj, eventSubscriptionId, actionID: eventId);
                }
                else
                {
                    EventPromiseInfo.CreateEventInstance(_stateManager, handler, obj, eventSubscriptionId);
                }
#if DEBUG
                Debug.Assert(_stateManager.GetObject(eventSubscriptionId) != null, "Event Subscription Failed", "Event for {0} on Object {1} failed", eventId, obj.UniqueID);
#endif
                result = eventSubscriptionId;
            }
            eventSubscriptionId = result;
        }
        public void Subscribe(string eventId, IStateObject component, ILogic logic, string methodName)
        {
            var type   = logic.GetType();
            var method = type.Method(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | Flags.ExcludeBackingMembers);

            RegisterMethodForEvent(logic, method, component.ToString(), eventId, component);
        }
        private void PublishInternal(string eventId, IStateObject source, object[] args)
        {
            eventId = eventId.ToUpper();
            var promisesInfo = HasSubscribers(eventId, source) as PromisesInfo;

            if (promisesInfo != null)
            {
                foreach (string eventsnameid in promisesInfo.GetListMethodsMame())
                {
                    var subscriptionId   = UniqueIDGenerator.GetEventRelativeUniqueID(source, eventsnameid);
                    var eventHandlerInfo = _stateManager.GetObject(subscriptionId) as EventPromiseInfo;
                    if (eventHandlerInfo != null)
                    {
                        this.PublishInternal(eventHandlerInfo, eventId, source, false, args);
                    }
                    else
                    {
                        TraceUtil.TraceError(string.Format("EventAggregator::PublishInternal. No Events found for EventId [{0}] on object [{1}]", subscriptionId, source == null ? "null" : source.UniqueID));
                    }
                }
            }
            else
            {
                TraceUtil.TraceError(string.Format("HandlersEventAggregator::PublishInternal. No Events found for EventId [{0}] on object [{1}]", eventId, source == null ? "null" : source.UniqueID));
            }
        }
예제 #27
0
 /// <summary>
 ///     It tries to removes the given model of the list of the subscribed models and the
 ///     bit array of the data arrays
 /// </summary>
 /// <param name="model"></param>
 /// <returns>True if is succeeds, false otherwise</returns>
 public void DetachModel(IStateObject model)
 {
     // Removing model from list of models
     lock (bitArraysLock)
     {
         bitArrays.Remove(model);
     }
 }
예제 #28
0
        public IUndoableEdit CreateChangeStateEdit(IStateObject stateObject, State state)
        {
            DefaultEdit <object> pe = new DefaultEdit <object>(stateObject, ChangeState, ChangeState);

            pe.UndoParams = new PropertyEditParameters("", stateObject.CurrentState);
            pe.RedoParams = new PropertyEditParameters("", state);
            return(pe);
        }
 public void Publish(string eventId, IStateObject source, params object[] args)
 {
     if (suspendedState > 0)
     {
         return;
     }
     PublishInternal(eventId, source, args);
 }
예제 #30
0
 public static void FixState(this DbContext context)
 {
     foreach (var entry in context.ChangeTracker.Entries <IStateObject>())
     {
         IStateObject stateInfo = entry.Entity;
         entry.State = ConvertState(stateInfo.State);
     }
 }
예제 #31
0
 public StateOperation( IStateObject o, ObjectState s1, ObjectState s2 )
 {
     v = o;
     before = s1;
     after = s2;
 }
예제 #32
0
 public void InvalidateAllAssociated( IStateObject obj )
 {
     foreach( GuiObject o in obj.Associated ) {
         o.Invalidate();
         o.invalidate_children();
         if( o is IStateObject )
             InvalidateAllAssociated( o as IStateObject );
     }
 }