private Delegate PublishInternal(EventPromiseInfo eventHandlerInfo, string eventId, IStateObject source, bool doNotCall, params object[] args)
        {
            var      delegateType  = TypeCacheUtils.GetType(eventHandlerInfo.DelegateType);
            Delegate eventDelegate = PromiseUtils.FromContinuationInfo(delegateType, eventHandlerInfo, source) as Delegate;

            if (eventDelegate == null)
            {
                TraceUtil.TraceError("EventAggregator::PublishInternal Error publishing event. Continuation could not be restored");
                return(null);
            }
            if (doNotCall)
            {
                return(eventDelegate);
            }
            TraceUtil.TraceInformation("Publishing event " + eventId);
            if (eventDelegate != null)
            {
                try
                {
                    eventDelegate.Method.Invoke(eventDelegate.Target, args);
                }
                catch (TargetInvocationException tiex)
                {
                    var baseException = tiex.GetBaseException();
                    PreserveStackTrace(baseException);
                    throw baseException;
                }
            }
            return(eventDelegate);
        }
            private object ReadInputAsType()
            {
                object val = reader.Value; reader.Read();

                val = TypeCacheUtils.GetType((string)val);
                return(val);
            }
        public T PublishDelegate <T>(string eventId)
        {
            Delegate result = null;

            var eventHandlerInfo = _stateManager.GetObject(eventId) as EventPromiseInfo;

            if (eventHandlerInfo != null)
            {
                var delegateType = TypeCacheUtils.GetType(eventHandlerInfo.DelegateType);
                result = PromiseUtils.FromContinuationInfo(delegateType, eventHandlerInfo) as Delegate;
            }
            return(result == null ? default(T) : (T)(object)Delegate.CreateDelegate(typeof(T), result.Target, result.Method));
        }
        private static void RestoreDelegateField(BinaryReader reader, object instance, FieldInfo field)
        {
            //First we retrieve the ID for the target object of delegate
            var targetID = reader.ReadString();

            if (targetID == "NULL")
            {
                //This is an static method
                var declaringTypeName = reader.ReadString();
                var declaringType     = TypeCacheUtils.GetType(declaringTypeName);
            }
            else if (targetID == "INST")
            {
                var methodName = reader.ReadString();
                //Is this an Action<> or Func<>
                if (field.FieldType.IsGenericType)
                {
                    Type[] parameterTypes = ExtractParameterTypesForDelegateInField(field);
                    var    methodInfo     = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, parameterTypes, null);
                    var    delegateValue  = CreateDelegateFromMethodInfo(instance, methodInfo);
                    field.SetValue(instance, delegateValue);
                }
            }
            else
            {
                var targetInstance = StateManager.Current.GetObject(targetID);
                if (targetInstance == null)
                {
                    throw new NotSupportedException("Instance for delegate could not be retrieved");
                }
                //This is an IStateObject
                var methodName = reader.ReadString();
                //Is this an Action<> or Func<>
                if (field.FieldType.IsGenericType)
                {
                    Type[] parameterTypes = ExtractParameterTypesForDelegateInField(field);
                    var    methodInfo     = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, parameterTypes, null);
                    var    delegateValue  = CreateDelegateFromMethodInfo(targetInstance, methodInfo);
                    field.SetValue(instance, delegateValue);
                }
            }
        }
        public object RawToObject(string uniqueId, object rawData)
        {
            if (rawData != null)
            {
                string raw = (string)rawData;
                string typeName;
                if (TypeCacheUtils.ISSAFETOSHORTENALLTYPES && TypeCacheUtils.SHORTENTYPENAME)
                {
                    typeName = raw.Substring(0, TypeCacheUtils.PADDEDCONTRACTEDTYPENAME);
                }
#pragma warning disable 0162
                else
                {
                    var match = regex.Match(raw);
                    if (!match.Success)
                    {
                        TraceUtil.TraceError("Error in StorageSerializerUsingJSONNET.rawToData while retrieve Type Descriptor from raw string. Aborting deserialization and returning null for UniqueId {0}", uniqueId);
                        return(null);
                    }
                    typeName = match.Groups[1].Value;
                }
#pragma warning restore 0162
                //At this point type still contains padding spaces
                int           offset     = typeName.Length;
                List <string> dependents = null;
                if (raw[typeName.Length] != '?')
                {
                    var endOfDependentsIndex = raw.IndexOf('?');
                    var dependentsStr        = raw.Substring(typeName.Length, endOfDependentsIndex - offset);
                    dependents = dependentsStr.Split(',').ToList();
                    offset    += dependentsStr.Length + 1;
                }
                else
                {
                    offset += 1;
                }
                raw = raw.Substring(offset);
                //Remove padding spaces
                var    type      = TypeCacheUtils.GetType(typeName);
                object actualRes = null;
                var    interceptionCurrentValue = LazyBehaviour.DisableInterception;
                try
                {
                    LazyBehaviour.DisableInterception = true;
                    actualRes = IocContainerImplWithUnity.Current.Resolve(type, null, IIocContainerFlags.RecoveredFromStorage);
                    var contract      = sessionStorageSerializer.ContractResolver.ResolveContract(type);
                    var jsonConverter = contract.Converter;
                    if (jsonConverter != null)
                    {
                        using (StringReader strReader = new StringReader(raw))
                            using (JsonTextReader reader = new JsonTextReader(strReader))
                            {
                                reader.ArrayPool = JsonArrayPool.Instance;
                                reader.Read();
                                jsonConverter.ReadJson(reader, type, actualRes, sessionStorageSerializer);
                            }
                    }
                    else
                    {
                        //None of the preset JSONConverters where used
                        //1. First check if the raw value is a JSON
                        if (raw.Length > 1)
                        {
                            if (raw[0] == '{')
                            {
                                using (JsonTextReader jsonReader = new JsonTextReader(new StringReader(raw)))
                                {
                                    jsonReader.ArrayPool = JsonArrayPool.Instance;
                                    sessionStorageSerializer.Populate(jsonReader, actualRes);
                                }
                            }
                            else
                            {
                                System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(actualRes.GetType());
                                if (converter.CanConvertFrom(typeof(string)))
                                {
                                    actualRes = converter.ConvertFrom(raw.Trim('"'));
                                }
                            }
                        }
                    }
                    //Once we have the uniqueID we need to make sure that the UniqueID is set
                    IStateObject asIStableObject = actualRes as IStateObject;
                    if (asIStableObject != null)
                    {
                        asIStableObject.UniqueID = uniqueId;
                    }
                }
                finally
                {
                    LazyBehaviour.DisableInterception = interceptionCurrentValue;
                }
                if (dependents != null)
                {
                    var dependentsC = actualRes as IDependentsContainer;
                    dependentsC.Dependents = dependents;
                }
                return(actualRes);
            }
            return(null);
        }
예제 #6
0
        object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            StateObjectPointer pointer = (StateObjectPointer)existingValue;

            reader.Read();
            var propertyName = reader.Value.ToString();

            if (propertyName == "p")
            {
                var uniqueIdforReferencedObject = reader.ReadAsString();
                pointer._targetUniqueId = uniqueIdforReferencedObject;
                return(pointer);
            }
            if (propertyName == "d")
            {
                reader.Read();
                var value = serializer.Deserialize(reader);
                ((StateObjectPointerReferenceSerializable)pointer).SuperTarget = value;
                return(pointer);
            }
            if (propertyName == "v" || propertyName == "u")
            {
                reader.Read();
                var type = TypeCacheUtils.GetType(reader.ReadAsString());
                if (type == typeof(object))
                {
                    return(new StateObjectPointerReferenceSuperValue());
                }
                else
                {
                    var    str   = reader.ReadAsString();
                    object value = null;
                    if (type.IsEnum)
                    {
                        value = Enum.Parse(type, str, true);
                    }
                    else if (typeof(decimal) == type)
                    {
                        value = decimal.Parse(str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    else if (typeof(double) == type)
                    {
                        value = double.Parse(str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        if (TypeCacheUtils.IsAnUserStructType(type))
                        {
                            value = JsonConvert.DeserializeObject(str, type);
                        }
                        else
                        {
                            value = System.Convert.ChangeType(str, type);
                        }
                    }

                    ((StateObjectPointerReferenceSuperValue)pointer).SuperTarget = value;
                    return(pointer);
                }
            }
            if (propertyName == "s")
            {
                //TODO surrogate
                var uniqueIDSurrogate = reader.ReadAsString();
                var superSurrogate    = pointer as StateObjectPointerReferenceSuperSurrogate;
                superSurrogate._targetSurrogateUniqueId = uniqueIDSurrogate;
                return(pointer);
            }

            throw new NotSupportedException();
        }
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type type = TypeCacheUtils.GetType(assemblyName, typeName);

            return(type);
        }
        internal static object FromContinuationInfo(Type type, EventPromiseInfo promise, IStateObject source = null)
        {
            try
            {
                var    methodDeclaringType = TypeCacheUtils.GetType(promise.DeclaringType);
                object targetInstance      = null;

                Type[] types = Type.EmptyTypes;
                if (promise.MethodArgs != null)
                {
                    var typesNames = promise.MethodArgs.Split(PIPE_SEPARATOR, StringSplitOptions.RemoveEmptyEntries);
                    types = new Type[typesNames.Length];
                    int i = 0;
                    foreach (var typeName in typesNames)
                    {
                        types[i++] = TypeCacheUtils.GetType(typeName);
                    }
                }

                if (promise.isLocalInstance && source != null)
                {
                    targetInstance = source;
                }
                else
                {
                    var pointer = promise.ObjectContainingMethod as StateObjectPointerReference;
                    if (pointer != null)
                    {
                        targetInstance = pointer.Target;
                    }
                    else
                    {
                        targetInstance = promise.ObjectContainingMethod;
                    }
                }


                if (targetInstance is StateObjectSurrogate)
                {
                    targetInstance = ((StateObjectSurrogate)targetInstance).Value;
                }
                if (targetInstance == null)
                {
                    //Was this an static method?
                    if (promise.TargetType == null)
                    {
                        //Yes static
                        var staticType   = TypeCacheUtils.GetType(promise.DeclaringType);
                        var staticmethod = staticType.GetMethod(promise.MethodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                        return(Delegate.CreateDelegate(type, staticmethod));
                    }
                    else
                    {
                        //Ok, it was a not an IStateObject object. It might have been
                        //a delegate from another class
                        //So we need to instantiate it and set it to targetInstance
                        var targetType = TypeCacheUtils.GetType(promise.TargetType);
                        targetInstance = Activator.CreateInstance(targetType);
                        if (promise.ContinuationFields != null)
                        {
                            //Pending Restore state
                        }
                    }
                }
                else
                {
                    //First check if method was on this targetInstance. Why not? Because it could have been on a form

                    if (typeof(ILogicView <IViewModel>).IsAssignableFrom(methodDeclaringType))
                    {
                        var instanceWithMethodDeclaredType = TypeCacheUtils.GetType(promise.TargetType);
                        var form = IocContainerImplWithUnity.Current.Resolve(instanceWithMethodDeclaredType, parameters: new object[] { (IViewModel)targetInstance });
                        targetInstance = form;
                    }
                }
                var method = methodDeclaringType.GetMethod(promise.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, new ReflectionBinderForPromisesResolution(), types, null);
                //If type is delegate then we must build a generic delegate from Action<> or Func<> helpers
                if (typeof(Delegate) == type)
                {
                    Type methodDelegateType = TypeCacheUtils.GetDelegateTypeBasedOnMethodParameters(method);
                    return(Delegate.CreateDelegate(methodDelegateType, targetInstance, method));
                }
                return(Delegate.CreateDelegate(type, targetInstance, method));
            }
            catch (Exception ex)
            {
                TraceUtil.TraceError("ViewManager::PromiseUtils::FromContinuationInfo error while trying to restore delegate from continuation " + ex.Message);
            }
            return(null);
        }