Example #1
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);
        }
        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));
            }
        }
        /// <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 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);
        }
Example #5
0
        /// <summary>
        /// Goes through all the References Tables in a branch and Updates the References.
        /// </summary>
        /// <param name="branchDeleted"></param>
        /// <param name="oldParentUID"></param>
        /// <param name="newParentUID"></param>
        public void UpdateReferencesTables(string oldParentUID, string newParentUID)
        {
            var newParentUIDRefTables = GetChildrenReferencesTables(newParentUID);

            if (newParentUIDRefTables != null)
            {
                foreach (var table in newParentUIDRefTables)
                {
                    var newUID = StateManager.GetParentUniqueID(table.UniqueID);
                    var oldUID = UniqueIDGenerator.ReplaceParent(newUID, newParentUID, oldParentUID);
                    //Let´s update and then validate the References.
                    table.UpdateReferencesTable(oldParentUID, newParentUID, oldUID, newUID);
                }
            }
            var olParentUIDRefTables = GetChildrenReferencesTables(oldParentUID);

            if (olParentUIDRefTables != null)
            {
                for (var i = 0; i < olParentUIDRefTables.Count; i++)
                {
                    var table = olParentUIDRefTables[i];
                    //Maybe table is already in ElementsToRemove
                    if (table != null)
                    {
                        var newUID = StateManager.GetParentUniqueID(table.UniqueID);
                        var oldUID = UniqueIDGenerator.ReplaceParent(newUID, newParentUID, oldParentUID);
                        //Let´s update and then validate the References.
                        table.UpdateReferencesTable(oldParentUID, newParentUID, oldUID, newUID);
                    }
                }
            }
        }
Example #6
0
 internal static bool ProcessGetterTopLevelIStateObject(PropertyInfoEx propEx, object parentObject, ref Object lastValue)
 {
     if (lastValue == null)
     {
         var prop           = propEx.prop;
         var parentInstance = parentObject as IStateObject;
         if (typeof(IStateObject).IsAssignableFrom(prop.DeclaringType))
         {
             Type returnType   = prop.PropertyType;
             var  stateManager = StateManager.Current;
             var  attributes   = returnType.GetCustomAttributes(typeof(Singleton), false);
             if (attributes.Length > 0)
             {
                 var cachedValue = stateManager.GetObject(UniqueIDGenerator.GetSinglentonUniqueId(returnType));
                 lastValue = cachedValue;
                 return(true);
             }
             else
             {
                 var propName    = GetPropertyName(propEx);
                 var relativeUid = UniqueIDGenerator.GetPointerRelativeUniqueID(parentInstance, propName);
                 var pointer     = (StateObjectPointer)stateManager.GetObject(relativeUid);
                 if (pointer != null)
                 {
                     var cachedValue = TryToRecoverWithPointer(stateManager, propEx, parentInstance, false, pointer: pointer);
                     lastValue = cachedValue;
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
Example #7
0
        public void UnSubscribe(object valueObject, string UniqueID, bool removeDirectly = false, string rootUniqueID = "")
        {
            var referenceToTheValue = valueObject as IStateObject;

            if (referenceToTheValue != null)
            {
                var referencesTable = GetObjectReferencesTable(UniqueID);
                if (referencesTable != null)
                {
                    if (rootUniqueID != "")
                    {
                        referencesTable.ValidateReferences(validateUnAttached: true, branchDeleted: rootUniqueID);
                    }
                    else
                    {
                        referencesTable.ValidateReferences(validateUnAttached: true);
                    }
                    if (UniqueIDGenerator.IsListItem(UniqueID) && !HasValidReferencesForListItem(referencesTable, UniqueID, _stateManager._objectsToBeValidatedAfterDisposeHashSet))
                    {
                        _stateManager.DettachListItem(UniqueID, rootUniqueID);
                    }
                    else if (referencesTable.Count == 0 && !referencesTable.AttachedToParent)
                    {
                        _stateManager.DettachObject(UniqueID, false);
                    }
                }
            }
        }
Example #8
0
        internal static bool ProcessGetterStrongReference(PropertyInfoEx propEx, object parentObject, ref Object lastResult)
        {
            var    prop           = propEx.prop;
            var    parentInstance = parentObject as IStateObject;
            string propName       = GetPropertyName(propEx);
            //Try to recover
            //1. First recover pointer
            //2. Then get surrogate
            string relativeUid  = UniqueIDGenerator.GetPointerRelativeUniqueID(parentInstance, propName);
            var    stateManager = StateManager.Current;
            var    pointer      = (StateObjectPointer)stateManager.GetObject(relativeUid);

            if (pointer != null)
            {
                if (propEx.stateManagementAttribute == StateManagementValues.ServerOnly)
                {
                    stateManager.isServerSideOnly.Add(pointer);
                }
                //Extend to support other types
                var cachedValue = TryToRecoverWithPointer(stateManager, propEx, parentInstance, false, false, pointer: pointer);
                lastResult = cachedValue;
                return(true);
            }
            else
            {
                //There was no pointer, then return null
                lastResult = null;
                return(true);
            }
        }
Example #9
0
        private bool HasValidReferencesForListItem(ReferencesTable referencesTable, string uniqueID, HashSet <string> _objectsToBeValidatedAfterDisposeHashSet)
        {
            var isValid = false;

            for (int i = referencesTable.References.Count - 1; i >= 0; i--)
            {
                var  reference = referencesTable.References[i];
                bool isPage    = UniqueIDGenerator.IsPage(reference.TargetUniqueID);
                if (isPage)
                {
                    var    page = reference.Target as Page;
                    string pageParentUniqueID = GetPageParentUniqueID(page);
                    //the reference is valid if and only if the list is not in elements to remove, and if the list is allbranchesattached.
                    if (!StateManager.Current.IsInElementsToRemove(pageParentUniqueID) &&
                        StateManager.AllBranchesAttached(pageParentUniqueID))
                    {
                        isValid = true;
                    }
                }
                else if (!StateManager.Current.IsInElementsToRemove(reference.TargetUniqueID))
                {
                    //if the reference is not a page, this means it is a pointer pointing to the list item
                    // and this pointer is not in elementsToRemove Collection
                    //so this item has valid reference yet.
                    isValid = true;
                    _objectsToBeValidatedAfterDisposeHashSet.Add(uniqueID);
                }
            }
            return(isValid);
        }
Example #10
0
        /// <summary>
        /// Rescues a Value if it has Valid References
        /// </summary>
        /// <param name="valueDeleted">It's the UniqueID of the IStateObject being deleted</param>
        /// <param name="branchUniqueID">It's the Root object that started the Deletion process.</param>
        /// <returns>True if the Value had valid references and it was rescued from deletion.</returns>
        internal bool RescueValue(string objToRemoveUniqueID, string branchUniqueID = null, bool allowUnAttachedReferences = true, bool isDispose = false, IFormBaseViewModel formBaseViewModel = null, HashSet <string> _objectsToBeValidatedAfterDisposeHashSet = null)
        {
            if (branchUniqueID == null)
            {
                branchUniqueID = objToRemoveUniqueID;
            }

            var referencesTable = GetObjectReferencesTable(objToRemoveUniqueID);

            if (referencesTable != null)
            {
                referencesTable.ValidateReferences(branchDeleted: branchUniqueID, validateUnAttached: !allowUnAttachedReferences);
                //If the object to be removed is a ListItem AND the referencesTable's count is major than zero,
                //then we have a special block for handling this situation.
                if (UniqueIDGenerator.IsListItem(objToRemoveUniqueID) && referencesTable.Count > 0)
                {
                    //If the referenced object is IViewModel, or IDisposableDependencyControl,
                    //we should never rescue them.
                    if (isDispose && referencesTable.IsReferencedObjectAnIDisposableDependencyControl)
                    {
                        return(false);
                    }
                    //If there are some valid references, we should rescue it.
                    else if (HasValidReferencesForListItem(referencesTable, objToRemoveUniqueID, _objectsToBeValidatedAfterDisposeHashSet))
                    {
                        RescuedValueUniqueIdHashSet.Add(objToRemoveUniqueID);
                        return(true);
                    }
                    //otherwise, we shouldn't resue it
                    else
                    {
                        return(false);
                    }
                }
                else if (referencesTable.Count > 0)//No references
                {
                    bool res = TransferValueToReference(branchUniqueID, referencesTable, isDispose: isDispose, formBaseViewModel: formBaseViewModel);
                    if (res)
                    {
                        RescuedValueUniqueIdHashSet.Add(objToRemoveUniqueID);
                    }
                    return(res);
                }
            }
            //Given this kind of uniqueID: x#y#KIXYZ
            // We have to validate if KIXYZ has been rescued previously,
            // if this KIXYZ has been rescued, we should skip this uniqueID
            var accessPathIndex = objToRemoveUniqueID.LastIndexOf(UniqueIDGenerator.UniqueIdSeparator);

            if (accessPathIndex > 0)
            {
                var ancestorUID = objToRemoveUniqueID.Substring(accessPathIndex + 1);
                var canRescue   = RescuedValueUniqueIdHashSet.Contains(ancestorUID) && !_stateManager.IsInElementsToRemove(ancestorUID);
                if (UniqueIDGenerator.IsListItem(ancestorUID) && canRescue)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #11
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);
        }
Example #12
0
        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;
                        if (!UniqueIDGenerator.IsListItem(childKey))
                        {
                            childUniqueID += uniqueIDPart;
                        }
                        var childValue = stateManager.GetObject(childUniqueID);
                        if (childValue != null)
                        {
                            result.Add(childUniqueID);
                            GetAllDependentKeys((IStateObject)childValue, result);
                        }
                    }
                }
            }
            return(result ?? EMPTYDEPENDENKEYS);
        }
        private IList <BasePromiseInfo> CreatePromises()
        {
            var stateCache = StateManager.Current;
            var uid        = UniqueIDGenerator.GetRelativeUniqueID(this, "Promises");
            var promises   = IocContainerImplWithUnity.Current.Resolve <IList <BasePromiseInfo> >();

            stateCache.PromoteObject((IStateObject)promises, uid);
            return(promises);
        }
Example #14
0
        //private int AdoptToAttachedParent(IOrderedEnumerable<OrphanInfoEntry> sortedOrphans)
        //{
        //    var adoptedOrphants = 0;
        //    var current = StateManager.Current;
        //    var tempCacheValues = current._tempcache.Values;
        //    var cacheValues = current._cache.Values;

        //    foreach (var orphanInfo in sortedOrphans)
        //    {
        //        //Is parent attached?
        //        //if (!tempCacheValues.Contains(orphanInfo.Parent, new CustomComparer()))
        //        //{
        //        //	Adopt(orphanInfo.Parent, orphanInfo.Orphan);
        //        //	this._currentOrphans.Remove(orphanInfo);
        //        //	adoptedOrphants++;
        //        //}
        //        if (current._tempcache.GetIndexedKeyByValue(orphanInfo.Parent) == null)
        //        {
        //            Adopt(orphanInfo.Parent, orphanInfo.Orphan);
        //            _currentOrphans.Remove(orphanInfo);
        //            adoptedOrphants++;
        //        }
        //        //if (cacheValues.Contains(orphanInfo.Parent, new CustomComparer()))
        //        //{
        //        //	Adopt(orphanInfo.Parent, orphanInfo.Orphan);
        //        //	this._currentOrphans.Remove(orphanInfo);
        //        //	adoptedOrphants++;
        //        //}
        //    }

        //    return adoptedOrphants;
        //}


        internal void Dispose()
        {
            this._currentOrphans = null;
            this._godparentsOrphansAssignment = null;
            this._orphanHolders          = null;
            this._promotedOrphans        = null;
            this._stateManager           = null;
            this._uniqueIdGenerator      = null;
            this.orphanInformationTables = null;
        }
Example #15
0
        /// <summary>
        /// Let's get the reference candidate for the adoption.
        /// </summary>
        /// <param name="referencedObject"></param>
        /// <param name="onlyAllBranchesAttached"></param>
        /// <returns></returns>
        public IStateObject GetReferenceValidForAdoption(ReferencesTable referencesTable, bool onlyAllBranchesAttached = true, bool isHandlingOrphans = false)
        {
            IStateObject result = null;

            if (referencesTable != null)
            {
                IStateObject firstNonVisualParentCandidate = null;;
                IStateObject firstVisualParentCandidate    = null;
                foreach (var candidate in referencesTable.References)
                {
                    var parent = CalculateCandidateForAdoption(candidate.Target as IStateObject);
                    //If the possible parent is a page, lets retrieve tha page's parent ( the list ), he will be the candidate
                    //who will compete with other parents in the addoption process.
                    if (isHandlingOrphans && parent is Page)
                    {
                        if ((parent as Page).Parent is IStateObject)
                        {
                            parent = (parent as Page).Parent as IStateObject;
                        }
                        else
                        {
                            parent = StateManager.Current.GetObject((parent as Page).Parent as string);
                        }
                    }
                    if (parent == null)
                    {
                        continue;
                    }
                    if (!onlyAllBranchesAttached || (onlyAllBranchesAttached && StateManager.AllBranchesAttached(parent)))
                    {
                        var isTopModel  = UniqueIDGenerator.IsRootModel(parent.UniqueID);
                        var isTopShared = UniqueIDGenerator.IsRootSharedState(parent.UniqueID);
                        if (isTopModel || isTopShared || parent is IModel || parent is IDependentModel || parent is IPromise)
                        {
                            firstNonVisualParentCandidate = parent;
                            continue;
                        }
                        if (parent is IViewModel || parent is IDependentViewModel)
                        {
                            firstVisualParentCandidate = parent;
                            break;
                        }
                    }
                }
                if (firstVisualParentCandidate != null)
                {
                    result = firstVisualParentCandidate;
                }
                else if (firstNonVisualParentCandidate != null)
                {
                    result = firstNonVisualParentCandidate;
                }
            }
            return(result);
        }
Example #16
0
        /// <summary>
        /// Gets the References table associated to an IStateObject
        /// </summary>
        /// <param name="valueObject"></param>
        /// <returns></returns>
        private ReferencesTable GetObjectReferencesTable(string uniqueID)
        {
            ReferencesTable result   = null;
            var             uniqueId = UniqueIDGenerator.GetReferenceTableRelativeUniqueID(uniqueID);
            var             obj      = _stateManager.GetObject(uniqueId);

            if (obj != null)
            {
                result = obj as ReferencesTable;
            }
            return(result);
        }
Example #17
0
 private static void ProcessStaticAdoption(IStateObject parent, IStateObject orphan)
 {
     //if (child is still orphan)
     if (!StateManager.AllBranchesAttached(orphan))
     {
         //Get relative id for orphan
         var orphanID    = StateManager.Current.UniqueIDGenerator.GetOrphanUniqueID();
         var newUniqueID = UniqueIDGenerator.GetRelativeUniqueID(parent, orphanID);
         LazyBehaviours.AddDependent(parent, orphanID);
         StateManager.Current.SwitchOrPromoteObject(orphan, newUniqueID, inAdoption: true);
     }
 }
        private void GetResolvedValueEx(DependencyResolutionInfo dependency)
        {
            var surrogateManager  = _stateManager.surrogateManager;
            var value             = dependency.value;
            var istateObjectValue = dependency.value as IStateObject;

            if (istateObjectValue != null)
            {
                //The value is an state object
                if (_stateManager.IsInElementsToRemove(istateObjectValue.UniqueID))
                {
                    //If the object is present in the elements it is detached from so its UniqueID
                    //is changed to a temporal one.
                    //The current in the session must be removed
                    _stateManager.DettachObject(istateObjectValue);
                }
                dependency.canBeAnOrphan = !StateManager.AllBranchesAttached(istateObjectValue);
                dependency.ResolvedValue = istateObjectValue;
                dependency.IsStateObject = true;
            }
            else if (value is ISurrogateEventsInfo)
            {
                dependency.ResolvedValue = value;
                dependency.isEventsInfo  = true;
            }
            else
            {
                //if (surrogateManager.IsSurrogateRegistered(value.GetType())) Commented for performance
                StateObjectSurrogate currentSurrogate = null;
                //Get the surrogate instance from the surrogates that are already loaded in memory or create one
                dependency.ResolvedValue = currentSurrogate = dependency.ResolvedSurrogate = surrogateManager.GetSurrogateFor(value, generateIfNotFound: true);

                if (currentSurrogate == null)
                {
                    throw new ArgumentException("A surrogate could not be gotten for value of type " + value.GetType().FullName);
                }

                if (_stateManager.IsInElementsToRemove(currentSurrogate.UniqueID))
                {
                    //If the object is present in the elements it is restored,
                    //since it is a top element no adoption needs to be performed
                    _stateManager.UndoRemove(currentSurrogate.UniqueID);
                    //We must unremove the Value surrogate
                    var valueUniqueID = UniqueIDGenerator.GetRelativeUniqueID(currentSurrogate, StateObjectSurrogate.VALUE_PREFIX);
                    _stateManager.UndoRemove(valueUniqueID);
                }
                else
                {
                    //OK
                }
            }
        }
        public IStateObject HasSubscribers(string eventId, IStateObject source)
        {
            eventId = eventId.ToUpper();
            if (source == null)
            {
                TraceUtil.TraceError("EventAggregator::PublishHighPriorityEvent Error publishing event [" + eventId + "] source argument should not be null");
                return(null);
            }
            var subscriptionId = UniqueIDGenerator.GetEventRelativeUniqueID(source, eventId);
            var promisesInfo   = _stateManager.GetObject(subscriptionId) as PromisesInfo;

            return(promisesInfo);
        }
Example #20
0
        public T ResolveSinglenton <T>(object[] parameters = null, IIocContainerFlags flags = IIocContainerFlags.None)
        {
            var t            = typeof(T);
            T   newInstance  = default(T);
            var stateManager = StateManager.Current;

            try
            {
                var isRecoveredFromStorage = (flags & IIocContainerFlags.RecoveredFromStorage) == IIocContainerFlags.RecoveredFromStorage;
                if (!isRecoveredFromStorage)
                {
                    flags       = flags | IIocContainerFlags.IsSinglenton;
                    newInstance = (T)stateManager.GetObject(UniqueIDGenerator.GetSinglentonUniqueId(t));
                    if (newInstance != null)
                    {
                        return(newInstance);
                    }
                    if ((flags & IIocContainerFlags.SinglentonNonReturnIfExisting) == IIocContainerFlags.SinglentonNonReturnIfExisting)
                    {
                        return(default(T));
                    }
                    //At this point the object was recovered from storage and it the RecoveredFromStorageFlags must
                    //added to avoid unnecessary further processing of this object
                    isRecoveredFromStorage = (newInstance != null);
                }
                if (newInstance == null)
                {
                    newInstance = (T)ResolveUnPrepared(t, isRecoveredFromStorage);
                }
                if (newInstance is ILogic)
                {
                    InitializeObject(stateManager, this, (ILogic)newInstance, parameters, t, isRecoveredFromStorage, flags);
                }
                else if (newInstance is IStateObject)
                {
                    if (!isRecoveredFromStorage)
                    {
                        InitializeObject(stateManager, this, (IStateObject)newInstance, parameters, t, flags);
                    }
                }
            }
            finally
            {
                if (newInstance is IStateObject)
                {
                    stateManager.RemoveIDInResolution(((IStateObject)newInstance).UniqueID);
                }
            }
            return(newInstance);
        }
Example #21
0
 private bool ProcessAdoption(IStateObject parent, IStateObject orphan)
 {
     if (!_promotedOrphans.Contains(orphan))
     {
         //Get relative id for orphan
         var orphanID    = _uniqueIdGenerator.GetOrphanUniqueID();
         var newUniqueID = UniqueIDGenerator.GetRelativeUniqueID(parent, orphanID);
         _stateManager.PromoteObject(orphan, newUniqueID, inAdoption: true);
         LazyBehaviours.AddDependent(parent, orphanID);
         _promotedOrphans.Add(orphan);
         return(true);
     }
     return(false);
 }
Example #22
0
        public void SaveSurrogate(StateObjectSurrogate surrogate)
        {
            //Save surrogate header
            var surrogateContext = StateManager.Current.surrogateManager.GetSurrogateContext(surrogate.UniqueID, surrogate);
            var raw = SurrogatesDirectory.ObjectToRaw(surrogate, surrogateContext);

            SaveRaw(surrogate.UniqueID, raw);

            //Save surrogate value
            var uid = UniqueIDGenerator.GetRelativeUniqueID(surrogate, StateObjectSurrogate.VALUE_PREFIX);

            surrogateContext = StateManager.Current.surrogateManager.GetSurrogateContext(uid, surrogate.Value);
            raw = SurrogatesDirectory.ObjectToRaw(surrogate.Value, surrogateContext);
            SaveRaw(uid, raw);
        }
Example #23
0
        public void SaveSurrogate(StateObjectSurrogate surrogate)
        {
            //Saving surrogate header
            var surrogatecontext = _surrogateManager.GetSurrogateContext(surrogate.UniqueID, surrogate);
            var raw = SurrogatesDirectory.ObjectToRaw(surrogate, surrogatecontext);

            SaveRaw(surrogate.UniqueID, raw);
            //Saving surrogateValue
            if (surrogate.ShouldSerializeValue)
            {
                var uid = UniqueIDGenerator.GetRelativeUniqueID(surrogate, StateObjectSurrogate.VALUE_PREFIX);
                surrogatecontext = _surrogateManager.GetSurrogateContext(uid, surrogate.Value);
                raw = SurrogatesDirectory.ObjectToRaw(surrogate.Value, surrogatecontext);
                SaveRaw(uid, raw);
            }
        }
Example #24
0
        /// <summary>
        /// Gets All the ReferencesTables in _cache.
        /// </summary>
        /// <param name="uniqueID"></param>
        /// <returns></returns>
        private List <ReferencesTable> GetChildrenReferencesTablesInCache(string uniqueID)
        {
            HashSet <string>       children = children = _stateManager.GetAllChildrenKeys(uniqueID);
            List <ReferencesTable> result   = null;

            foreach (var child in children)
            {
                result = result ?? new List <ReferencesTable>();
                if (UniqueIDGenerator.IsRefencesTable(child) && !_stateManager.IsInElementsToRemove(child))
                {
                    var table = _stateManager.GetObject(child) as ReferencesTable;
                    result.Add(table);
                }
            }
            return(result);
        }
Example #25
0
        /// <summary>
        /// Gets All the ReferencesTables in _tempCache.
        /// </summary>
        /// <param name="uniqueID"></param>
        /// <returns></returns>
        private List <ReferencesTable> GetChildrenReferencesTablesInTempStorage(string uniqueID)
        {
            var children = _stateManager._tempcache.GetAllDependentItems(uniqueID);
            List <ReferencesTable> result = null;

            foreach (var child in children)
            {
                result = result ?? new List <ReferencesTable>();
                if (UniqueIDGenerator.IsRefencesTable(child.Key))
                {
                    var table = child.Value as ReferencesTable;
                    result.Add(table);
                }
            }
            return(result);
        }
Example #26
0
        private static IStateObject GetCurrentValue(StateManager stateManager, PropertyInfoEx propEx, IStateObject parentInstance, out string valueRelativeUid, bool isNew = false)
        {
            var propName = GetPropertyName(propEx);

            valueRelativeUid = UniqueIDGenerator.GetRelativeUniqueID(parentInstance, propName);
            //First Try: Let's get the object from the Storage.
            var currentValue = stateManager.GetObject(valueRelativeUid);

            if (currentValue == null)
            {
                var pointerRelativeUid = UniqueIDGenerator.GetPointerRelativeUniqueID(parentInstance, propName);
                //Second try: get the Reference if present.
                currentValue = stateManager.GetObject(pointerRelativeUid, isNew: isNew);
            }
            return(currentValue);
        }
Example #27
0
        internal static void ProcessSetterSimpleTypes(PropertyInfoEx propEx, object parentObject, object newObjectValue, bool isNew = false)
        {
            if (isNew)
            {
                return;
            }
            string propName       = propEx.prop.Name;
            var    parentInstance = (IStateObject)parentObject;
            var    tracker        = StateManager.Current.Tracker;

            // Delta Tracking of modified property
            if (!tracker.IsDirtyModel(parentInstance))
            {
                tracker.MarkAsModified(parentInstance, propEx.propertyPositionIndex);
            }
            var stateManager = StateManager.Current;

            if (!stateManager.flagInBind)
            {
                var bindinguid     = UniqueIDGenerator.GetRelativeUniqueID(parentInstance, propName + StateManager.BindingKey);
                var bindingPointer = StateManager.Current.GetObject(bindinguid) as StateObjectPointer;
                if (bindingPointer != null)
                {
                    var bindingSurrogate = bindingPointer.Target as StateObjectSurrogate;
                    if (bindingSurrogate != null)
                    {
                        var binding = bindingSurrogate.Value as DataBinding;
                        if (binding != null)
                        {
                            var dataSource = binding.DataSourceReference;
                            if (dataSource is StateObjectSurrogate)
                            {
                                var surrogate      = (StateObjectSurrogate)dataSource;
                                var surrogateValue = surrogate.Value;
                                var setter         = SurrogatesDirectory.GetPropertySetter(surrogate.Value);
                                setter(surrogateValue, binding.DataSourceProperty, newObjectValue);
                            }
                            else
                            {
                                throw new NotImplementedException();
                            }
                        }
                    }
                }
            }
        }
Example #28
0
        private static void AddOrUpdateReference(PropertyInfoEx propEx, IStateObject parentInstance, object newValueObj, StateObjectPointerReference currentValue = null, bool isNew = false)
        {
            var    stateManager = StateManager.Current;
            string propName     = GetPropertyName(propEx);
            var    relativeUid  = UniqueIDGenerator.GetPointerRelativeUniqueID(parentInstance, propName);

            var reference = currentValue;

            if (reference == null)
            {
                reference = stateManager.GetObject(relativeUid, isNew: isNew) as StateObjectPointerReference;
            }
            //We need to remove the pointer;
            if (reference != null)
            {
                //	We need to remove the Reference to the value if present and if it's not a
                //StateObjectPointerReferenceSuperValueBase
                if (!(reference is StateObjectPointerReferenceSuperValueBase))
                {
                    stateManager.ReferencesManager.RemoveReference(reference, reference.Target);
                }
                // Let's check if the existing reference is compatible with the newValue to
                //remove it or if the value being set is null as well.
                if (newValueObj == null || !reference.IsCompatibleWith(newValueObj))
                {
                    //If the Reference is not compatible then we need to remove it to get a new one.
                    stateManager.RemoveObject(relativeUid, true);
                    reference = null;
                }
            }
            //Only if the newValue is not null we need a reference, otherwise lets avoid the overhead.
            if (newValueObj != null && reference == null)
            {
                //Gets the reference for the property.
                reference = GetReference(propEx, parentInstance, newValueObj);
            }
            //No reference, no value...We don't need to do anything else.
            else if (newValueObj == null && reference == null)
            {
                return;
            }

            //Once we got the Reference let's update it.
            UpdateReferenceValue(stateManager, reference, parentInstance, newValueObj);
        }
Example #29
0
 /// <summary>
 /// NOTE: this method is called *ONLY* if the object DOES not come from storage
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="parameters"></param>
 /// <param name="t"></param>
 /// <param name="isRecovedFromStorage"></param>
 private static void InitializeObject(StateManager stateManager, IIocContainer container, IStateObject obj, object[] parameters, Type t, IIocContainerFlags flags)
 {
     if ((flags & IIocContainerFlags.IsSinglenton) == IIocContainerFlags.IsSinglenton)
     {
         //Unique ID
         obj.UniqueID = UniqueIDGenerator.GetSinglentonUniqueId(t);
     }
     else
     {
         //If it doesn't come from storage we must setup the UniqueID
         //that will be use later on for persistance
         if (!StateManager.IsRootLevelObject(obj))
         {
             obj.UniqueID = stateManager.UniqueIDGenerator.GetUniqueIDForTemporaryObject();
             //A new temparary object was created and it's in resolution.
             stateManager.AddIDInResolution(obj.UniqueID);
         }
         else
         {
             if (obj is IModel)
             {
                 obj.UniqueID = stateManager.UniqueIDGenerator.GetUniqueIDForModel();
             }
             else
             {
                 obj.UniqueID = stateManager.UniqueIDGenerator.GetUniqueID();
             }
         }
     }
     stateManager.AddNewObject(obj);
     if (obj is IDependentViewModel && (flags & IIocContainerFlags.NoBuild) != IIocContainerFlags.NoBuild)
     {
         try
         {
             ViewManager.Instance.Events.Suspend();
             ((IDependentViewModel)obj).Build(container);
         }
         finally
         {
             ViewManager.Instance.Events.Resume();
         }
         /* IDependants are now iLogic so this properties are injected in ILogic resolve code */
     }
 }
        public void UnSubscribe(string eventId, IStateObject source, string methodName)
        {
            eventId = eventId.ToUpper();
            var promisesInfo = HasSubscribers(eventId, source) as PromisesInfo;

            if (promisesInfo != null)
            {
                methodName = methodName.ToUpper();
                promisesInfo.Remove(methodName);
                var eventSubscriptionId = UniqueIDGenerator.GetEventRelativeUniqueID(source, methodName + eventId);
                _stateManager.RemoveObject(eventSubscriptionId, true);

                if (promisesInfo.IsEmpty())
                {
                    eventSubscriptionId = UniqueIDGenerator.GetEventRelativeUniqueID(source, eventId);
                    _stateManager.RemoveObject(eventSubscriptionId, true);
                }
            }
        }