Exemple #1
0
        public ApplicationSkeleton(
            ApplicationModel <ApplicationSPI> applicationModel,
            IEnumerable <Tuple <CompositeModelType, CompositeModelTypeModelScopeSupport> > compositeModelTypeSupport,
            String name,
            String mode,
            String version
            )
        {
            this._model = applicationModel;
            this._collectionsFactory = applicationModel.CollectionsFactory;
            this._name    = name;
            this._mode    = mode;
            this._version = version;
            this._constraintInstancePools = new
#if SILVERLIGHT
                                            Dictionary <Type, InstancePool <Object> >();
#else
                                            System.Collections.Concurrent.ConcurrentDictionary <Type, InstancePool <Object> >();
#endif

            this._compositeModelTypeSupport = this._model.CollectionsFactory.NewDictionaryProxy <CompositeModelType, CompositeModelTypeInstanceScopeSupport>(compositeModelTypeSupport.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2.CreateInstanceScopeSupport())).CQ;

            this._activationState = (Int32)ActivationState.PASSIVE;
            //this._disposedState = Convert.ToInt32( false );
            this._activationInProgress  = null;
            this._passivationInProgress = null;
            this._cancelTokenSource     = new CancellationTokenSource();
        }
Exemple #2
0
        public static Boolean PerformPassivation(ref Int32 transitionState, ref InProgressTracker passivationInProgress, InProgressTracker activationInProgress, Int32 waitTime, Action passivationAction)
        {
            Int32   initialState = (Int32)(new InProgressTracker().Equals(activationInProgress) ? ActivationState.DURING_ACTIVATION : ActivationState.ACTIVE);
            Int32   prevState;
            Boolean actionInvoked;
            Boolean tryAgain;

#if SILVERLIGHT
            using (var waitEvt = new ManualResetEvent(false))
#else
            using (var waitEvt = new ManualResetEventSlim(false))
#endif
            {
                do
                {
                    prevState = ApplicationSkeleton.ThreadsafeStateTransition(ref transitionState, initialState, (Int32)ActivationState.DURING_PASSIVATION, (Int32)ActivationState.PASSIVE, false, ref passivationInProgress, waitTime, passivationAction);

                    actionInvoked = prevState == initialState;
                    tryAgain      = !actionInvoked && prevState != (Int32)ActivationState.PASSIVE && prevState != (Int32)ActivationState.DURING_PASSIVATION;
                    if (tryAgain && initialState == (Int32)ActivationState.ACTIVE)
                    {
                        // Wait if we are not inside activation action,
                        // and if transition state change failed because activation is in progress.
#if SILVERLIGHT
                        waitEvt.WaitOne(waitTime);
#else
                        waitEvt.Wait(waitTime);
#endif
                    }
                } while (tryAgain);
            }
            return(actionInvoked);
        }
        internal ServiceCompositeInstanceImpl(CompositeInstanceStructureOwner structureOwner, CompositeModel model, IEnumerable <Type> publicCompositeType, UsesContainerQuery usesContainer, String serviceID, MainCompositeConstructorArguments mainCtorArgs)
            : base(structureOwner, model, publicCompositeType, usesContainer, mainCtorArgs)
        {
            var publicCtors = mainCtorArgs.Arguments;

            this._activationState = (Int32)ActivationState.PASSIVE;

            this._activationInProgress = null;
            this._activationAction     = (Action)publicCtors[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX + COMPOSITE_CTOR_ADDITIONAL_PARAMS_COUNT];

            this._passivationInProgress = null;
            this._passivationAction     = (Action)publicCtors[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX + COMPOSITE_CTOR_ADDITIONAL_PARAMS_COUNT + 1];

            this._serviceID = serviceID;

            this._activatingAllowed = (Int32)ActivatingAllowed.ALLOWED;
            this._needToSetIdentity = Convert.ToInt32(true);
        }
Exemple #4
0
        public static Boolean PerformActivation(ref Int32 transitionState, ref InProgressTracker activationInProgress, InProgressTracker passivationInProgress, Int32 waitTime, Boolean throwIfActivatingWithinPassivation, Action activationAction)
        {
            var passivationInProgressBool = new InProgressTracker().Equals(passivationInProgress);

            if (throwIfActivatingWithinPassivation && passivationInProgressBool)
            {
                // Trying to activate within passivation => not possible
                throw new InvalidOperationException("Can not activate from within passivation.");
            }

            Boolean result;
            Int32   prevState;
            Boolean tryAgain;

#if SILVERLIGHT
            using (var waitEvt = new ManualResetEvent(false))
#else
            using (var waitEvt = new ManualResetEventSlim(false))
#endif
            {
                do
                {
                    prevState = ThreadsafeStateTransition(ref transitionState, (Int32)ActivationState.PASSIVE, (Int32)ActivationState.DURING_ACTIVATION, (Int32)ActivationState.ACTIVE, true, ref activationInProgress, waitTime, activationAction);

                    result = prevState == (Int32)ActivationState.PASSIVE;
                    // Try again only if we are waiting for passivation to end in another thread
                    tryAgain = !result && prevState == (Int32)ActivationState.DURING_PASSIVATION && !passivationInProgressBool;
                    if (tryAgain)
                    {
#if SILVERLIGHT
                        waitEvt.WaitOne(waitTime);
#else
                        waitEvt.Wait(waitTime);
#endif
                    }
                } while (tryAgain);
            }

                   return(result);
        }
Exemple #5
0
        public static Int32 ThreadsafeStateTransition(ref Int32 transitionState, Int32 initialState, Int32 intermediate, Int32 final, Boolean rollbackStateOnFailure, ref InProgressTracker inProgressTracker, Int32 waitTime, Action transitionAction)
        {
            Int32 oldValue = Interlocked.CompareExchange(ref transitionState, intermediate, initialState);

            if (initialState == oldValue)
            {
                Boolean finished = false;
                try
                {
                    Interlocked.Exchange(ref inProgressTracker, new InProgressTracker());

                    transitionAction();

                    finished = true;
                }
                finally
                {
                    Interlocked.Exchange(ref inProgressTracker, null);
                    Interlocked.Exchange(ref transitionState, finished || !rollbackStateOnFailure ? final : initialState);
                }
            }
            else if (final != oldValue && !(new InProgressTracker()).Equals(inProgressTracker))
            {
                // We are entering mid-transition from another thread
#if SILVERLIGHT
                using (var evt = new ManualResetEvent(false))
#else
                using (var evt = new ManualResetEventSlim(false))
#endif
                {
                    while (inProgressTracker != null)
                    {
                        // Wait
#if SILVERLIGHT
                        evt.WaitOne(waitTime);
#else
                        evt.Wait(waitTime);
#endif
                    }
                }
            }
            return(oldValue);
        }
        protected CompositeInstanceImpl(
            CompositeInstanceStructureOwner structureOwner,
            CompositeModel model,
            IEnumerable <Type> publicCompositeTypes,
            UsesContainerQuery usesContainer,
            MainCompositeConstructorArguments publicCtorArgsObject
            )
        {
            ArgumentValidator.ValidateNotNull("Structure owner", structureOwner);
            ArgumentValidator.ValidateNotNull("Composite model", model);
            ArgumentValidator.ValidateNotEmpty("Composite type", publicCompositeTypes);
            ArgumentValidator.ValidateNotNull("Container for objects to be used in fragment creation", usesContainer);

            this._structureOwner = structureOwner;
            var application = this._structureOwner.Application;

            this._modelInfo = this._structureOwner.ModelInfoContainer.GetCompositeModelInfo(model);
            if (publicCompositeTypes.Any(pcType => pcType.ContainsGenericParameters()))
            {
                throw new InternalException("With given public composite types {" + String.Join(", ", publicCompositeTypes) + "} and public composite type in model being [" + String.Join(", ", model.PublicTypes) + "], the public composite types contained non-closed generic parameters.");
            }
            this._usesContainer = usesContainer;

            this._isPrototype = (Int32)PrototypeState.PROTOTYPE;

            this._invocationInfos = new Lazy <ThreadLocal <Stack <InvocationInfo> > >(() => new ThreadLocal <Stack <InvocationInfo> >(() => new Stack <InvocationInfo>()), LazyThreadSafetyMode.PublicationOnly);

            var composites = application.CollectionsFactory.NewDictionaryProxy <Type, Object>();
            var cProps     = application.CollectionsFactory.NewListProxy(new List <CompositeProperty>(model.Methods.Count * 2));
            var cEvents    = application.CollectionsFactory.NewListProxy(new List <CompositeEvent>(model.Methods.Count * 2));

            var publicTypeGenResult = this._modelInfo.Types;
            var factory             = publicTypeGenResult.CompositeFactory;

            var gArgs = publicTypeGenResult.PublicCompositeGenericArguments.Count == 0 ? null : new Type[publicTypeGenResult.GeneratedMainPublicType.GetGenericArguments().Length];

            this._gArgs = gArgs;

            foreach (var pType in publicCompositeTypes)
            {
                ListQuery <Int32> gArgInfo = null;
                if (publicTypeGenResult.PublicCompositeGenericArguments.TryGetValue(pType.GetGenericDefinitionIfGenericType(), out gArgInfo))
                {
                    var declaredGArgs = pType.GetGenericArguments();
                    for (Int32 i = 0; i < declaredGArgs.Length; ++i)
                    {
                        gArgs[gArgInfo[i]] = declaredGArgs[i];
                    }
                }
            }

            if (gArgs != null && gArgs.Any(gArg => gArg == null))
            {
                throw new InvalidCompositeTypeException(publicCompositeTypes, "Could not find suitable generic argument for all public types of composite " + this._modelInfo.Model + ".");
            }

            Action prePrototypeAction = null;
            var    publicCtorArgs     = new Object[publicTypeGenResult.MaxParamCountForCtors];

            Object[] compositeCtorParams = null;
            foreach (var genType in publicTypeGenResult.GeneratedPublicTypes)
            {
                var isMainType  = genType.GeneratedType.Equals(this._modelInfo.Types.GeneratedMainPublicType);
                var curCtorArgs = isMainType ? publicCtorArgs : compositeCtorParams;
                this.SetCompositeCtorArgs(ref curCtorArgs, cProps.AO, cEvents.AO);
                var publicComposite = factory.CreateInstance(genType.GeneratedTypeID, gArgs, curCtorArgs);
                foreach (var cType in this.GetTypeKeysForGeneratedType(publicComposite.GetType(), true, isMainType))
                {
                    composites[cType] = publicComposite;
                }

                if (isMainType)
                {
                    if (publicCtorArgsObject != null)
                    {
                        publicCtorArgsObject.Arguments = curCtorArgs;
                    }
                    prePrototypeAction     = (Action)publicCtorArgs[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX];
                    this._prototypeAction  = (Action)publicCtorArgs[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX + 1];
                    this._checkStateFunc   = (Action <IDictionary <QualifiedName, IList <ConstraintViolationInfo> > >)publicCtorArgs[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX + 2];
                    this._compositeMethods = new Lazy <MethodInfo[]>(() => ((CompositeCallbacks)publicComposite).GetCompositeMethods(), LazyThreadSafetyMode.ExecutionAndPublication);
                }
            }

            this._isPrototypeTransitionInProgress = null;

            this.SetCompositeCtorArgs(ref compositeCtorParams, cProps.AO, cEvents.AO);

            foreach (var typeGenResult in publicTypeGenResult.PrivateCompositeGenerationResults)
            {
                var privateComposite = factory.CreateInstance(typeGenResult.GeneratedTypeID, gArgs, compositeCtorParams);
                foreach (var cTypeOrParent in this.GetTypeKeysForGeneratedType(privateComposite.GetType(), false, false))
                {
                    composites.Add(cTypeOrParent, privateComposite);
                }
            }

            this._composites = composites.CQ;

            this._methodsToModels = new Lazy <DictionaryQuery <MethodInfo, CompositeMethodModel> >(() =>
            {
                var retVal   = new Dictionary <MethodInfo, CompositeMethodModel>();
                var cMethods = this._compositeMethods.Value;
                for (var i = 0; i < cMethods.Length; ++i)
                {
                    var cm = cMethods[i];
                    retVal.Add(cm, this._modelInfo.Model.Methods[i]);
                }
                return(application.CollectionsFactory.NewDictionaryProxy(retVal).CQ);
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            this._state = new CompositeStateImpl(this._structureOwner.Application.CollectionsFactory, cProps.CQ, cEvents.CQ);

            this._fragmentInstancePools = this.CreatePoolDictionary <FragmentTypeGenerationResult, FragmentInstance>(
                gArgs,
                this._modelInfo.Types.FragmentGenerationResults.Where(fGenResult => fGenResult.InstancePoolRequired),
                application.CollectionsFactory);
            var fInstances = application.CollectionsFactory.NewDictionaryProxy(new Dictionary <Type, FragmentInstance>());

            foreach (var genResult in publicTypeGenResult.FragmentGenerationResults.Where(val => !val.InstancePoolRequired))
            {
                var genType = genResult.GeneratedType;
                if (gArgs != null)
                {
                    genType = genType.MakeGenericType(gArgs);
                }
                else if (genType.ContainsGenericParameters())
                {
                    throw new InternalException("Could not find generic arguments for fragment type " + genResult.DeclaredType + ".");
                }
                fInstances.Add(genType, new FragmentInstanceImpl());
            }
            this._fragmentInstances             = fInstances.CQ;
            this._concernInvocationInstances    = this.CreatePoolDictionary <TypeGenerationResult, FragmentDependant>(gArgs, publicTypeGenResult.ConcernInvocationGenerationResults, application.CollectionsFactory);
            this._sideEffectInvocationInstances = this.CreatePoolDictionary <TypeGenerationResult, FragmentDependant>(gArgs, publicTypeGenResult.SideEffectGenerationResults, application.CollectionsFactory);
            this._constructorsForFragments      = application.CollectionsFactory.NewDictionaryProxy <Type, ListQuery <FragmentConstructorInfo> >(this._fragmentInstancePools.Keys.Concat(this._fragmentInstances.Keys)
                                                                                                                                                 .ToDictionary(
                                                                                                                                                     fType => fType,
                                                                                                                                                     fType => application.CollectionsFactory.NewListProxy(fType
                                                                                                                                                                                                          .GetAllInstanceConstructors()
                                                                                                                                                                                                          .Select(fCtor =>
            {
                Int32 idx;
                return(fCtor.TryGetConstructorModelIndex(out idx) ?
                       new FragmentConstructorInfo(model.Constructors[idx], fCtor) :
                       null);
            })
                                                                                                                                                                                                          .Where(i => i != null)
                                                                                                                                                                                                          .ToList()
                                                                                                                                                                                                          ).CQ
                                                                                                                                                     )).CQ;

            if (prePrototypeAction != null)
            {
                prePrototypeAction();
            }
        }