Esempio n. 1
0
        DelegateSerializationHolder(SerializationInfo info, StreamingContext ctx)
        {
            DelegateEntry entryChain = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));

            // Count the number of delegates to combine
            int           count = 0;
            DelegateEntry entry = entryChain;

            while (entry != null)
            {
                entry = entry.delegateEntry;
                count++;
            }

            // Deserializes and combines the delegates
            if (count == 1)
            {
                _delegate = entryChain.DeserializeDelegate(info);
            }
            else
            {
                Delegate[] delegates = new Delegate[count];
                entry = entryChain;
                for (int n = 0; n < count; n++)
                {
                    delegates[n] = entry.DeserializeDelegate(info);
                    entry        = entry.delegateEntry;
                }
                _delegate = Delegate.Combine(delegates);
            }
        }
Esempio n. 2
0
        public static void GetDelegateData(Delegate instance, SerializationInfo info, StreamingContext ctx)
        {
            // Fills a SerializationInfo object with the information of the delegate.

            Delegate[]    delegates = instance.GetInvocationList();
            DelegateEntry lastEntry = null;

            for (int n = 0; n < delegates.Length; n++)
            {
                Delegate      del         = delegates[n];
                string        targetLabel = (del.Target != null) ? ("target" + n) : null;
                DelegateEntry entry       = new DelegateEntry(del, targetLabel);

                if (lastEntry == null)
                {
                    info.AddValue("Delegate", entry);
                }
                else
                {
                    lastEntry.delegateEntry = entry;
                }

                lastEntry = entry;
                if (del.Target != null)
                {
                    info.AddValue(targetLabel, del.Target);
                }
            }
            info.SetType(typeof(DelegateSerializationHolder));
        }
Esempio n. 3
0
        private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            bool bNewWire = true;

            try
            {
                m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
            }
            catch
            {
                // Old wire format
                m_delegateEntry = OldDelegateWireFormat(info, context);
                bNewWire        = false;
            }

            if (bNewWire)
            {
                // retrieve the targets
                DelegateEntry deiter = m_delegateEntry;
                int           count  = 0;
                while (deiter != null)
                {
                    if (deiter.target != null)
                    {
                        string stringTarget = deiter.target as string; //need test to pass older wire format
                        if (stringTarget != null)
                        {
                            deiter.target = info.GetValue(stringTarget, typeof(Object));
                        }
                    }
                    count++;
                    deiter = deiter.delegateEntry;
                }

                // If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
                // them into an ordered array if present.
                MethodInfo[] methods = new MethodInfo[count];
                int          i;
                for (i = 0; i < count; i++)
                {
                    String methodInfoName = "method" + i;
                    methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
                    if (methods[i] == null)
                    {
                        break;
                    }
                }

                // If we got the info then make the array available for deserialization.
                if (i == count)
                {
                    m_methods = methods;
                }
            }
        }
Esempio n. 4
0
        public Object GetRealObject(StreamingContext context)
        {
            int count = 0;

            for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
            {
                count++;
            }

            int maxindex = count - 1;

            if (count == 1)
            {
                return(GetDelegate(m_delegateEntry, 0));
            }
            else
            {
                object[] invocationList = new object[count];

                for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
                {
                    // Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
                    // the order we process the entries: we're actually looking at them in reverse order.
                    --count;
                    invocationList[count] = GetDelegate(de, maxindex - count);
                }
                return(((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length));
            }
        }
Esempio n. 5
0
        // [System.Security.SecurityCritical]  // auto-generated
        internal static DelegateEntry GetDelegateSerializationInfo(
            SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
        {
            // Used for MulticastDelegate

            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            Contract.EndContractBlock();

            // VALFIX
            //if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
            //    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();

            Type c = delegateType.BaseType;

            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
            {
                throw new ArgumentException(Ssz.Runtime.Serialization.Environment.GetResourceString("Arg_MustBeDelegate"), "type");
            }

            if (method.DeclaringType == null)
            {
                throw new NotSupportedException(Ssz.Runtime.Serialization.Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
            }

            DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
                                                 method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate", de, typeof(DelegateEntry));
            }

            // target can be an object so it needs to be added to the info, or else a fixup is needed
            // when deserializing, and the fixup will occur too late. If it is added directly to the
            // info then the rules of deserialization will guarantee that it will be available when
            // needed

            if (target != null)
            {
                String targetName = "target" + targetIndex;
                info.AddValue(targetName, de.target);
                de.target = targetName;
            }

            // Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
            // first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
            // get this by serializing the target MethodInfo. We still need to send the same information as before though (the
            // DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
            // ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
            // order of deserialization guarantee otherwise.
            String methodInfoName = "method" + targetIndex;

            info.AddValue(methodInfoName, method);

            return(de);
        }
        public DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }
            Contract.EndContractBlock();

            try
            {
                _delegateEntry = (DelegateEntry)info.GetValue("DelegateEntry", typeof(DelegateEntry));
            }
            catch
            {
                // TODO: If we *really* want to support cross-runtime serialization and deserialization of delegates,
                // we'll have to implemenent the handling of the old format we have today in CoreCLR.
                // This is not a requirement today.
                _delegateEntry = null;
            }

            _delegatesCount = 0;
            DelegateEntry currentEntry = _delegateEntry;

            while (currentEntry != null)
            {
                _delegatesCount++;
                currentEntry = currentEntry.NextEntry;
            }
        }
Esempio n. 7
0
        // [System.Security.SecurityCritical]
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate d;

            try
            {
                if (de.methodName == null || de.methodName.Length == 0)
                {
                    ThrowInsufficientState("MethodName");
                }

                if (de.assembly == null || de.assembly.Length == 0)
                {
                    ThrowInsufficientState("DelegateAssembly");
                }

                if (de.targetTypeName == null || de.targetTypeName.Length == 0)
                {
                    ThrowInsufficientState("TargetTypeName");
                }

                // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
                Type type       = (Type)SszAssembly.GetType_Compat(de.assembly, de.type);
                Type targetType = (Type)SszAssembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);

                // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                if (m_methods != null)
                {
#if FEATURE_REMOTING
                    Object target = de.target != null?RemotingServices.CheckCast(de.target, targetType) : null;
#else
                    if (!targetType.IsInstanceOfType(de.target))
                    {
                        throw new InvalidCastException();
                    }
                    Object target = de.target;
#endif
                    // VALFIX
                    //d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
                    d = Delegate.CreateDelegate(type, target, m_methods[index]);
                }
                else
                {
                    if (de.target != null)
#if FEATURE_REMOTING
                    { d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName); }
#else
                    {
                        if (!targetType.IsInstanceOfType(de.target))
                        {
                            throw new InvalidCastException();
                        }
                        d = Delegate.CreateDelegate(type, de.target, de.methodName);
                    }
#endif
                    else
                    {
                        d = Delegate.CreateDelegate(type, targetType, de.methodName);
                    }
                }
        public Object GetRealObject(StreamingContext context)
        {
            if (_delegateEntry == null)
            {
                ThrowInsufficientState("DelegateEntry");
            }

            if (_delegatesCount == 1)
            {
                return(GetDelegate(_delegateEntry));
            }
            else
            {
                Delegate[] invocationList = new Delegate[_delegatesCount];

                int index = _delegatesCount - 1;
                for (DelegateEntry de = _delegateEntry; de != null; de = de.NextEntry)
                {
                    // Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
                    // the order we process the entries: we're actually looking at them in reverse order.
                    invocationList[index--] = GetDelegate(de);
                }
                return(((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length));
            }
        }
        internal static DelegateEntry GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
        {
            // Used for MulticastDelegate

            Debug.Assert(method != null);

            Type c = delegateType.BaseType;

            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
            {
                throw new ArgumentException(SR.Arg_MustBeDelegate);
            }

            if (method.DeclaringType == null)
            {
                throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization);
            }

            DelegateEntry de = new DelegateEntry(delegateType, target, method);

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("DelegateEntry", de, typeof(DelegateEntry));
            }

            return(de);
        }
        public virtual Object GetRealObject(StreamingContext context)
        {
            Delegate          root   = GetDelegate(m_delegateEntry);
            MulticastDelegate mdroot = root as MulticastDelegate;

            if (mdroot != null)
            {
                DelegateEntry     de       = m_delegateEntry.Entry;
                MulticastDelegate previous = mdroot;
                while (de != null)
                {
                    Delegate          newdelegate = GetDelegate(de);
                    MulticastDelegate current     = newdelegate as MulticastDelegate;
                    if (current != null)
                    {
                        previous.Previous = current;
                        previous          = current;
                        de = de.Entry;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(root);
        }
Esempio n. 11
0
        /// <summary>Creates a delegate type for a method</summary>
        /// <param name="method">The method</param>
        /// <param name="convention">Calling convention. If specified, adds <see cref="UnmanagedFunctionPointerAttribute"/> to the delegate type.</param>
        /// <returns>The new delegate type</returns>
        public Type CreateDelegateType(MethodInfo method, CallingConvention?convention)
        {
            DelegateEntry entry;

            if (TypeCache.TryGetValue(method, out var entries) &&
                (entry = entries.FirstOrDefault(e => e.callingConvention == convention)) != null)
            {
                return(entry.delegateType);
            }

            if (entries == null)
            {
                TypeCache[method] = entries = new List <DelegateEntry>();
            }

            entry = new DelegateEntry
            {
                delegateType = CreateDelegateType(method.ReturnType,
                                                  method.GetParameters().Types().ToArray(), convention),
                callingConvention = convention
            };

            entries.Add(entry);
            return(entry.delegateType);
        }
Esempio n. 12
0
        // Implement the IObjectReference interface.
        public Object GetRealObject(StreamingContext context)
        {
            // Get the first delegate in the chain.
            Delegate del = entry.ToDelegate();

            // Bail out early if this is a unicast delegate.
            if (!(del is MulticastDelegate) || entry.delegateEntry == null)
            {
                return(del);
            }

            // Build the multicast delegate chain.
            Delegate      end = del;
            Delegate      newDelegate;
            DelegateEntry e = entry.delegateEntry;

            while (e != null)
            {
                newDelegate = e.ToDelegate();
                if (newDelegate.GetType() != del.GetType())
                {
                    throw new SerializationException
                              (_("Arg_DelegateMismatch"));
                }
                ((MulticastDelegate)end).prev =
                    (newDelegate as MulticastDelegate);
                end = newDelegate;
                e   = e.delegateEntry;
            }
            return(del);
        }
Esempio n. 13
0
    private void AddDelegateEntry()
    {
        DelegateEntry delegateEntry = new DelegateEntry();

        exposedDelegate.delegateEntries.Add(delegateEntry);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        UpdateDelegateEntries();
    }
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate delegate2;

            try
            {
                if ((de.methodName == null) || (de.methodName.Length == 0))
                {
                    this.ThrowInsufficientState("MethodName");
                }
                if ((de.assembly == null) || (de.assembly.Length == 0))
                {
                    this.ThrowInsufficientState("DelegateAssembly");
                }
                if ((de.targetTypeName == null) || (de.targetTypeName.Length == 0))
                {
                    this.ThrowInsufficientState("TargetTypeName");
                }
                Type type  = Assembly.Load(de.assembly).GetType(de.type, true, false);
                Type type2 = Assembly.Load(de.targetTypeAssembly).GetType(de.targetTypeName, true, false);
                if (this.m_methods != null)
                {
                    object firstArgument = (de.target != null) ? RemotingServices.CheckCast(de.target, type2) : null;
                    delegate2 = Delegate.InternalCreateDelegate(type, firstArgument, this.m_methods[index]);
                }
                else if (de.target != null)
                {
                    delegate2 = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, type2), de.methodName);
                }
                else
                {
                    delegate2 = Delegate.CreateDelegate(type, type2, de.methodName);
                }
                if (((delegate2.Method == null) || delegate2.Method.IsPublic) && ((delegate2.Method.DeclaringType == null) || delegate2.Method.DeclaringType.IsVisible))
                {
                    return(delegate2);
                }
                new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
            }
            catch (Exception exception)
            {
                if (exception is SerializationException)
                {
                    throw exception;
                }
                throw new SerializationException(exception.Message, exception);
            }
            catch
            {
                throw new SerializationException();
            }
            return(delegate2);
        }
 private Delegate GetDelegate(DelegateEntry de, int index)
 {
     Delegate delegate2;
     try
     {
         if ((de.methodName == null) || (de.methodName.Length == 0))
         {
             this.ThrowInsufficientState("MethodName");
         }
         if ((de.assembly == null) || (de.assembly.Length == 0))
         {
             this.ThrowInsufficientState("DelegateAssembly");
         }
         if ((de.targetTypeName == null) || (de.targetTypeName.Length == 0))
         {
             this.ThrowInsufficientState("TargetTypeName");
         }
         Type type = Assembly.Load(de.assembly).GetType(de.type, true, false);
         Type type2 = Assembly.Load(de.targetTypeAssembly).GetType(de.targetTypeName, true, false);
         if (this.m_methods != null)
         {
             object firstArgument = (de.target != null) ? RemotingServices.CheckCast(de.target, type2) : null;
             delegate2 = Delegate.InternalCreateDelegate(type, firstArgument, this.m_methods[index]);
         }
         else if (de.target != null)
         {
             delegate2 = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, type2), de.methodName);
         }
         else
         {
             delegate2 = Delegate.CreateDelegate(type, type2, de.methodName);
         }
         if (((delegate2.Method == null) || delegate2.Method.IsPublic) && ((delegate2.Method.DeclaringType == null) || delegate2.Method.DeclaringType.IsVisible))
         {
             return delegate2;
         }
         new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
     }
     catch (Exception exception)
     {
         if (exception is SerializationException)
         {
             throw exception;
         }
         throw new SerializationException(exception.Message, exception);
     }
     catch
     {
         throw new SerializationException();
     }
     return delegate2;
 }
Esempio n. 16
0
        private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            bool flag = true;

            try
            {
                this.m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
            }
            catch
            {
                this.m_delegateEntry = this.OldDelegateWireFormat(info, context);
                flag = false;
            }
            if (flag)
            {
                DelegateEntry delegateEntry = this.m_delegateEntry;
                int           num           = 0;
                while (delegateEntry != null)
                {
                    if (delegateEntry.target != null)
                    {
                        string target = delegateEntry.target as string;
                        if (target != null)
                        {
                            delegateEntry.target = info.GetValue(target, typeof(object));
                        }
                    }
                    num++;
                    delegateEntry = delegateEntry.delegateEntry;
                }
                MethodInfo[] infoArray = new MethodInfo[num];
                int          index     = 0;
                while (index < num)
                {
                    string name = "method" + index;
                    infoArray[index] = (MethodInfo)info.GetValueNoThrow(name, typeof(MethodInfo));
                    if (infoArray[index] == null)
                    {
                        break;
                    }
                    index++;
                }
                if (index == num)
                {
                    this.m_methods = infoArray;
                }
            }
        }
        [System.Security.SecurityCritical]  // auto-generated
        internal static DelegateEntry GetDelegateSerializationInfo(
            SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
        {
            // Used for MulticastDelegate

            if (method == null) 
                throw new ArgumentNullException("method");
            Contract.EndContractBlock();
    
            if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
                new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
    
            Type c = delegateType.BaseType;

            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");

            if (method.DeclaringType == null)
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));

            DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
                method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate",de,typeof(DelegateEntry));
            }

            // target can be an object so it needs to be added to the info, or else a fixup is needed
            // when deserializing, and the fixup will occur too late. If it is added directly to the
            // info then the rules of deserialization will guarantee that it will be available when
            // needed

            if (target != null)
            {
                String targetName = "target" + targetIndex;
                info.AddValue(targetName, de.target);
                de.target = targetName;
            }

            // Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
            // first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
            // get this by serializing the target MethodInfo. We still need to send the same information as before though (the
            // DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
            // ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
            // order of deserialization guarantee otherwise.
            String methodInfoName = "method" + targetIndex;
            info.AddValue(methodInfoName, method);

            return de;
        }
 private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     bool flag = true;
     try
     {
         this.m_delegateEntry = (DelegateEntry) info.GetValue("Delegate", typeof(DelegateEntry));
     }
     catch
     {
         this.m_delegateEntry = this.OldDelegateWireFormat(info, context);
         flag = false;
     }
     if (flag)
     {
         DelegateEntry delegateEntry = this.m_delegateEntry;
         int num = 0;
         while (delegateEntry != null)
         {
             if (delegateEntry.target != null)
             {
                 string target = delegateEntry.target as string;
                 if (target != null)
                 {
                     delegateEntry.target = info.GetValue(target, typeof(object));
                 }
             }
             num++;
             delegateEntry = delegateEntry.delegateEntry;
         }
         MethodInfo[] infoArray = new MethodInfo[num];
         int index = 0;
         while (index < num)
         {
             string name = "method" + index;
             infoArray[index] = (MethodInfo) info.GetValueNoThrow(name, typeof(MethodInfo));
             if (infoArray[index] == null)
             {
                 break;
             }
             index++;
         }
         if (index == num)
         {
             this.m_methods = infoArray;
         }
     }
 }
        // Used for MulticastDelegate
        internal static DelegateEntry GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
        {
            Message.DebugOut("Inside GetDelegateSerializationInfo \n");
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            BCLDebug.Assert(!(target is Delegate), "!(target is Delegate)");
            BCLDebug.Assert(info != null, "[DelegateSerializationHolder.GetDelegateSerializationInfo]info!=null");

            Type c = delegateType.BaseType;

            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
            }


            DelegateEntry de = new DelegateEntry(
                delegateType.FullName,
                delegateType.Module.Assembly.FullName,
                target,
                method.ReflectedType.Module.Assembly.FullName,
                method.ReflectedType.FullName,
                method.Name
                );

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate", de, typeof(DelegateEntry));
            }

            // target can be an object so it needs to be added to the info, or else a fixup is needed
            // when deserializing, and the fixup will occur too late. If it is added directly to the
            // info then the rules of deserialization will guarantee that it will be available when
            // needed

            if (target != null)
            {
                String targetName = "target" + targetIndex;
                info.AddValue(targetName, de.target);
                de.target = targetName;
            }

            return(de);
        }
        // Used for MulticastDelegate
        internal static DelegateEntry GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)        
        {
            Message.DebugOut("Inside GetDelegateSerializationInfo \n");
            if (method==null) {
                throw new ArgumentNullException("method");
            }
    
            BCLDebug.Assert(!(target is Delegate),"!(target is Delegate)");
            BCLDebug.Assert(info!=null, "[DelegateSerializationHolder.GetDelegateSerializationInfo]info!=null");
    
            Type c = delegateType.BaseType;
            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
            }
    

             DelegateEntry de = new DelegateEntry(
                                                  delegateType.FullName,
                                                  delegateType.Module.Assembly.FullName,
                                                  target,
                                                  method.ReflectedType.Module.Assembly.FullName,
                                                  method.ReflectedType.FullName,
                                                  method.Name
                                                  );

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate",de,typeof(DelegateEntry));
            }

            // target can be an object so it needs to be added to the info, or else a fixup is needed
            // when deserializing, and the fixup will occur too late. If it is added directly to the
            // info then the rules of deserialization will guarantee that it will be available when
            // needed

            if (target != null)
            {
                String targetName = "target"+targetIndex;
                info.AddValue(targetName, de.target);
                de.target = targetName;
            }

            return de;
        }
Esempio n. 21
0
        // Constructor.
        public DelegateSerializationHolder(SerializationInfo info,
                                           StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            bool needsResolve = false;

            try
            {
                // Try the new serialization format first.
                entry = (DelegateEntry)(info.GetValue
                                            ("Delegate", typeof(DelegateEntry)));
                needsResolve = true;
            }
            catch (Exception)
            {
                // Try the old-style serialization format (deprecated).
                entry                    = new DelegateEntry();
                entry.type               = info.GetString("DelegateType");
                entry.assembly           = info.GetString("DelegateAssembly");
                entry.target             = info.GetValue("Target", typeof(Object));
                entry.targetTypeAssembly =
                    info.GetString("TargetTypeAssembly");
                entry.targetTypeName = info.GetString("TargetTypeName");
                entry.methodName     = info.GetString("MethodName");
            }

            // Resolve targets specified as field names.
            if (needsResolve)
            {
                DelegateEntry e = entry;
                while (e != null)
                {
                    if (e.target is String)
                    {
                        e.target = info.GetValue
                                       ((String)(e.target), typeof(Object));
                    }
                    e = e.delegateEntry;
                }
            }
        }
        private Delegate GetDelegate(DelegateEntry de)
        {
            try
            {
                if (de.DelegateType == null)
                {
                    ThrowInsufficientState("DelegateType");
                }

                if (de.TargetMethod == null)
                {
                    ThrowInsufficientState("TargetMethod");
                }

                return(Delegate.CreateDelegate(de.DelegateType, de.TargetObject, de.TargetMethod));
            }
            catch (Exception e) when(!(e is SerializationException))
            {
                throw new SerializationException(e.Message, e);
            }
        }
Esempio n. 23
0
        // Serialize a multicast delegate object.
        internal static void SerializeMulticast
            (SerializationInfo info, MulticastDelegate del)
        {
            DelegateEntry entry, next;
            int           index = 0;

            // Serialize the first entry on the multicast list.
            entry = Serialize(info, index++, del.GetType(), del.target,
                              MethodBase.GetMethodFromHandle(del.method));

            // Serialize the rest of the multicast chain.
            del = del.prev;
            while (del != null)
            {
                next = Serialize
                           (info, index++, del.GetType(), del.target,
                           MethodBase.GetMethodFromHandle(del.method));
                entry.delegateEntry = next;
                entry = next;
                del   = del.prev;
            }
        }
Esempio n. 24
0
        public object GetRealObject(StreamingContext context)
        {
            int index = 0;

            for (DelegateEntry entry = this.m_delegateEntry; entry != null; entry = entry.Entry)
            {
                index++;
            }
            int num2 = index - 1;

            if (index == 1)
            {
                return(this.GetDelegate(this.m_delegateEntry, 0));
            }
            object[] invocationList = new object[index];
            for (DelegateEntry entry2 = this.m_delegateEntry; entry2 != null; entry2 = entry2.Entry)
            {
                index--;
                invocationList[index] = this.GetDelegate(entry2, num2 - index);
            }
            return(((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length));
        }
        internal DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            bool bNewWire = true;

            try
            {
                m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
            }
            catch (Exception)
            {
                // Old wire format
                m_delegateEntry = OldDelegateWireFormat(info, context);
                bNewWire        = false;
            }

            if (bNewWire)
            {
                // retrieve the targets
                DelegateEntry deiter = m_delegateEntry;
                while (deiter != null)
                {
                    if (deiter.target != null)
                    {
                        string stringTarget = deiter.target as string; //need test to pass older wire format
                        if (stringTarget != null)
                        {
                            deiter.target = info.GetValue(stringTarget, typeof(Object));
                        }
                    }
                    deiter = deiter.delegateEntry;
                }
            }
        }
Esempio n. 26
0
        internal static DelegateEntry GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, object target, MethodInfo method, int targetIndex)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            if (!method.IsPublic || ((method.DeclaringType != null) && !method.DeclaringType.IsVisible))
            {
                new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
            }
            Type baseType = delegateType.BaseType;

            if ((baseType == null) || ((baseType != typeof(Delegate)) && (baseType != typeof(MulticastDelegate))))
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
            }
            if (method.DeclaringType == null)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
            }
            DelegateEntry entry = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target, method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate", entry, typeof(DelegateEntry));
            }
            if (target != null)
            {
                string str = "target" + targetIndex;
                info.AddValue(str, entry.target);
                entry.target = str;
            }
            string name = "method" + targetIndex;

            info.AddValue(name, method);
            return(entry);
        }
Esempio n. 27
0
        // Serialize a delegate object.
        internal static DelegateEntry Serialize
            (SerializationInfo info, int listPosition,
            Type delegateType, Object target, MethodBase method)
        {
            // Create the new delegate entry block.
            DelegateEntry entry = new DelegateEntry();

            entry.type               = delegateType.FullName;
            entry.assembly           = delegateType.Assembly.FullName;
            entry.target             = target;
            entry.targetTypeAssembly =
                method.ReflectedType.Assembly.FullName;
            entry.targetTypeName = method.ReflectedType.FullName;
            entry.methodName     = method.Name;

            // Add the block if this is the first in the list.
            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate", entry, typeof(DelegateEntry));
            }

            // Add the target object to the top level of the info block.
            // Needed to get around order of fixup problems in some
            // third party serialization implementations.
            if (target != null)
            {
                String name = "target" + listPosition.ToString();
                info.AddValue(name, target, typeof(Object));
                entry.target = name;
            }

            // Return the entry to the caller so that we can chain
            // multiple entries together for multicast delegates.
            return(entry);
        }
Esempio n. 28
0
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate d;

            try
            {
                if (de.methodName == null || de.methodName.Length == 0)
                {
                    ThrowInsufficientState("MethodName");
                }

                if (de.assembly == null || de.assembly.Length == 0)
                {
                    ThrowInsufficientState("DelegateAssembly");
                }

                if (de.targetTypeName == null || de.targetTypeName.Length == 0)
                {
                    ThrowInsufficientState("TargetTypeName");
                }

                Type type       = Assembly.Load(de.assembly).GetType(de.type, true, false);
                Type targetType = Assembly.Load(de.targetTypeAssembly).GetType(de.targetTypeName, true, false);

                // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                if (m_methods != null)
                {
                    Object target = de.target != null?RemotingServices.CheckCast(de.target, targetType) : null;

                    d = Delegate.InternalCreateDelegate(type, target, m_methods[index]);
                }
                else
                {
                    if (de.target != null)
                    {
                        d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
                    }
                    else
                    {
                        d = Delegate.CreateDelegate(type, targetType, de.methodName);
                    }
                }

                if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
                {
                    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
                }
            }
            catch (Exception e)
            {
                if (e is SerializationException)
                {
                    throw e;
                }

                throw new SerializationException(e.Message, e);
            }
            catch
            {
                throw new SerializationException();
            }

            return(d);
        }
Esempio n. 29
0
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate d;

            try
            {
                if (de.methodName == null || de.methodName.Length == 0)
                {
                    ThrowInsufficientState("MethodName");
                }

                if (de.assembly == null || de.assembly.Length == 0)
                {
                    ThrowInsufficientState("DelegateAssembly");
                }

                if (de.targetTypeName == null || de.targetTypeName.Length == 0)
                {
                    ThrowInsufficientState("TargetTypeName");
                }

                // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
                RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);

                // {de.targetTypeAssembly, de.targetTypeName} do not actually refer to the type of the target, but the reflected
                // type of the method. Those types may be the same when the method is on the target's type or on a type in its
                // inheritance chain, but those types may not be the same when the method is an extension method for the
                // target's type or a type in its inheritance chain.

                // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                if (m_methods != null)
                {
                    // The method info is serialized, so the target type info is redundant. The desktop framework does no
                    // additional verification on the target type info.
                    d = Delegate.CreateDelegateNoSecurityCheck(type, de.target, m_methods[index]);
                }
                else
                {
                    if (de.target != null)
                    {
                        // For consistency with the desktop framework, when the method info is not serialized for a closed
                        // delegate, the method is assumed to be on the target's type or in its inheritance chain. An extension
                        // method would not work on this path for the above reason and also because the delegate binds to
                        // instance methods only. The desktop framework does no additional verification on the target type info.
                        d = Delegate.CreateDelegate(type, de.target, de.methodName);
                    }
                    else
                    {
                        RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
                        d = Delegate.CreateDelegate(type, targetType, de.methodName);
                    }
                }
            }
            catch (Exception e)
            {
                if (e is SerializationException)
                {
                    throw e;
                }

                throw new SerializationException(e.Message, e);
            }

            return(d);
        }
 internal static DelegateEntry GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, object target, MethodInfo method, int targetIndex)
 {
     if (method == null)
     {
         throw new ArgumentNullException("method");
     }
     if (!method.IsPublic || ((method.DeclaringType != null) && !method.DeclaringType.IsVisible))
     {
         new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
     }
     Type baseType = delegateType.BaseType;
     if ((baseType == null) || ((baseType != typeof(Delegate)) && (baseType != typeof(MulticastDelegate))))
     {
         throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
     }
     if (method.DeclaringType == null)
     {
         throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
     }
     DelegateEntry entry = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target, method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
     if (info.MemberCount == 0)
     {
         info.SetType(typeof(DelegateSerializationHolder));
         info.AddValue("Delegate", entry, typeof(DelegateEntry));
     }
     if (target != null)
     {
         string str = "target" + targetIndex;
         info.AddValue(str, entry.target);
         entry.target = str;
     }
     string name = "method" + targetIndex;
     info.AddValue(name, method);
     return entry;
 }
Esempio n. 31
0
    public DelegateEntryEditor(ExposedDelegateEditor exposedDelegateEditor, DelegateEntry delegateEntry)
    {
        this.exposedDelegateEditor = exposedDelegateEditor;
        this.delegateEntry         = delegateEntry;

        VisualTreeAsset visualTree = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>("Assets/UtilityAI/Scripts/Editor/Delegate Entry Editor/DelegateEntryEditor.uxml");

        visualTree.CloneTree(this);

        StyleSheet stylesheet = AssetDatabase.LoadAssetAtPath <StyleSheet>("Assets/UtilityAI/Scripts/Editor/Delegate Entry Editor/DelegateEntryEditor.uss");

        this.styleSheets.Add(stylesheet);

        this.AddToClassList("delegateEntryEditor");
        if (exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor.GetType() == typeof(UtilityAIAgentEditor))
        {
            UtilityAIAgentEditor editorWindow = (UtilityAIAgentEditor)exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor;
            if (delegateEntry.TargetGO != editorWindow.utilityAIAgent.gameObject)
            {
                delegateEntry.TargetGO = editorWindow.utilityAIAgent.gameObject;
            }
        }

        delegateEntryFoldout = this.Query <Foldout>("delegateEntry");

        delegateEntryFoldout.Query <Toggle>().First().AddToClassList("delegateEntryFoldout");

        Button moveUpButton = this.Query <Button>("moveUpButton").First();

        moveUpButton.BringToFront();
        moveUpButton.clickable.clicked += MoveEntryUp;

        Button moveDownButton = this.Query <Button>("moveDownButton").First();

        moveDownButton.BringToFront();
        moveDownButton.clickable.clicked += MoveEntryDown;

        Button deleteButton = this.Query <Button>("deleteButton").First();

        deleteButton.BringToFront();
        deleteButton.clickable.clicked += DeleteEntry;
        List <Component> components = new List <Component>();

        if (exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor is UtilityAIAgentEditor)
        {
            components = delegateEntry.TargetGO.GetComponents <Component>().ToList();
        }
        else if (exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor is UtilityAIActionSetEditor)
        {
            if (((UtilityAIActionSetEditor)exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor).utilityAIAgent.inheritingGameObject != null)
            {
                components = ((UtilityAIActionSetEditor)exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor).utilityAIAgent.inheritingGameObject.GetComponents <Component>().ToList();
            }
        }
        if (components.Count > 0)
        {
            int index = 0;
            if (delegateEntry.Target != null)
            {
                List <Component> sharedComponents = components.Where(o => o.GetType() == delegateEntry.Target.GetType()).ToList();
                if (sharedComponents.Count > 0)
                {
                    index = components.IndexOf(sharedComponents[0]);
                }
                else
                {
                    if (exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor is UtilityAIAgentEditor && ((UtilityAIAgentEditor)exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor).utilityAIAgent.actionSet != null)
                    {
                        ((UtilityAIAgentEditor)exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor).utilityAIAgent.MakeActionsSetUnique();
                        ((UtilityAIAgentEditor)exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor).CreateInspectorGUI();
                        return;
                    }
                }
            }
            PopupField <Component> targetComponentField = new PopupField <Component>("Component: ", components, index);

            delegateEntry.Target = targetComponentField.value;
            targetComponentField.RegisterCallback <ChangeEvent <Component> >(
                e =>
            {
                delegateEntry.Target = (Component)e.newValue;
                exposedDelegateEditor.UpdateDelegateEntries();
            }
                );
            delegateEntryFoldout.Add(targetComponentField);
            if (delegateEntry.Target != null)
            {
                Type         selectedComponentType = delegateEntry.Target.GetType();
                BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
                //Get a list of methods attached to the component, and create a dropdown menu:
                List <MethodInfo>       methods           = selectedComponentType.GetMethods(flags).ToList();
                PopupField <MethodInfo> targetMethodField = new PopupField <MethodInfo>("Method: ", methods, methods.Contains(delegateEntry.Method) ? methods.IndexOf(delegateEntry.Method) : 0);
                if (delegateEntry.Method == null || delegateEntry.Method.Name != targetMethodField.value.Name)
                {
                    delegateEntry.SetMethod(selectedComponentType, targetMethodField.value.Name);
                }
                targetMethodField.RegisterCallback <ChangeEvent <MethodInfo> >(
                    e =>
                {
                    delegateEntry.SetMethod(selectedComponentType, e.newValue.Name);
                    exposedDelegateEditor.UpdateDelegateEntries();
                }
                    );
                delegateEntryFoldout.Add(targetMethodField);
                if (delegateEntry.Method != null && delegateEntry.Parameters.Length > 0)
                {
                    Foldout parametersFoldout = new Foldout();
                    parametersFoldout.text = "Parameters: ";

                    foreach (SerializableObject parameter in delegateEntry.Parameters)
                    {
                        if (parameter.obj is int)
                        {
                            IntegerField parameterField = new IntegerField();
                            parameterField.value = (int)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <int> >(
                                e =>
                            {
                                parameter.obj = (int)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is float)
                        {
                            FloatField parameterField = new FloatField();
                            parameterField.value = (float)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <float> >(
                                e =>
                            {
                                parameter.obj = (float)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is bool)
                        {
                            Toggle parameterField = new Toggle();
                            parameterField.value = (bool)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <bool> >(
                                e =>
                            {
                                parameter.obj = (bool)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is string)
                        {
                            TextField parameterField = new TextField();
                            parameterField.value = (string)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <string> >(
                                e =>
                            {
                                parameter.obj = (string)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is Vector3)
                        {
                            Vector3Field parameterField = new Vector3Field();
                            parameterField.value = (Vector3)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <Vector3> >(
                                e =>
                            {
                                parameter.obj = (Vector3)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is Vector2)
                        {
                            Vector2Field parameterField = new Vector2Field();
                            parameterField.value = (Vector2)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <Vector2> >(
                                e =>
                            {
                                parameter.obj = (Vector2)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is Bounds)
                        {
                            BoundsField parameterField = new BoundsField();
                            parameterField.value = (Bounds)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <Bounds> >(
                                e =>
                            {
                                parameter.obj = (Bounds)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is Rect)
                        {
                            RectField parameterField = new RectField();
                            parameterField.value = (Rect)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <Rect> >(
                                e =>
                            {
                                parameter.obj = (Rect)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is Color)
                        {
                            ColorField parameterField = new ColorField();
                            parameterField.value = (Color)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <Color> >(
                                e =>
                            {
                                parameter.obj = (Color)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                        else if (parameter.obj is UnityEngine.Object)
                        {
                            ObjectField parameterField = new ObjectField();
                            parameterField.value = (UnityEngine.Object)parameter.obj;
                            parameterField.RegisterCallback <ChangeEvent <UnityEngine.Object> >(
                                e =>
                            {
                                parameter.obj = (UnityEngine.Object)e.newValue;
                            }
                                );
                            parametersFoldout.Add(parameterField);
                        }
                    }

                    delegateEntryFoldout.Add(parametersFoldout);
                }
            }
        }

        if (delegateEntry.TargetGO != null)
        {
            delegateEntryFoldout.text += delegateEntry.TargetGO.name;
            if (delegateEntry.Target != null)
            {
                delegateEntryFoldout.text += "(" + delegateEntry.Target.GetType() + ") ";
                if (delegateEntry.Method != null)
                {
                    delegateEntryFoldout.text += delegateEntry.Method.Name;
                }
            }
            delegateEntryFoldout.text += ": ";
        }
        else
        {
            delegateEntryFoldout.text = "New Delegate Entry:";
        }
        if (exposedDelegateEditor.utilityAIActionEditor.utilityAIAgentEditor is UtilityAIActionSetEditor && components.Count <= 0)
        {
            delegateEntryFoldout.text = "No inheriting object selected!";
        }
    }
Esempio n. 32
0
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate d;

            try
            {
                if (de.methodName == null || de.methodName.Length == 0)
                {
                    ThrowInsufficientState("MethodName");
                }

                if (de.assembly == null || de.assembly.Length == 0)
                {
                    ThrowInsufficientState("DelegateAssembly");
                }

                if (de.targetTypeName == null || de.targetTypeName.Length == 0)
                {
                    ThrowInsufficientState("TargetTypeName");
                }

                // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
                RuntimeType type       = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
                RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);

                // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                if (m_methods != null)
                {
                    if (de.target != null && !targetType.IsInstanceOfType(de.target))
                    {
                        throw new InvalidCastException();
                    }
                    Object target = de.target;
                    d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
                }
                else
                {
                    if (de.target != null)
                    {
                        if (!targetType.IsInstanceOfType(de.target))
                        {
                            throw new InvalidCastException();
                        }
                        d = Delegate.CreateDelegate(type, de.target, de.methodName);
                    }
                    else
                    {
                        d = Delegate.CreateDelegate(type, targetType, de.methodName);
                    }
                }

                if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
                {
                    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
                }
            }
            catch (Exception e)
            {
                if (e is SerializationException)
                {
                    throw e;
                }

                throw new SerializationException(e.Message, e);
            }

            return(d);
        }
        private Delegate GetDelegate(DelegateEntry de)
        {
            Delegate d;

            if (de.methodName == null || de.methodName.Length == 0)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            Assembly assem = FormatterServices.LoadAssemblyFromString(de.assembly);

            if (assem == null)
            {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.assembly);
                throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.assembly));
            }

            Type type = assem.GetTypeInternal(de.type, false, false, false);

            assem = FormatterServices.LoadAssemblyFromString(de.targetTypeAssembly);
            if (assem == null)
            {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.targetTypeAssembly);
                throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.targetTypeAssembly));
            }

            Type targetType = assem.GetTypeInternal(de.targetTypeName, false, false, false);

            if (de.target == null && targetType == null)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            if (type == null)
            {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.GetRealObject]Missing Type");
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            if (targetType == null)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            Object target = null;

            if (de.target != null) //We have a delegate to a non-static object
            {
                target = RemotingServices.CheckCast(de.target, targetType);
                d      = Delegate.CreateDelegate(type, target, de.methodName);
            }
            else
            {
                //For a static delegate
                d = Delegate.CreateDelegate(type, targetType, de.methodName);
            }

            // We will refuse to create delegates to methods that are non-public.
            MethodInfo mi = d.Method;

            if (mi != null)
            {
                if (!mi.IsPublic)
                {
                    throw new SerializationException(
                              Environment.GetResourceString("Serialization_RefuseNonPublicDelegateCreation"));
                }
            }

            return(d);
        }
Esempio n. 34
0
		public static void GetDelegateData (Delegate instance, SerializationInfo info, StreamingContext ctx)
		{
			// Fills a SerializationInfo object with the information of the delegate.

			Delegate[] delegates = instance.GetInvocationList ();
			DelegateEntry lastEntry = null;
			for (int n=0; n<delegates.Length; n++) {
				Delegate del = delegates[n];
				string targetLabel = (del.Target != null) ? ("target" + n) : null;
				DelegateEntry entry = new DelegateEntry (del, targetLabel);

				if (lastEntry == null)
					info.AddValue ("Delegate", entry);
				else
					lastEntry.delegateEntry = entry;

				lastEntry = entry;
				if (del.Target != null)
					info.AddValue (targetLabel, del.Target);
			}
			info.SetType (typeof (DelegateSerializationHolder));
		}
Esempio n. 35
0
 public DelegateEntry(DelegateEntry delegateEntry)
 {
     this.Target     = delegateEntry.Target;
     this.Method     = delegateEntry.Method;
     this.Parameters = delegateEntry.Parameters;
 }
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate d;

            try
            {
                if (de.methodName == null || de.methodName.Length == 0)
                    ThrowInsufficientState("MethodName");

                if (de.assembly == null || de.assembly.Length == 0)
                    ThrowInsufficientState("DelegateAssembly");

                if (de.targetTypeName == null || de.targetTypeName.Length == 0)
                    ThrowInsufficientState("TargetTypeName");

                Type type = Assembly.Load(de.assembly).GetType(de.type, true, false);
                Type targetType = Assembly.Load(de.targetTypeAssembly).GetType(de.targetTypeName, true, false);

                // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                if (m_methods != null)
                {
                    Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
                    d = Delegate.InternalCreateDelegate(type, target, m_methods[index]);
                }
                else
                {
                    if (de.target != null)
                        d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
                    else
                        d = Delegate.CreateDelegate(type, targetType, de.methodName);
                }

                if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
                    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
            }
            catch (Exception e)
            {
                if (e is SerializationException)
                    throw e;

                throw new SerializationException(e.Message, e);
            }
            catch
            {
                throw new SerializationException();
            }

            return d;
        }
        [System.Security.SecurityCritical]  // auto-generated
        private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            Contract.EndContractBlock();
    
            bool bNewWire = true;

            try
            {
                m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
            }
            catch
            {
                // Old wire format
                m_delegateEntry = OldDelegateWireFormat(info, context);
                bNewWire = false;
            }

            if (bNewWire)
            {
                // retrieve the targets
                DelegateEntry deiter = m_delegateEntry;
                int count = 0;
                while (deiter != null)
                {
                    if (deiter.target != null)
                    {
                        string stringTarget = deiter.target as string; //need test to pass older wire format
                        if (stringTarget != null)
                            deiter.target = info.GetValue(stringTarget, typeof(Object));
                    }
                    count++;
                    deiter = deiter.delegateEntry;
                }

                // If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
                // them into an ordered array if present.
                MethodInfo[] methods = new MethodInfo[count];
                int i;
                for (i = 0; i < count; i++)
                {
                    String methodInfoName = "method" + i;
                    methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
                    if (methods[i] == null)
                        break;
                }

                // If we got the info then make the array available for deserialization.
                if (i == count)
                    m_methods = methods;
            }
        }
        private Delegate GetDelegate(DelegateEntry de, int index)
        {
            Delegate d;

            try
            {
                if (de.methodName == null || de.methodName.Length == 0)
                    ThrowInsufficientState("MethodName");

                if (de.assembly == null || de.assembly.Length == 0)
                    ThrowInsufficientState("DelegateAssembly");

                if (de.targetTypeName == null || de.targetTypeName.Length == 0)
                    ThrowInsufficientState("TargetTypeName");

                // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
                RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
                RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);

                // If we received the new style delegate encoding we already have the target MethodInfo in hand.
                if (m_methods != null)
                {
#if FEATURE_REMOTING                
                    Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
#else
                    if(!targetType.IsInstanceOfType(de.target))
                        throw new InvalidCastException();
                    Object target=de.target;
#endif
                    d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
                }
                else
                {
                    if (de.target != null)
#if FEATURE_REMOTING                
                        d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
#else
                {
                    if(!targetType.IsInstanceOfType(de.target))
                        throw new InvalidCastException();
                     d = Delegate.CreateDelegate(type, de.target, de.methodName);
                }
#endif
                    else
                        d = Delegate.CreateDelegate(type, targetType, de.methodName);
                }

                if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
                    new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
            }
            catch (Exception e)
            {
                if (e is SerializationException)
                    throw e;

                throw new SerializationException(e.Message, e);
            }

            return d;
        }
	// Serialize a delegate object.
	internal static DelegateEntry Serialize
				(SerializationInfo info, int listPosition,
				 Type delegateType, Object target, MethodBase method)
			{
				// Create the new delegate entry block.
				DelegateEntry entry = new DelegateEntry();
				entry.type = delegateType.FullName;
				entry.assembly = delegateType.Assembly.FullName;
				entry.target = target;
				entry.targetTypeAssembly =
						method.ReflectedType.Assembly.FullName;
				entry.targetTypeName = method.ReflectedType.FullName;
				entry.methodName = method.Name;

				// Add the block if this is the first in the list.
				if(info.MemberCount == 0)
				{
					info.SetType(typeof(DelegateSerializationHolder));
					info.AddValue("Delegate", entry, typeof(DelegateEntry));
				}

				// Add the target object to the top level of the info block.
				// Needed to get around order of fixup problems in some
				// third party serialization implementations.
				if(target != null)
				{
					String name = "target" + listPosition.ToString();
					info.AddValue(name, target, typeof(Object));
					entry.target = name;
				}

				// Return the entry to the caller so that we can chain
				// multiple entries together for multicast delegates.
				return entry;
			}
	// Constructor.
	public DelegateSerializationHolder(SerializationInfo info,
									   StreamingContext context)
			{
				if(info == null)
				{
					throw new ArgumentNullException("info");
				}
				bool needsResolve = false;
				try
				{
					// Try the new serialization format first.
					entry = (DelegateEntry)(info.GetValue
						("Delegate", typeof(DelegateEntry)));
					needsResolve = true;
				}
				catch(Exception)
				{
					// Try the old-style serialization format (deprecated).
					entry = new DelegateEntry();
					entry.type = info.GetString("DelegateType");
					entry.assembly = info.GetString("DelegateAssembly");
					entry.target = info.GetValue("Target", typeof(Object));
					entry.targetTypeAssembly =
						info.GetString("TargetTypeAssembly");
					entry.targetTypeName = info.GetString("TargetTypeName");
					entry.methodName = info.GetString("MethodName");
				}

				// Resolve targets specified as field names.
				if(needsResolve)
				{
					DelegateEntry e = entry;
					while(e != null)
					{
						if(e.target is String)
						{
							e.target = info.GetValue
								((String)(e.target), typeof(Object));
						}
						e = e.delegateEntry;
					}
				}
			}
        internal DelegateSerializationHolder(SerializationInfo info, StreamingContext context) {
            if (info==null) {
                throw new ArgumentNullException("info");
            }
    
            bool bNewWire = true;
            try
            {
                m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
            }
            catch(Exception)
            {
                // Old wire format
                m_delegateEntry = OldDelegateWireFormat(info, context);
                bNewWire = false;
            }

            if (bNewWire)
            {
                // retrieve the targets
                DelegateEntry deiter = m_delegateEntry;
                while (deiter != null)
                {
                    if (deiter.target != null)
                    {
                        string stringTarget = deiter.target as string; //need test to pass older wire format
                        if (stringTarget != null)
                            deiter.target = info.GetValue(stringTarget, typeof(Object));
                    }
                    deiter= deiter.delegateEntry;
                }
            }

        }
	// Serialize a multicast delegate object.
	internal static void SerializeMulticast
				(SerializationInfo info, MulticastDelegate del)
			{
				DelegateEntry entry, next;
				int index = 0;

				// Serialize the first entry on the multicast list.
				entry = Serialize(info, index++, del.GetType(), del.target,
								  MethodBase.GetMethodFromHandle(del.method));

				// Serialize the rest of the multicast chain.
				del = del.prev;
				while(del != null)
				{
					next = Serialize
						(info, index++, del.GetType(), del.target,
						 MethodBase.GetMethodFromHandle(del.method));
					entry.delegateEntry = next;
					entry = next;
					del = del.prev;
				}
			}
        private Delegate GetDelegate(DelegateEntry de)
        {
            Delegate d;
    
            if (de.methodName==null || de.methodName.Length==0) {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }
    
            Assembly assem = FormatterServices.LoadAssemblyFromString(de.assembly);

            if (assem==null) {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.assembly);
                throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.assembly));
            }

            Type type = assem.GetTypeInternal(de.type, false, false, false);

            assem = FormatterServices.LoadAssemblyFromString(de.targetTypeAssembly);
            if (assem==null) {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.targetTypeAssembly);
                throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.targetTypeAssembly));
        }
    
            Type targetType = assem.GetTypeInternal(de.targetTypeName, false, false, false);

            if (de.target==null && targetType==null) {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }
    
            if (type==null) {
                BCLDebug.Trace("SER","[DelegateSerializationHolder.GetRealObject]Missing Type");
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }
    
            if (targetType==null) {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            Object target = null;

            if (de.target!=null) { //We have a delegate to a non-static object
                target = RemotingServices.CheckCast(de.target, targetType);
                d=Delegate.CreateDelegate(type, target, de.methodName);
            } else {
                //For a static delegate
                d=Delegate.CreateDelegate(type, targetType, de.methodName);
            }
    
            // We will refuse to create delegates to methods that are non-public.
            MethodInfo mi = d.Method;
            if (mi != null)
            {
                if (!mi.IsPublic)
                {
                    throw new SerializationException(
                        Environment.GetResourceString("Serialization_RefuseNonPublicDelegateCreation"));
                }
            }
    
            return d;
        }