コード例 #1
0
        public static SerializationInfo GetSerializationInfo(this ISerializable value)
        {
            SerializationInfo?serializationInfo = new SerializationInfo(value.GetType(), new FormatterConverter());
            StreamingContext  streamingContext  = new StreamingContext();

#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
            MethodInfo mi = value.GetType().GetMethod("GetObjectData", new Type[] { typeof(SerializationInfo), typeof(StreamingContext) });
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
            mi.Invoke(value, new object[] { serializationInfo, streamingContext });
#pragma warning restore CS8602 // Dereference of a possibly null reference.
            return(serializationInfo);
        }
コード例 #2
0
        public void WriteValueChild(XmlElement childElement, ISerializable serializable)
        {
            Type   type     = serializable.GetType();
            int    token    = Types.GetToken(type);
            string typeName = token.ToString();

            if (string.IsNullOrEmpty(typeName))
            {
                throw new InvalidValueException($"Type '{serializable.GetType()}' is not registered in TypesDictionary", 178884);
            }
            //throw XmlDocumentSerializationException.NotRegistered(serializable);
            childElement.SetAttribute(_TypeAttributeId, typeName);
            serializable.WriteToXml(childElement, this);
        }
コード例 #3
0
        public int SendToAll(ISerializable message, DeliveryOptions deliveryOptions, Guid exception)
        {
            var stream = _shamanStreamPool.Rent(message.GetType());

            try
            {
                _serializer.Serialize(message, stream);
                _roomSender.SendToAll(new Payload(stream.GetBuffer()), deliveryOptions, exception);
                return((int)stream.Length);
            }
            finally
            {
                _shamanStreamPool.Return(stream, message.GetType());
            }
        }
コード例 #4
0
        public int Send(ISerializable message, DeliveryOptions deliveryOptions, IPeerSender peer)
        {
            var stream = _shamanStreamPool.Rent(message.GetType());

            try
            {
                _serializer.Serialize(message, stream);
                _packetSender.AddPacket(peer, deliveryOptions, new Payload(stream.GetBuffer()));
                return((int)stream.Length);
            }
            finally
            {
                _shamanStreamPool.Return(stream, message.GetType());
            }
        }
コード例 #5
0
    private void send(MultiplayerServerBroadcastType type, ISerializable data)
    {
        string json      = JsonUtility.ToJson(data);
        string className = data.GetType().ToString();

        webSocket.SendString(type.ToString() + ":" + className + ":" + json);
    }
コード例 #6
0
        /// <summary>
        /// Handled serializable (run ISerializable method with actual parameters).
        /// </summary>
        /// <param name="serializable"></param>
        private void HandleSerializable(ISerializable serializable)
        {
            FormatterConverter formatterConverter = new FormatterConverter();
            SerializationInfo  serializationInfo  = new SerializationInfo(serializable.GetType(), formatterConverter);
            StreamingContext   streamingContext   = new StreamingContext(StreamingContextStates.All);

            serializable.GetObjectData(serializationInfo, streamingContext);

            // TODO: Check and test ISerializable support.
            // Serialize additional data
            if (serializationInfo.MemberCount > 0)
            {
                foreach (SerializationEntry entry in serializationInfo)
                {
                    this.WriteString(entry.Name);
                    this.WriteType(entry.ObjectType, false);

                    if (entry.ObjectType.IsPrimitive)
                    {
                        this.TryWritePrimitiveType <int>(entry.Value, entry.ObjectType, this.WriteInt);
                        this.TryWritePrimitiveType <byte>(entry.Value, entry.ObjectType, this.WriteByte);
                        this.TryWritePrimitiveType <long>(entry.Value, entry.ObjectType, this.WriteLong);
                        this.TryWritePrimitiveType <float>(entry.Value, entry.ObjectType, this.WriteFloat);
                        this.TryWritePrimitiveType <double>(entry.Value, entry.ObjectType, this.WriteDouble);
                        this.TryWritePrimitiveType <short>(entry.Value, entry.ObjectType, this.WriteShort);
                        this.TryWritePrimitiveType <char>(entry.Value, entry.ObjectType, this.WriteChar);
                        this.TryWritePrimitiveType <bool>(entry.Value, entry.ObjectType, this.WriteBoolean);
                    }
                    else
                    {
                        this.WriteObject(entry.Value);
                    }
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// deconstructs objects that inhert ISerializable
        /// </summary>
        /// <returns></returns>
        private static BinaryBuilder SeriObjDeconstructor(ISerializable obj)
        {
            SerializationInfo info    = new SerializationInfo(obj.GetType(), new FormatterConverter());
            StreamingContext  context = new StreamingContext(StreamingContextStates.All);

            obj.GetObjectData(info, context);
            var           node        = info.GetEnumerator();
            BinaryBuilder byteBuilder = new BinaryBuilder();

            byteBuilder.Append(serializerEntry);

            ///Object Type Change
            byteBuilder.Append(info.ObjectType.AssemblyQualifiedName);
            byteBuilder.Append(equals);
            ///Object Type Change

            while (node.MoveNext())
            {
                //bytebuilder adds to itself the new byte arrays, no need to assign
                byteBuilder.Append(startClass + node.Name + typeEntry + node.ObjectType.ToString() + equals + Deconstruction(node.Value) + endClass);
                //stringBuilder.Append(startClass + node.Name + typeEntry + node.ObjectType + equals + Deconstruct(node.Value) + endClass);
            }
            byteBuilder.Append(serializerExit);
            return(byteBuilder);
        }
コード例 #8
0
 public SurrogateForISerializable(ISerializable serializable)
 {
     var serializationInfo = new SerializationInfo(serializable.GetType(), new FormatterConverter());
     var streamingContext = new StreamingContext(StreamingContextStates.Clone);
     serializable.GetObjectData(serializationInfo, streamingContext);
     keys = new string[serializationInfo.MemberCount];
     values = new object[serializationInfo.MemberCount];
     var i = 0;
     foreach(var entry in serializationInfo)
     {
         keys[i] = entry.Name;
         values[i] = entry.Value;
         i++;
     }
     assemblyQualifiedName = serializable.GetType().AssemblyQualifiedName;
 }
コード例 #9
0
        private void smethod_3930(Class_296 arg_0, ISerializable arg_1, Class_367 arg_2, Class_454 arg_3, Class_350 arg_4, Class_454 arg_5)
        {
            if (!Class_470.FullyTrusted)
            {
                string text = "Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
                text = text.FormatWith(CultureInfo.InvariantCulture, arg_1.GetType());
                throw Class_417.gmethod_3103(null, arg_0.prop_3, text, null);
            }
            this.vmethod_3915(arg_0, arg_2, arg_1);
            this.field_2.Add(arg_1);
            this.pmethod_3919(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5);
            SerializationInfo serializationInfo = new SerializationInfo(arg_2.prop_0, new FormatterConverter());

            arg_1.GetObjectData(serializationInfo, this.field_3.field_14);
            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                Class_349 class_ = this.cmethod_3904(serializationEntry.Value);
                if (this.lmethod_3908(serializationEntry.Value, null, class_, arg_2, arg_3))
                {
                    arg_0.gmethod_2013(serializationEntry.Name);
                    this.xmethod_3911(arg_0, serializationEntry.Value);
                }
                else if (this.smethod_3910(arg_0, serializationEntry.Value, null, class_, arg_2, arg_3))
                {
                    arg_0.gmethod_2013(serializationEntry.Name);
                    this.dmethod_3906(arg_0, serializationEntry.Value, class_, null, arg_2, arg_3);
                }
            }
            arg_0.lmethod_2008();
            this.field_2.RemoveAt(this.field_2.Count - 1);
            this.dmethod_3916(arg_0, arg_2, arg_1);
        }
コード例 #10
0
        public void WriteToStream(Stream stream, ISerializable obj)
        {
            var aw = new AwesomeWriter(stream, Info.BigEndian);

            var serializer = Serializers.FirstOrDefault(x => x.IsOfType(obj));

            if (serializer == null)
            {
                throw new NotImplementedException($"Serialization of {obj.GetType().Name} is not supported yet!");
            }

            serializer.WriteToStream(aw, obj);

            /*
             * switch (obj)
             * {
             *  case Tex tex:
             *      WriteToStream(aw, tex);
             *      break;
             *  case HMXBitmap bitmap:
             *      WriteToStream(aw, bitmap);
             *      break;
             *  case MiloObjectBytes bytes:
             *      WriteToStream(aw, bytes);
             *      break;
             *  default:
             *      throw new NotImplementedException($"Serialization of {obj.GetType().Name} is not supported yet!");
             * } */
        }
コード例 #11
0
    private void method_33(JsonWriter jsonWriter_0, ISerializable iserializable_0, JsonISerializableContract jsonISerializableContract_0, JsonProperty jsonProperty_0, JsonContainerContract jsonContainerContract_0, JsonProperty jsonProperty_1)
    {
        if (!Class124.smethod_18())
        {
            string text = "Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
            text = text.smethod_0(CultureInfo.InvariantCulture, iserializable_0.GetType());
            throw JsonSerializationException.Create(null, jsonWriter_0.xEuXaafal7(), text, null);
        }
        this.method_17(jsonWriter_0, jsonISerializableContract_0, iserializable_0);
        this.list_0.Add(iserializable_0);
        this.method_21(jsonWriter_0, iserializable_0, jsonISerializableContract_0, jsonProperty_0, jsonContainerContract_0, jsonProperty_1);
        SerializationInfo serializationInfo = new SerializationInfo(jsonISerializableContract_0.UnderlyingType, new FormatterConverter());

        iserializable_0.GetObjectData(serializationInfo, this.jsonSerializer_0.streamingContext_0);
        foreach (SerializationEntry serializationEntry in serializationInfo)
        {
            JsonContract jsonContract_ = this.method_7(serializationEntry.Value);
            if (this.method_11(serializationEntry.Value, null, jsonContract_, jsonISerializableContract_0, jsonProperty_0))
            {
                jsonWriter_0.WritePropertyName(serializationEntry.Name);
                this.method_14(jsonWriter_0, serializationEntry.Value);
            }
            else if (this.method_13(jsonWriter_0, serializationEntry.Value, null, jsonContract_, jsonISerializableContract_0, jsonProperty_0))
            {
                jsonWriter_0.WritePropertyName(serializationEntry.Name);
                this.method_9(jsonWriter_0, serializationEntry.Value, jsonContract_, null, jsonISerializableContract_0, jsonProperty_0);
            }
        }
        jsonWriter_0.WriteEndObject();
        this.list_0.RemoveAt(this.list_0.Count - 1);
        this.method_18(jsonWriter_0, jsonISerializableContract_0, iserializable_0);
    }
コード例 #12
0
        public static PropertyWrapper[] GetProperties(ISerializable obj)
        {
            var buf = new List <PropertyWrapper>();

            SerializationInfo info = new SerializationInfo(obj.GetType(), new FormatterConverter());

            obj.GetObjectData(info, new StreamingContext());

            var mData    = (object[])info.GetMemberValue("m_data");
            var mTypes   = (Type[])info.GetMemberValue("m_types");
            var mMembers = (string[])info.GetMemberValue("m_members");
            var indexes  = (Dictionary <string, int>)info.GetMemberValue("m_nameToIndex");

            foreach (var pair in indexes)
            {
                var member = pair.Key;

                if (indexes.ContainsKey(member))
                {
                    var prp = new PropertyWrapper()
                    {
                        PropertyName  = member,
                        PropertyValue = Wrap(mData[indexes[member]])
                    };

                    buf.Add(prp);
                }
            }


            return(buf.ToArray());

            throw new NotImplementedException();
        }
コード例 #13
0
ファイル: TypedPublisher.cs プロジェクト: xuchdong/umundo
        /// <summary>
        /// Retrieves a message from the given serializable that can be sent over umundo.
        /// The name is automatically determined.
        /// </summary>
        /// <param name="serializable">the object to send</param>
        /// <returns></returns>
        public Message PrepareMessage(ISerializable serializable)
        {
            byte[] buffer = Serialize(serializable);
            string type   = serializable.GetType().Name;

            return(PrepareMessage(type, buffer));
        }
コード例 #14
0
        public Serializer(ISerializable target)
        {
            _serializedData = new XElement("object");

            _serializedData.Add(new XAttribute("id", target.ID));
            _serializedData.Add(new XAttribute("type", target.GetType()));
        }
コード例 #15
0
ファイル: Param.cs プロジェクト: ewin66/Monitor
 public String ToStr()
 {
     try
     {
         if (mValue == null)
         {
             return("<OutParam Name=" + mName + " Class=String>" + mValue + "</OutParam>");
         }
         else if (mValue is String)
         {
             return("<OutParam Name=" + mName + " Class=String>" + mValue
                    + "</OutParam>");
         }
         else
         {
             ISerializable value = (ISerializable)mValue;
             return("<OutParam Name=" + mName + " Class=" + value.GetType()
                    + ">" + value.ToStr() + "</OutParam>");
         }
     }
     catch
     {
         return("<OutParam Name=" + mName + " Class=String>" + mValue + "</OutParam>");
     }
 }
        public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
        {
            Type type = obj.GetType();
            SerializationInfo serInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter);

            this.GetObjectData(obj, serInfo, base.GetStreamingContext());
            this.WriteSerializationInfo(xmlWriter, type, serInfo);
        }
コード例 #17
0
ファイル: TypedPublisher.cs プロジェクト: Memphiz/umundo
        /// <summary>
        /// Sends the serializable object and autmatically determine the name.
        /// </summary>
        /// <param name="o">the object to send</param>
        public void SendObject(ISerializable o)
        {
            byte[]  buffer  = Serialize(o);
            string  type    = o.GetType().Name;
            Message message = PrepareMessage(type, buffer);

            send(message);
        }
        internal static SerializationInfo GetSerializationInfo(this ISerializable serializable)
        {
            var serializationInfo = new SerializationInfo(serializable.GetType(), new FormatterConverter());

            serializable.GetObjectData(serializationInfo, new StreamingContext(StreamingContextStates.Persistence));

            return(serializationInfo);
        }
コード例 #19
0
        public SurrogateForISerializable(ISerializable serializable)
        {
            var serializationInfo = new SerializationInfo(serializable.GetType(), new FormatterConverter());
            var streamingContext  = new StreamingContext(StreamingContextStates.Clone);

            serializable.GetObjectData(serializationInfo, streamingContext);
            keys   = new string[serializationInfo.MemberCount];
            values = new object[serializationInfo.MemberCount];
            var i = 0;

            foreach (var entry in serializationInfo)
            {
                keys[i]   = entry.Name;
                values[i] = entry.Value;
                i++;
            }
            assemblyQualifiedName = serializable.GetType().AssemblyQualifiedName;
        }
コード例 #20
0
 /// <summary>
 /// Serializes an object that implements ISerializable into a json string.
 /// </summary>
 /// <param name="obj">The object to be serialized</param>
 /// <returns>A json string of the serialized object</returns>
 public static string ToJson(this ISerializable obj)
 {
     using (var stream = new MemoryStream()) {
         var a = new DataContractJsonSerializer(obj.GetType());
         a.WriteObject(stream, obj);
         stream.Position = 0;
         using (var reader = new StreamReader(stream)) {
             return(reader.ReadToEnd());
         }
     }
 }
        internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
        {
            Type type = obj.GetType();
            SerializationInfo info = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter);

            obj.GetObjectData(info, base.GetStreamingContext());
            if (DataContract.GetClrTypeFullName(type) != info.FullTypeName)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString("ChangingFullTypeNameNotSupported", new object[] { info.FullTypeName, DataContract.GetClrTypeFullName(type) })));
            }
            base.WriteSerializationInfo(xmlWriter, type, info);
        }
コード例 #22
0
        protected bool SerializeSerializable(ISerializable obj, StringBuilder builder)
        {
            IDictionary       ht   = ordered ? new OrderedDictionary() : (IDictionary) new Hashtable();
            SerializationInfo info = new SerializationInfo(obj.GetType(), new FormatterConverter());

            obj.GetObjectData(info, new StreamingContext(StreamingContextStates.Persistence));
            foreach (SerializationEntry entry in info)
            {
                ht [entry.Name] = entry.Value;
            }
            return(SerializeObject(ht, builder));
        }
コード例 #23
0
        public static void Write(this BinaryWriter writer, ISerializable serializable)
        {
            SerializerPointer serializerPointer = serializable.GetType().GetCustomAttribute <SerializerPointer>();

            if (serializerPointer == null)
            {
                throw new FieldAccessException("Serializable does not have a pointer attribute!");
            }

            writer.Write(serializerPointer.Identifier);
            serializable.ToByteArray(writer);
        }
コード例 #24
0
        private Department GetDepartmentFromISerializable(ISerializable iSerializable)
        {
            Department        department = new Department();
            SerializationInfo si         = new SerializationInfo(iSerializable.GetType(), new FormatterConverter());

            iSerializable.GetObjectData(si, new StreamingContext());
            department.Name         = si.GetString("Name");
            department.DepartmentID = si.GetInt16("DepartmentID");
            department.GroupName    = si.GetString("GroupName");
            department.ModifiedDate = si.GetDateTime("ModifiedDate");
            return(department);
        }
コード例 #25
0
ファイル: XmlSerializer.cs プロジェクト: vulf3d/BFE.Net
        public static void Serialize(ISerializable obj)
        {
            SerializationInfo info    = new SerializationInfo(obj.GetType(), new FormatterConverter());
            StreamingContext  context = new StreamingContext();

            obj.GetObjectData(info, context);


            while (true)
            {
            }
        }
コード例 #26
0
        public void ReadFromStream(Stream stream, ISerializable data)
        {
            var serializer = Serializers.FirstOrDefault(x => x.IsOfType(data));

            if (serializer == null)
            {
                throw new NotImplementedException($"Deserialization of {data.GetType().Name} is not supported yet!");
            }

            var ar = new AwesomeReader(stream, Info.BigEndian);

            serializer.ReadFromStream(ar, data);
        }
コード例 #27
0
ファイル: Param.cs プロジェクト: ewin66/Monitor
 public String ToXml()
 {
     try
     {
         ISerializable value = (ISerializable)mValue;
         return("<OutParam Name=" + mName + " Class=" + value.GetType()
                + ">" + value.ToXml() + "</OutParam>");
     }
     catch
     {
         return("<OutParam Name=" + mName + " Class=String>" + mValue + "</OutParam>");
     }
 }
コード例 #28
0
        private static void CheckObjectTypeIntegrity(ISerializable serializable)
        {
            SerializationInfo testData = new SerializationInfo(serializable.GetType(), new FormatterConverter());

            serializable.GetObjectData(testData, new StreamingContext(StreamingContextStates.Other));

            foreach (SerializationEntry entry in testData)
            {
                if (entry.Value != null)
                {
                    Assert.IsAssignableFrom(entry.ObjectType, entry.Value);
                }
            }
        }
コード例 #29
0
        protected bool SerializeSerializable(ISerializable obj, StringBuilder builder)
        {
            IDictionary       anObject = this.ordered ? ((IDictionary) new OrderedDictionary()) : ((IDictionary) new Hashtable());
            SerializationInfo info     = new SerializationInfo(obj.GetType(), new FormatterConverter());

            obj.GetObjectData(info, new StreamingContext(StreamingContextStates.Persistence));
            SerializationInfoEnumerator enumerator = info.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SerializationEntry current = enumerator.Current;
                anObject[current.Name] = current.Value;
            }
            return(this.SerializeObject(anObject, builder));
        }
コード例 #30
0
        internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
        {
            Type objType = obj.GetType();
            var  serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter);

            GetObjectData(obj, serInfo, GetStreamingContext());
            if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType))));
            }
            else
            {
                base.WriteSerializationInfo(xmlWriter, objType, serInfo);
            }
        }
コード例 #31
0
        public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
        {
            Type objType = obj.GetType();
            var  serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter /*!UnsafeTypeForwardingEnabled is always false*/);

            GetObjectData(obj, serInfo, GetStreamingContext());

            if (!UnsafeTypeForwardingEnabled && serInfo.AssemblyName == Globals.MscorlibAssemblyName)
            {
                // Throw if a malicious type tries to set its assembly name to "0" to get deserialized in mscorlib
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ISerializableAssemblyNameSetToZero, DataContract.GetClrTypeFullName(obj.GetType()))));
            }

            WriteSerializationInfo(xmlWriter, objType, serInfo);
        }
コード例 #32
0
        /// <summary>
        /// Method which executes single ROP with multiple server objects.
        /// </summary>
        /// <param name="ropRequest">ROP request object.</param>
        /// <param name="inputObjHandles">Server object handles in request.</param>
        /// <param name="response">ROP response object.</param>
        /// <param name="rawData">The ROP response payload.</param>
        /// <param name="expectedRopResponseType">ROP response type expected.</param>
        /// <returns>Server objects handles in response.</returns>
        public List<List<uint>> ProcessSingleRopWithMutipleServerObjects(
            ISerializable ropRequest,
            List<uint> inputObjHandles,
            ref IDeserializable response,
            ref byte[] rawData,
            RopResponseType expectedRopResponseType)
        {
            List<ISerializable> requestRops = new List<ISerializable>
            {
                ropRequest
            };

            List<uint> requestSOH = new List<uint>();
            for (int i = 0; i < inputObjHandles.Count; i++)
            {
                requestSOH.Add(inputObjHandles[i]);
            }

            if (Common.IsOutputHandleInRopRequest(ropRequest))
            {
                 // Add an element for server output object handle, set default value to 0xFFFFFFFF
                requestSOH.Add(DefaultOutputHandle);
            }

            List<IDeserializable> responseRops = new List<IDeserializable>();
            List<List<uint>> responseSOHs = new List<List<uint>>();

            uint ret = this.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, MaxRgbOut);
            if (ret != OxcRpcErrorCode.ECNone)
            {
                Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", ret);
                return responseSOHs;
            }

            if (responseRops != null)
            {
                if (responseRops.Count > 0)
                {
                    response = responseRops[0];
                }
            }
            else
            {
                response = null;
            }

            if (ropRequest.GetType() == typeof(RopReleaseRequest))
            {
                return responseSOHs;
            }

            try
            {
                this.VerifyAdapterCaptureCode(expectedRopResponseType, response, ropRequest);
            }
            catch (TargetInvocationException invocationEx)
            {
                Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
                if (invocationEx.InnerException != null)
                {
                    throw invocationEx.InnerException;
                }
            }
            catch (NullReferenceException nullEx)
            {
                Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
            }

            return responseSOHs;
        }
コード例 #33
0
 // Token: 0x06000C07 RID: 3079
 // RVA: 0x00047744 File Offset: 0x00045944
 private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
     if (!JsonTypeReflector.FullyTrusted)
     {
         string text = "Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
         text = StringUtils.FormatWith(text, CultureInfo.InvariantCulture, value.GetType());
         throw JsonSerializationException.Create(null, writer.ContainerPath, text, null);
     }
     this.OnSerializing(writer, contract, value);
     this._serializeStack.Add(value);
     this.WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
     SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
     value.GetObjectData(serializationInfo, this.Serializer._context);
     SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();
     while (enumerator.MoveNext())
     {
         SerializationEntry current = enumerator.Current;
         JsonContract contractSafe = this.GetContractSafe(current.Value);
         if (this.ShouldWriteReference(current.Value, null, contractSafe, contract, member))
         {
             writer.WritePropertyName(current.Name);
             this.WriteReference(writer, current.Value);
         }
         else if (this.CheckForCircularReference(writer, current.Value, null, contractSafe, contract, member))
         {
             writer.WritePropertyName(current.Name);
             this.SerializeValue(writer, current.Value, contractSafe, null, contract, member);
         }
     }
     writer.WriteEndObject();
     this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
     this.OnSerialized(writer, contract, value);
 }
コード例 #34
0
        /// <summary>
        /// Send ROP request with single operation.
        /// </summary>
        /// <param name="ropRequest">ROP request objects.</param>
        /// <param name="insideObjHandle">Server object handle in request.</param>
        /// <param name="response">ROP response objects.</param>
        /// <param name="rawData">The ROP response payload.</param>
        /// <param name="getPropertiesFlag">The flag indicate the test cases expect to get which object type's properties(message's properties or attachment's properties).</param>
        /// <param name="returnValue">An unsigned integer value indicates the return value of call EcDoRpcExt2 method.</param>
        /// <returns>Server objects handles in response.</returns>
        public List<List<uint>> DoRopCall(ISerializable ropRequest, uint insideObjHandle, ref object response, ref byte[] rawData, GetPropertiesFlags getPropertiesFlag, out uint returnValue)
        {
            List<ISerializable> requestRops = new List<ISerializable>
            {
                ropRequest
            };

            List<uint> requestSOH = new List<uint>
            {
                insideObjHandle
            };

            if (Common.IsOutputHandleInRopRequest(ropRequest))
            {
                // Add an element for server output object handle, set default value to 0xFFFFFFFF
                requestSOH.Add(DefaultOutputHandle);
            }
            
            List<IDeserializable> responseRops = new List<IDeserializable>();
            List<List<uint>> responseSOHs = new List<List<uint>>();

            // 0x10008 specifies the maximum size of the rgbOut buffer to place in Response.
            uint ret = this.oxcropsClient.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, 0x10008);
            returnValue = ret;
            if (ret == OxcRpcErrorCode.ECRpcFormat)
            {
                this.Site.Assert.Fail("Error RPC Format");
            }

            if (ret != 0)
            {
                return responseSOHs;
            }

            if (responseRops != null)
            {
                if (responseRops.Count > 0)
                {
                    response = responseRops[0];
                }
            }
            else
            {
                response = null;
            }

            if (ropRequest.GetType() == typeof(RopReleaseRequest))
            {
                return responseSOHs;
            }

            byte ropId = (byte)BitConverter.ToInt16(ropRequest.Serialize(), 0);

            List<PropertyObj> pts = null;
            switch (ropId)
            {
                case (byte)RopId.RopOpenMessage:
                    RopOpenMessageResponse openMessageResponse = (RopOpenMessageResponse)response;

                    // This check is for the open specification expectation for a particular request with some valid input parameters.
                    if (openMessageResponse.ReturnValue == 0x00000000)
                    {
                        this.VerifyRopOpenMessageResponse(openMessageResponse);
                    }

                    break;

                case (byte)RopId.RopGetPropertiesSpecific:
                    // RopGetPropertiesSpecificRequest
                    pts = PropertyHelper.GetPropertyObjFromBuffer(((RopGetPropertiesSpecificRequest)ropRequest).PropertyTags, (RopGetPropertiesSpecificResponse)response);

                    foreach (PropertyObj pitem in pts)
                    {
                        // Verify capture code for MS-OXCMSG. 
                        this.VerifyMessageSyntaxDataType(pitem);
                    }

                    PropertyObj propertyObjPidTagSubjectPrefix = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagSubjectPrefix);
                    PropertyObj propertyObjPidTagNormalizedSubject = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagNormalizedSubject);

                    // Verify the message of PidTagSubjectPrefixAndPidTagNormalizedSubject
                    if (PropertyHelper.IsPropertyValid(propertyObjPidTagSubjectPrefix) || PropertyHelper.IsPropertyValid(propertyObjPidTagNormalizedSubject))
                    {
                        this.VerifyMessageSyntaxPidTagSubjectPrefixAndPidTagNormalizedSubject(propertyObjPidTagSubjectPrefix, propertyObjPidTagNormalizedSubject);
                    }

                    // Verify the requirements of PidTagAttachmentLinkId and PidTagAttachmentFlags.
                    PropertyObj pidTagAttachmentLinkId = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAttachmentLinkId);
                    if (PropertyHelper.IsPropertyValid(pidTagAttachmentLinkId))
                    {
                        this.VerifyMessageSyntaxPidTagAttachmentLinkIdAndPidTagAttachmentFlags(pidTagAttachmentLinkId);
                    }

                    PropertyObj pidTagAttachmentFlags = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAttachmentFlags);
                    if (PropertyHelper.IsPropertyValid(pidTagAttachmentFlags))
                    {
                        this.VerifyMessageSyntaxPidTagAttachmentLinkIdAndPidTagAttachmentFlags(pidTagAttachmentFlags);
                    }

                    // Verify the requirements of PidTagDisplayName
                    PropertyObj pidTagDisplayName = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagDisplayName);
                    PropertyObj pidTagAttachLongFilename = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAttachLongFilename);

                    if (PropertyHelper.IsPropertyValid(pidTagDisplayName) && PropertyHelper.IsPropertyValid(pidTagAttachLongFilename))
                    {
                        this.VerifyMessageSyntaxPidTagDisplayName(pidTagDisplayName, pidTagAttachLongFilename);
                    }

                    PropertyObj pidTagObjectType = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagObjectType);
                    PropertyObj pidTagRecordKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagRecordKey);

                    this.VerifyPidTagObjectTypeAndPidTagRecordKey(pidTagObjectType, pidTagRecordKey);
                    break;

                case (byte)RopId.RopGetPropertiesAll:
                    RopGetPropertiesAllResponse getPropertiesAllResponse = (RopGetPropertiesAllResponse)response;
                    pts = PropertyHelper.GetPropertyObjFromBuffer(getPropertiesAllResponse);

                    foreach (PropertyObj pitem in pts)
                    {
                        // Verify capture code for MS-OXCMSG. 
                        this.VerifyMessageSyntaxDataType(pitem);
                    }

                    // Verify the requirements of PidTagArchiveDate
                    PropertyObj pidTagArchiveDateObj = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagArchiveDate);
                    PropertyObj pidTagStartDateEtc = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagStartDateEtc);

                    if (PropertyHelper.IsPropertyValid(pidTagArchiveDateObj))
                    {
                        if (PropertyHelper.IsPropertyValid(pidTagStartDateEtc))
                        {
                            byte[] byteDest = new byte[8];
                            Array.Copy((byte[])pidTagStartDateEtc.Value, 6, byteDest, 0, 8);
                            this.VerifyMessageSyntaxPidTagArchiveDate(pidTagArchiveDateObj, DateTime.FromFileTimeUtc(BitConverter.ToInt64(byteDest, 0)));
                        }
                    }

                    PropertyObj pidTagAccessLevel = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAccessLevel);
                    pidTagRecordKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagRecordKey);

                    if (getPropertiesFlag == GetPropertiesFlags.MessageProperties)
                    {
                        PropertyObj pidTagAccess = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagAccess);

                        PropertyObj pidTagChangeKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagChangeKey);
                        PropertyObj pidTagCreationTime = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagCreationTime);
                        PropertyObj pidTagLastModificationTime = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagLastModificationTime);
                        PropertyObj pidTagLastModifierName = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagLastModifierName);
                        PropertyObj pidTagSearchKey = PropertyHelper.GetPropertyByName(pts, PropertyNames.PidTagSearchKey);

                        // Verify properties PidTagAccess, PidTagAccessLevel, PidTagChangeKey, PidTagCreationTime, PidTagLastModificationTime, PidTagLastModifierName and PidTagSearchKey exist on all Message objects.
                        this.VerifyPropertiesExistOnAllMessageObject(pidTagAccess, pidTagAccessLevel, pidTagChangeKey, pidTagCreationTime, pidTagLastModificationTime, pidTagLastModifierName, pidTagSearchKey);
                    }

                    if (getPropertiesFlag == GetPropertiesFlags.AttachmentProperties)
                    {
                        // Verify properties PidTagAccessLevel and PidTagRecordKey exist on any Attachment object.
                        this.VerifyPropertiesExistOnAllAttachmentObject(pidTagAccessLevel, pidTagRecordKey);
                    }

                    break;

                case (byte)RopId.RopCreateMessage:
                    RopCreateMessageResponse createMessageResponse = (RopCreateMessageResponse)response;

                    // Adapter requirements related with RopCreateMessage will be verified if the response is a successful one.
                    if (createMessageResponse.ReturnValue == 0x00000000)
                    {
                        int hasMessageId = createMessageResponse.HasMessageId;
                        this.VerifyMessageSyntaxHasMessageId(hasMessageId);
                    }

                    break;

                case (byte)RopId.RopReadRecipients:
                    RopReadRecipientsResponse readRecipientsResponse = (RopReadRecipientsResponse)response;

                    // Adapter requirements related with RopReadRecipients will be verified if the response is a successful one.
                    if (readRecipientsResponse.ReturnValue == 0x00000000)
                    {
                        this.VerifyMessageSyntaxRowCount(readRecipientsResponse);
                    }

                    break;

                case (byte)RopId.RopSetMessageStatus:
                    RopSetMessageStatusResponse setMessageStatusResponse = (RopSetMessageStatusResponse)response;

                    // Adapter requirements related with RopSetMessageStatus will be verified if the response is a successful one.
                    if (setMessageStatusResponse.ReturnValue == 0x00000000)
                    {
                        this.VerifyMessageSyntaxMessageStatusFlags(setMessageStatusResponse);
                    }

                    break;

                case (byte)RopId.RopCreateAttachment:
                    RopCreateAttachmentResponse createAttachmentResponse = (RopCreateAttachmentResponse)response;

                    // Adapter requirements related with RopCreateAttachment will be verified if the response is a successful one.
                    if (createAttachmentResponse.ReturnValue == 0x00000000)
                    {
                        int id = (int)createAttachmentResponse.AttachmentID;
                        this.VerifyDataStructureRopCreateAttachmentResponse(createAttachmentResponse, id);
                    }

                    break;

                case (byte)RopId.RopOpenEmbeddedMessage:
                    RopOpenEmbeddedMessageResponse openEmbeddedMessageResponse = (RopOpenEmbeddedMessageResponse)response;

                    // Adapter requirements related with RopOpenEmbeddedMessage will be verified if the response is a successful one.
                    if (openEmbeddedMessageResponse.ReturnValue == 0x00000000)
                    {
                        ulong mid = openEmbeddedMessageResponse.MessageId;
                        this.VerifyDataStructureRopOpenEmbeddedMessageResponse(openEmbeddedMessageResponse, mid);
                    }

                    break;

                case (byte)RopId.RopSetMessageReadFlag:
                    RopSetMessageReadFlagResponse setMessageReadFlagResponse = (RopSetMessageReadFlagResponse)response;

                    // Adapter requirements related with RopSetMessageReadFlag will be verified if the response is a successful one.
                    if (setMessageReadFlagResponse.ReturnValue == 0x00000000)
                    {
                        this.VerifyMessageSyntaxReadStatusChanged(setMessageReadFlagResponse, (RopSetMessageReadFlagRequest)ropRequest);
                    }

                    break;

                case (byte)RopId.RopSetReadFlags:
                    // Adapter requirements related with RopSetReadFlags will be verified if the response is a successful one.
                    if (((RopSetReadFlagsResponse)response).ReturnValue == 0x00000000)
                    {
                        this.VerifyRopSetReadFlagsResponse((RopSetReadFlagsResponse)response);
                    }

                    break;

                case (byte)RopId.RopGetMessageStatus:
                    // Adapter requirements related with RopGetMessageStatus will be verified if the response is a successful one.
                    if (((RopSetMessageStatusResponse)response).ReturnValue == 0x00000000)
                    {
                        this.VerifyGetMessageStatusResponse((RopSetMessageStatusResponse)response);
                    }

                    break;

                default:
                    break;
            }

           this.VerifyMAPITransport();

            return responseSOHs;
        }
 internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
 {
     Type type = obj.GetType();
     SerializationInfo info = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter);
     obj.GetObjectData(info, base.GetStreamingContext());
     if (DataContract.GetClrTypeFullName(type) != info.FullTypeName)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString("ChangingFullTypeNameNotSupported", new object[] { info.FullTypeName, DataContract.GetClrTypeFullName(type) })));
     }
     base.WriteSerializationInfo(xmlWriter, type, info);
 }
コード例 #36
0
ファイル: CompositeCustomData.cs プロジェクト: itadapter/nfx
        private void serializeFromISerializable(ISerializable data)
        {
            m_CustomData = new Dictionary<string,CustomTypedEntry>();

                    var info = new SerializationInfo(data.GetType(), new FormatterConverter());
                    StreamingContext streamingContext = new StreamingContext(StreamingContextStates.Persistence);
                    data.GetObjectData(info, streamingContext);

                    var senum = info.GetEnumerator();
                    while(senum.MoveNext())
                    {
                        var value = new CustomTypedEntry();
                        value.TypeIndex = MetaType.GetExistingOrNewMetaTypeIndex( m_Document, senum.ObjectType );
                        value.Data = m_Document.NativeDataToPortableData( senum.Value );
                        m_CustomData[senum.Name] = value;
                    }
        }
コード例 #37
0
        /// <summary>
        /// Method which executes single ROP.
        /// </summary>
        /// <param name="ropRequest">ROP request objects.</param>
        /// <param name="inputObjHandle">Server object handle in request.</param>
        /// <param name="response">ROP response objects.</param>
        /// <param name="rawData">The ROP response payload.</param>
        /// <param name="expectedRopResponseType">ROP response type expected.</param>
        /// <param name="returnValue">The return value of the ROP method.</param>
        /// <returns>Server objects handles in response.</returns>
        public List<List<uint>> ProcessSingleRopWithReturnValue(
            ISerializable ropRequest,
            uint inputObjHandle,
            ref IDeserializable response,
            ref byte[] rawData,
            RopResponseType expectedRopResponseType,
            out uint returnValue)
        {
            List<ISerializable> requestRops = null;
            if (ropRequest != null)
            {
                requestRops = new List<ISerializable>
                {
                    ropRequest
                };
            }

            List<uint> requestSOH = new List<uint>
            {
                inputObjHandle
            };

            if (Common.IsOutputHandleInRopRequest(ropRequest))
            {
                // Add an element for server output object handle and set default value to 0xFFFFFFFF.
                requestSOH.Add(DefaultOutputHandle);
            }

            if (this.IsInvalidInputHandleNeeded(ropRequest, expectedRopResponseType))
            {
                // Add an invalid input handle in request and set its value to 0xFFFFFFFF.
                requestSOH.Add(InvalidInputHandle);
            }

            List<IDeserializable> responseRops = new List<IDeserializable>();
            List<List<uint>> responseSOHs = new List<List<uint>>();

            uint ret = this.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, MaxRgbOut);
            returnValue = ret;
            if (ret != OxcRpcErrorCode.ECNone && ret != 1726)
            {
                Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", ret);
                return responseSOHs;
            }

            if (responseRops != null)
            {
                if (responseRops.Count > 0)
                {
                    response = responseRops[0];
                }
            }
            else
            {
                response = null;
            }

            if (ropRequest.GetType() == typeof(RopReleaseRequest))
            {
                return responseSOHs;
            }

            if (response.GetType() == typeof(RopSaveChangesMessageResponse) && ((RopSaveChangesMessageResponse)response).ReturnValue == 0x80040401)
            {
                return responseSOHs;
            }

            if (response != null)
            {
                try
                {
                    this.VerifyAdapterCaptureCode(expectedRopResponseType, response, ropRequest);
                }
                catch (TargetInvocationException invocationEx)
                {
                    Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
                    if (invocationEx.InnerException != null)
                    {
                        throw invocationEx.InnerException;
                    }
                }
                catch (NullReferenceException nullEx)
                {
                    Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
                }
            }

            return responseSOHs;
        }
コード例 #38
0
        /// <summary>
        /// Method which executes single ROP with multiple server objects.
        /// </summary>
        /// <param name="ropRequest">ROP request object.</param>
        /// <param name="insideObjHandle">Server object handles in request.</param>
        /// <param name="response">ROP response object.</param>
        /// <param name="rawData">The ROP response payload.</param>
        /// <param name="expectedRopResponseType">ROP response type expected.</param>
        /// <returns>Server objects handles in response.</returns>
        private List<List<uint>> ProcessSingleRopWithMutipleServerObjects(
            ISerializable ropRequest,
            List<uint> insideObjHandle,
            ref IDeserializable response,
            ref byte[] rawData,
            RopResponseType expectedRopResponseType)
        {
            List<ISerializable> requestRops = new List<ISerializable>
            {
                ropRequest
            };

            List<uint> requestSOH = new List<uint>();
            for (int i = 0; i < insideObjHandle.Count; i++)
            {
                requestSOH.Add(insideObjHandle[i]);
            }

            if (Common.IsOutputHandleInRopRequest(ropRequest))
            {
                // Add an element for server output object handle, set default value to 0xFFFFFFFF
                requestSOH.Add(DefaultOutputHandle);
            }

            List<IDeserializable> responseRops = new List<IDeserializable>();
            List<List<uint>> responseSOHs = new List<List<uint>>();

            uint ret = this.oxcropsClient.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, MaxRgbOut);
            this.Site.Assert.AreEqual<uint>(OxcRpcErrorCode.ECNone, ret, "ROP call should return 0 for success, actually it returns {0}", ret);
            if (responseRops != null)
            {
                if (responseRops.Count > 0)
                {
                    response = responseRops[0];
                }
            }
            else
            {
                response = null;
            }

            if (ropRequest is RopReleaseRequest)
            {
                return responseSOHs;
            }

            try
            {
                string resName = response.GetType().Name;

                // The word "Response" takes 8 length.
                string ropName = resName.Substring(0, resName.Length - 8);
                Type adapterType = typeof(MS_OXCPRPTAdapter);

                // Call capture code using reflection mechanism
                // The code followed is to construct the verify method name of capture code and then call this method through reflection.
                string verifyMethodName = string.Empty;
                if (expectedRopResponseType == RopResponseType.SuccessResponse)
                {
                    verifyMethodName = "Verify" + ropName + "SuccessResponse";
                }
                else if (expectedRopResponseType == RopResponseType.FailureResponse)
                {
                    verifyMethodName = "Verify" + ropName + "FailureResponse";
                }
                else if (expectedRopResponseType == RopResponseType.Response)
                {
                    verifyMethodName = "Verify" + ropName + "Response";
                }
                else if (expectedRopResponseType == RopResponseType.NullDestinationFailureResponse)
                {
                    verifyMethodName = "Verify" + ropName + "NullDestinationFailureResponse";
                }
                else if (expectedRopResponseType == RopResponseType.RedirectResponse)
                {
                    verifyMethodName = "Verify" + ropName + "RedirectResponse";
                }

                Type reqType = ropRequest.GetType();
                MethodInfo method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
                if (method == null)
                {
                    if (expectedRopResponseType == RopResponseType.SuccessResponse || expectedRopResponseType == RopResponseType.FailureResponse)
                    {
                        verifyMethodName = "Verify" + ropName + "Response";
                        method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
                    }
                }

                if (method != null)
                {
                    ParameterInfo[] paraInfos = method.GetParameters();
                    int paraNum = paraInfos.Length;
                    object[] paraObjects = new object[paraNum];
                    paraObjects[0] = response;
                    for (int i = 1; i < paraNum; i++)
                    {
                        FieldInfo fieldInReq = reqType.GetField(
                            paraInfos[i].Name,
                            BindingFlags.IgnoreCase
                            | BindingFlags.DeclaredOnly
                            | BindingFlags.Public
                            | BindingFlags.NonPublic
                            | BindingFlags.GetField
                            | BindingFlags.Instance);
                        paraObjects[i] = fieldInReq.GetValue(ropRequest);
                    }

                    method.Invoke(this, paraObjects);
                }
            }
            catch (TargetInvocationException invocationEx)
            {
                Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
                if (invocationEx.InnerException != null)
                {
                    throw invocationEx.InnerException;
                }
            }
            catch (NullReferenceException nullEx)
            {
                Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
            }

            return responseSOHs;
        }
コード例 #39
0
        /// <summary>
        /// Verify adapter capture code using reflection mechanism.
        /// </summary>
        /// <param name="expectedRopResponseType">The Expected ROP response type.</param>
        /// <param name="response">ROP response object.</param>
        /// <param name="ropRequest">ROP request object.</param>
        private void VerifyAdapterCaptureCode(RopResponseType expectedRopResponseType, IDeserializable response, ISerializable ropRequest)
        {
            string resName = response.GetType().Name;

            // The word "Response" takes 8 length.
            string ropName = resName.Substring(0, resName.Length - 8);
            Type adapterType = typeof(MS_OXCROPSAdapter);

            // Call capture code using reflection mechanism
            // The code followed is to construct the verify method name of capture code and then call this method through reflection.
            string verifyMethodName = string.Empty;
            if (expectedRopResponseType == RopResponseType.SuccessResponse)
            {
                verifyMethodName = "Verify" + ropName + "SuccessResponse";
            }
            else if (expectedRopResponseType == RopResponseType.FailureResponse)
            {
                verifyMethodName = "Verify" + ropName + "FailureResponse";
            }
            else if (expectedRopResponseType == RopResponseType.Response)
            {
                verifyMethodName = "Verify" + ropName + "Response";
            }
            else if (expectedRopResponseType == RopResponseType.NullDestinationFailureResponse)
            {
                verifyMethodName = "Verify" + ropName + "NullDestinationFailureResponse";
            }
            else if (expectedRopResponseType == RopResponseType.RedirectResponse)
            {
                verifyMethodName = "Verify" + ropName + "RedirectResponse";
            }

            Type reqType = ropRequest.GetType();
            MethodInfo method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
            if (method == null)
            {
                if (expectedRopResponseType == RopResponseType.SuccessResponse || expectedRopResponseType == RopResponseType.FailureResponse)
                {
                    verifyMethodName = "Verify" + ropName + "Response";
                    method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
                }
            }

            if (method != null)
            {
                ParameterInfo[] paraInfos = method.GetParameters();
                int paraNum = paraInfos.Length;
                object[] paraObjects = new object[paraNum];
                paraObjects[0] = response;
                for (int i = 1; i < paraNum; i++)
                {
                    FieldInfo fieldInReq = reqType.GetField(
                        paraInfos[i].Name,
                        BindingFlags.IgnoreCase
                        | BindingFlags.DeclaredOnly
                        | BindingFlags.Public
                        | BindingFlags.NonPublic
                        | BindingFlags.GetField
                        | BindingFlags.Instance);
                    paraObjects[i] = fieldInReq.GetValue(ropRequest);
                }

                method.Invoke(this, paraObjects);
            }
        }
        internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
#endif
        {
            Type objType = obj.GetType();
            SerializationInfo serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter);
            GetObjectData(obj, serInfo, GetStreamingContext()); 
            if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType))));
            }
            else
            {
                base.WriteSerializationInfo(xmlWriter, objType, serInfo);
            }
        }
コード例 #41
0
    private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      if (!JsonTypeReflector.FullyTrusted)
      {
        throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
      }

      contract.InvokeOnSerializing(value, Serializer.Context);
      _serializeStack.Add(value);

      WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);

      SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
      value.GetObjectData(serializationInfo, Serializer.Context);

      foreach (SerializationEntry serializationEntry in serializationInfo)
      {
        writer.WritePropertyName(serializationEntry.Name);
        SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null, member);
      }

      writer.WriteEndObject();

      _serializeStack.RemoveAt(_serializeStack.Count - 1);
      contract.InvokeOnSerialized(value, Serializer.Context);
    }
コード例 #42
0
ファイル: TypedPublisher.cs プロジェクト: 0790486/umundo
 /// <summary>
 /// Sends the serializable object and autmatically determine the name.
 /// </summary>
 /// <param name="o">the object to send</param>
 public void SendObject(ISerializable o)
 {
     byte[] buffer = Serialize(o);
     string type = o.GetType().Name;
     Message message = PrepareMessage(type, buffer);
     send(message);
 }