//****************************************************************
        // Add Listener - Methods for registering listeners with this
        // notification center.
        //****************************************************************

        /// <summary>
        /// Registers the listener to receive notifications with the specified
        /// notification name and/or containing the given object.
        /// </summary>
        /// <param name="listener">The listener to register.</param>
        /// <param name="callbackMethodName">
        /// The name of the method to invoke on the listener.
        /// </param>
        /// <param name="notificationName">
        /// The name of notifications the listener would like to receive.
        /// </param>
        /// <param name="obj">
        /// The object for which the listener would like to recieve associated notifications.
        /// </param>
        /// <remarks>
        /// When a matching notification is posted, the 'callBackMethodName' message will be
        /// sent to the listener with a single PNotification argument.  If the notification
        /// name is null, the listener will receive all notifications with an object matching
        /// the given object. If the object is null, the listener will receive all
        /// notifications with the notification name.
        /// </remarks>
        public virtual void AddListener(Object listener, String callbackMethodName, String notificationName, Object obj)
        {
            ProcessDeadKeys();

            Object     name       = notificationName;
            MethodInfo methodInfo = null;

            try {
                methodInfo = listener.GetType().GetMethod(callbackMethodName, new Type[] { typeof(PNotification) });
            } catch (ArgumentNullException e) {
                System.Console.WriteLine(e.StackTrace);
                return;
            }

            if (name == null)
            {
                name = NULL_MARKER;
            }
            if (obj == null)
            {
                obj = NULL_MARKER;
            }

            Object key = new CompoundKey(name, obj);
            Object val = new CompoundValue(listener, methodInfo);

            IList list = (IList)listenersMap[key];

            if (list == null)
            {
                list = new ArrayList();
                listenersMap.Add(new CompoundKey(name, obj), list);
            }

            if (!list.Contains(val))
            {
                list.Add(val);
            }
        }
        /// <summary>
        /// Build a proxy type which implements the requested interface by redirecting all calls to the supplied object type.
        /// </summary>
        /// <param name="interfaceType">An interface type to implement.</param>
        /// <param name="objectTypes">Array of types which expected to have all members of the given interface.</param>
        /// <returns>The duck object type.</returns>
        public static Type?GetDuckType(this Type interfaceType, Type[] objectTypes)
        {
            if (!interfaceType.IsInterface)
            {
                throw new ArgumentException("'interfaceType' must be an interface.", nameof(interfaceType));
            }
            //if (!interfaceType.IsPublic && !interfaceType.IsNestedPublic)
            //	throw new ArgumentException("The interface must be public.", nameof(interfaceType));

            Dictionary <object, Type?> types;

            lock (_duckTypes)
                if (!_duckTypes.TryGetValue(interfaceType, out types))
                {
                    _duckTypes.Add(interfaceType, types = new Dictionary <object, Type?>());
                }

            var objects = new object[objectTypes.Length];

            for (var i = 0; i < objectTypes.Length; i++)
            {
                objects[i] = objectTypes[i];
            }

            Type?  type;
            object key = new CompoundValue(objects);

            lock (types) if (!types.TryGetValue(key, out type))
                {
                    type = TypeFactory.GetType(
                        new CompoundValue(interfaceType, key),
                        interfaceType,
                        new DuckTypeBuilder(MustImplementAttribute.Aggregate, interfaceType, objectTypes));

                    types.Add(key, type);
                }

            return(type);
        }
Example #3
0
        /// <summary>
        /// Build a proxy type which implements the requested interface by redirecting all calls to the supplied object type.
        /// </summary>
        /// <param name="interfaceType">An interface type to implement.</param>
        /// <param name="objectTypes">Array of types which expected to have all members of the given interface.</param>
        /// <returns>The duck object type.</returns>
        public static Type GetDuckType(Type interfaceType, Type[] objectTypes)
        {
            if (interfaceType == null)
            {
                throw new ArgumentNullException("interfaceType");
            }
            if (!interfaceType.IsInterface)
            {
                throw new ArgumentException(Resources.DuckTyping_InterfaceTypeMustBeAnInterface, "interfaceType");
            }
            if (!interfaceType.IsPublic && !interfaceType.IsNestedPublic)
            {
                throw new ArgumentException(Resources.DuckTyping_InterfaceMustBePublic, "interfaceType");
            }

            Dictionary <object, Type> types;

            lock (_duckTypes)
                if (!_duckTypes.TryGetValue(interfaceType, out types))
                {
                    _duckTypes.Add(interfaceType, types = new Dictionary <object, Type>());
                }

            object key = new CompoundValue(objectTypes);
            Type   type;

            lock (types) if (!types.TryGetValue(key, out type))
                {
                    type = TypeFactory.GetType(
                        new CompoundValue(interfaceType, key),
                        interfaceType,
                        new DuckTypeBuilder(MustImplementAttribute.Aggregate, interfaceType, objectTypes));

                    types.Add(key, type);
                }

            return(type);
        }
Example #4
0
        /// <inheritdoc />
        public override void VisitCompoundValue(CompoundValue value)
        {
            switch (operation)
            {
            case Operations.Identical:
                result = OutSet.CreateBool(false);
                break;

            case Operations.NotIdentical:
                result = OutSet.CreateBool(true);
                break;

            default:
                result = Comparison.RightAlwaysGreater(OutSet, operation);
                if (result != null)
                {
                    break;
                }

                base.VisitCompoundValue(value);
                break;
            }
        }
Example #5
0
            public static void ClearCache(CacheAspect aspect, CompoundValue key)
            {
                lock (RegisteredAspects.SyncRoot)
                {
                    if (!aspect.HasCache)
                    {
                        return;
                    }

                    if (!Monitor.TryEnter(aspect.CacheSyncRoot, 10))
                    {
                        return;
                    }
                    try
                    {
                        _objectsExpired += 1;
                        aspect.Cache.Remove(key);
                    }
                    finally
                    {
                        Monitor.Exit(aspect.CacheSyncRoot);
                    }
                }
            }
Example #6
0
        /// <summary>
        /// Invokes a web method asynchronously.
        /// </summary>
        /// <param name="methodName">Web method name.</param>
        /// <param name="asyncCallState">Call state handle.
        /// Upon return, may be used to cancel the call</param>
        /// <param name="parameters">Web method parameters.</param>
        /// <param name="callback">Callback method to process the result.</param>
        /// <param name="exceptionHandler">Fail handler.</param>
        /// <seealso cref="CancelAsync(AsyncCallState)"/>
        public void InvokeAsync(
            string methodName,
            AsyncCallState asyncCallState,
            Action <Exception> exceptionHandler,
            Delegate callback,
            params object[]   parameters)
        {
#if DEBUG
            var sw = Stopwatch.StartNew();
#endif

            if (asyncCallState != null)
            {
#if DEBUG
                Debug.WriteLineIf(TS.TraceVerbose && asyncCallState.PendingCall != null,
                                  string.Format("Cancelling async call {0}/{1}",
                                                Url, methodName), TS.DisplayName);
#endif
                CancelAsync(asyncCallState);
            }

            var exceptionCallback = exceptionHandler ?? delegate(Exception ex)
            {
                if (ex is WebException)
                {
                    var webException = (WebException)ex;

                    // Request cancelled.
                    //
                    if (webException.Status == WebExceptionStatus.RequestCanceled)
                    {
                        OnWebOperationCancelled(methodName, parameters);
                        return;
                    }
                }

                // Check for retry.
                //
                if (OnWebOperationException(methodName, parameters, ex))
                {
                    InvokeAsync(methodName, asyncCallState, exceptionHandler, callback, parameters);
                }
            };

            System.Threading.SendOrPostCallback sendCallback = delegate(object obj)
            {
#if DEBUG
                Debug.WriteLineIf(TS.TraceVerbose,
                                  string.Format("Async call {0}/{1} = {2} msec.",
                                                Url, methodName, sw.ElapsedMilliseconds), TS.DisplayName);
#endif

                var ea = (InvokeCompletedEventArgs)obj;

                if (ea.Error != null)
                {
                    // Internal redirection
                    //
                    if (ea.Error is WebException && ((WebException)ea.Error).Status == WebExceptionStatus.ReceiveFailure)
                    {
                        InvokeAsync(methodName, asyncCallState, exceptionHandler, callback, parameters);
                    }
                    else
                    {
                        exceptionCallback(ea.Error);
                    }
                }
                else if (ea.Cancelled || (asyncCallState != null && ea.UserState != asyncCallState.PendingCall))
                {
                    exceptionCallback(new WebException(methodName, WebExceptionStatus.RequestCanceled));
                }
                else
                {
                    callback.DynamicInvoke(AcceptChanges(ea.Results));
                }

                if (asyncCallState != null && ea.UserState == asyncCallState.PendingCall)
                {
                    asyncCallState.PendingCall = null;
                }
            };

            object cookie = new CompoundValue(methodName, parameters);

            if (asyncCallState != null)
            {
                asyncCallState.PendingCall = cookie;
            }

            InvokeAsync(methodName, parameters, sendCallback, cookie);
        }
Example #7
0
 void act([Domain("P")] CompoundValue i /* Sequence<int> x */)
 {
 }
Example #8
0
		protected static CacheAspectItem GetItem(IDictionary cache, CompoundValue key)
		{
			var obj = cache[key];

			if (obj == null)
				return null;

			var wr = obj as WeakReference;

			if (wr == null)
				return (CacheAspectItem)obj;

			obj = wr.Target;

			if (obj != null)
				return (CacheAspectItem)obj;

			cache.Remove(key);

			return null;
		}
Example #9
0
        protected override void AfterCall(InterceptCallInfo info)
        {
            if (!IsEnabled)
            {
                return;
            }

            IDictionary cache = GetCache(info);

            lock (cache.SyncRoot)
            {
                CompoundValue key = (CompoundValue)info.Items["CacheKey"];

                if (key == null)
                {
                    return;
                }

                int  maxCacheTime = MaxCacheTime;
                bool isWeak       = IsWeak;

                if (!string.IsNullOrEmpty(info.ConfigString))
                {
                    ConfigParameters cp = GetConfigParameters(info);

                    if (cp.MaxCacheTime != null)
                    {
                        maxCacheTime = (int)cp.MaxCacheTime;
                    }
                    if (cp.IsWeak != null)
                    {
                        isWeak = (bool)cp.IsWeak;
                    }
                }

                CacheAspectItem item = new CacheAspectItem();

                item.ReturnValue  = info.ReturnValue;
                item.MaxCacheTime = maxCacheTime == int.MaxValue || maxCacheTime < 0?
                                    DateTime.MaxValue:
                                    DateTime.Now.AddMilliseconds(maxCacheTime);

                ParameterInfo[] pis = info.CallMethodInfo.Parameters;

                int n = 0;

                foreach (ParameterInfo pi in pis)
                {
                    if (pi.ParameterType.IsByRef)
                    {
                        n++;
                    }
                }

                if (n > 0)
                {
                    item.RefValues = new object[n];

                    n = 0;

                    for (int i = 0; i < pis.Length; i++)
                    {
                        if (pis[i].ParameterType.IsByRef)
                        {
                            item.RefValues[n++] = info.ParameterValues[i];
                        }
                    }
                }

                cache[key] = isWeak? (object)new WeakReference(item): item;
            }
        }
		//****************************************************************
		// Add Listener - Methods for registering listeners with this
		// notification center.
		//****************************************************************

		/// <summary>
		/// Registers the listener to receive notifications with the specified
		/// notification name and/or containing the given object.
		/// </summary>
		/// <param name="listener">The listener to register.</param>
		/// <param name="callbackMethodName">
		/// The name of the method to invoke on the listener.
		/// </param>
		/// <param name="notificationName">
		/// The name of notifications the listener would like to receive.
		/// </param>
		/// <param name="obj">
		/// The object for which the listener would like to recieve associated notifications.
		/// </param>
		/// <remarks>
		/// When a matching notification is posted, the 'callBackMethodName' message will be
		/// sent to the listener with a single PNotification argument.  If the notification
		/// name is null, the listener will receive all notifications with an object matching
		/// the given object. If the object is null, the listener will receive all
		/// notifications with the notification name.
		/// </remarks>
		public virtual void AddListener(Object listener, String callbackMethodName, String notificationName, Object obj) {
			ProcessDeadKeys();

			Object name = notificationName;
			MethodInfo methodInfo = null;

			try {
				methodInfo = listener.GetType().GetMethod(callbackMethodName, new Type[] { typeof(PNotification) });
			} catch (ArgumentNullException e) {
				System.Console.WriteLine(e.StackTrace);
				return;
			}
		
			if (name == null) name = NULL_MARKER;
			if (obj == null) obj = NULL_MARKER;

			Object key = new CompoundKey(name, obj);
			Object val = new CompoundValue(listener, methodInfo);

			IList list = (IList) listenersMap[key];
			if (list == null) {
				list = new ArrayList();
				listenersMap.Add(new CompoundKey(name, obj), list);
			}

			if (!list.Contains(val)) {
				list.Add(val);
			}
		}
Example #11
0
 /// <inheritdoc />
 public override void VisitCompoundValue(CompoundValue value)
 {
     result = value;
 }
Example #12
0
			public static void ClearCache(IDictionary cache, CompoundValue key)
			{
				lock (RegisteredAspects.SyncRoot)
					lock (cache.SyncRoot)
					{
						_objectsExpired += 1;
						cache.Remove(key);
					}
			}
Example #13
0
 /// <inheritdoc />
 public override void VisitCompoundValue(CompoundValue value)
 {
     preservedValues.Add(value);
 }
Example #14
0
        public Between <TObj, CompoundValue <T1, T2> > AndIncluding(T1 p1, T2 p2)
        {
            var endAt = new CompoundValue <T1, T2>(p1);

            return(new Between <TObj, CompoundValue <T1, T2> >(this.IndexedValue, this.StartAt, this.IncludeStartAt, endAt, true));
        }
Example #15
0
 internal BetweenBuilder(BaseIndexedValue <TObj, CompoundValue <T1, T2> > indexedValue, CompoundValue <T1, T2> startAt, bool includeStartAt)
 {
     this.IndexedValue   = indexedValue;
     this.StartAt        = startAt;
     this.IncludeStartAt = includeStartAt;
 }
Example #16
0
			public static void ClearCache(CacheAspect aspect, CompoundValue key)
			{
				lock (RegisteredAspects.SyncRoot)
				{
					if (!aspect.HasCache)
						return;

					if (!Monitor.TryEnter(aspect.CacheSyncRoot, 10))
						return;
					try
					{
						_objectsExpired += 1;
						aspect.Cache.Remove(key);
					}
					finally
					{
						Monitor.Exit(aspect.CacheSyncRoot);
					}
				}
			}