public XmlObjectSerializerBodyWriter (
			object body, XmlObjectSerializer formatter)
			: base (true)
		{
			this.body = body;
			this.formatter = formatter;
		}
 private XmlObjectSerializerHeader(XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
 {
     this.syncRoot = new object();
     if (actor == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("actor");
     }
     this.mustUnderstand = mustUnderstand;
     this.relay = relay;
     this.serializer = serializer;
     this.actor = actor;
     if (actor == EnvelopeVersion.Soap12.UltimateDestinationActor)
     {
         this.isOneOneSupported = false;
         this.isOneTwoSupported = true;
     }
     else if (actor == EnvelopeVersion.Soap12.NextDestinationActorValue)
     {
         this.isOneOneSupported = false;
         this.isOneTwoSupported = true;
     }
     else if (actor == EnvelopeVersion.Soap11.NextDestinationActorValue)
     {
         this.isOneOneSupported = true;
         this.isOneTwoSupported = false;
     }
     else
     {
         this.isOneOneSupported = true;
         this.isOneTwoSupported = true;
         this.isNoneSupported = true;
     }
 }
        public static object Deserialize(string xmlContent, string serializerType)
        {
            object returnValue = null;
            SerializerTypes serializerTypeValue;
            Type instanceType;
            GetSerializerDetails(serializerType, out serializerTypeValue, out instanceType);

            if (serializerTypeValue == SerializerTypes.XmlSerializer)
            {
                StringReader sww = new StringReader(xmlContent);
                XmlReader reader = XmlReader.Create(sww);
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(instanceType);
                returnValue = serializer.Deserialize(reader);
            }
            else if (serializerTypeValue == SerializerTypes.XmlObjectSerializer)
            {
                XmlObjectSerializer serializer = new XmlObjectSerializer();
                returnValue = serializer.Deserialize(xmlContent, true);
            }
            else
            {
                if (instanceType == typeof(string))
                {
                    returnValue = xmlContent;
                }
                else
                {
                    var method = instanceType.GetMethod("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    returnValue = method.Invoke(null, new object[] { xmlContent });
                }
            }
            return returnValue;
        }
        public MessageSubscribtionInfo(DataContractKey contractKey, ICallHandler handler, XmlObjectSerializer serializer, bool receiveSelfPublish, IEnumerable<BusHeader> filterHeaders)
        {
            _handler = handler;
            _serializer = serializer;

            _filterInfo = new MessageFilterInfo(contractKey, receiveSelfPublish, filterHeaders);
        }
 public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
 {
     if (serializer == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
     }
     return new XmlObjectSerializerHeader(name, ns, value, serializer, mustUnderstand, actor, relay);
 }
 private WebFormatterSerializationContext(XmlObjectSerializer xmlSerializer)
 {
     if (xmlSerializer is DataContractJsonSerializer)
         ContentFormat = SerializationFormat.Json;
     else
         ContentFormat = SerializationFormat.Xml;
     XmlSerializer = xmlSerializer;
 }
 public XmlObjectSerializerFault(FaultCode code, FaultReason reason, object detail, XmlObjectSerializer serializer, string actor, string node)
 {
     this.code = code;
     this.reason = reason;
     this.detail = detail;
     this.serializer = serializer;
     this.actor = actor;
     this.node = node;
 }
Beispiel #8
0
		public FileTape(string tapeFolder)
		{
			if (string.IsNullOrEmpty(tapeFolder))
				throw new ArgumentNullException("tapeFolder");

			_tapeFolder = tapeFolder;

			_serializer = new NetDataContractSerializer();	
		}
 internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject, DataContractResolver dataContractResolver)
 {
     this.serializer = serializer;
     this.itemCount = 1;
     this.maxItemsInObjectGraph = maxItemsInObjectGraph;
     this.streamingContext = streamingContext;
     this.ignoreExtensionDataObject = ignoreExtensionDataObject;
     this.dataContractResolver = dataContractResolver;
 }
 internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject, System.Runtime.Serialization.DataContractResolver dataContractResolver)
 {
     this.scopedKnownTypes = new ScopedKnownTypes();
     this.serializer = serializer;
     this.itemCount = 1;
     this.maxItemsInObjectGraph = maxItemsInObjectGraph;
     this.streamingContext = streamingContext;
     this.ignoreExtensionDataObject = ignoreExtensionDataObject;
     this.dataContractResolver = dataContractResolver;
 }
        public JsonSerializer(Type type, XmlObjectSerializer fallbackSerializer, bool isCompress,
            SerializeContentTypes contentType)
        {
            this.type = type;
            this.isCustomSerialization = true;
            this.fallbackSerializer = fallbackSerializer;

            m_IsCompress = isCompress;
            m_ContentType = contentType;
        }
Beispiel #12
0
        /// <remarks>
        /// DataContractJsonSerializer : XmlObjectSerializer (abstract)
        /// DataContractSerializer : XmlObjectSerializer (abstract)
        /// </remarks>
        private string WriteObject(Location location, XmlObjectSerializer serializer)
        {
            var memoryStream = new System.IO.MemoryStream();

            serializer.WriteObject(memoryStream, location);

            memoryStream.Position = 0;
            var reader = new System.IO.StreamReader(memoryStream);
            var output = reader.ReadToEnd();
            return output;
        }
        static byte[] Serialize(object result, XmlObjectSerializer serializer)
        {
            byte[] body;
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, result);
                body = stream.ToArray();
            }

            //hack to remove the type info from the json
            var bodyString = Encoding.UTF8.GetString(body);

            var toReplace = $", {result.GetType().Assembly.GetName().Name}";

            bodyString = bodyString.Replace(toReplace, ", ServiceControl");

            body = Encoding.UTF8.GetBytes(bodyString);
            return body;
        }
 public XmlObjectSerializerHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) : this(serializer, mustUnderstand, actor, relay)
 {
     if (name == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
     }
     if (name.Length == 0)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("SFXHeaderNameCannotBeNullOrEmpty"), "name"));
     }
     if (ns == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
     }
     if (ns.Length > 0)
     {
         NamingHelper.CheckUriParameter(ns, "ns");
     }
     this.objectToSerialize = objectToSerialize;
     this.name = name;
     this.ns = ns;
 }
        public static ClaimSet DeserializeClaimSet(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer, XmlObjectSerializer claimSerializer)
        {
            if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return null;
            }
            else if (reader.IsStartElement(dictionary.X509CertificateClaimSet, dictionary.EmptyString))
            {
                reader.ReadStartElement();
                byte[] rawData = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return new X509CertificateClaimSet(new X509Certificate2(rawData), false);
            }
            else if (reader.IsStartElement(dictionary.SystemClaimSet, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return ClaimSet.System;
            }
            else if (reader.IsStartElement(dictionary.WindowsClaimSet, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return ClaimSet.Windows;
            }
            else if (reader.IsStartElement(dictionary.AnonymousClaimSet, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return ClaimSet.Anonymous;
            }
            else if (reader.IsStartElement(dictionary.ClaimSet, dictionary.EmptyString))
            {
                ClaimSet issuer = null;
                List<Claim> claims = new List<Claim>();
                reader.ReadStartElement();

                if (reader.IsStartElement(dictionary.PrimaryIssuer, dictionary.EmptyString))
                {
                    reader.ReadStartElement();
                    issuer = DeserializeClaimSet(reader, dictionary, serializer, claimSerializer);
                    reader.ReadEndElement();
                }

                while (reader.IsStartElement())
                {
                    reader.ReadStartElement();
                    claims.Add(DeserializeClaim(reader, dictionary, claimSerializer));
                    reader.ReadEndElement();
                }

                reader.ReadEndElement();
                return issuer != null ? new DefaultClaimSet(issuer, claims) : new DefaultClaimSet(claims);
            }
            else
            {
                return (ClaimSet)serializer.ReadObject(reader);
            }
        }
        private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string?dataContractName, string?dataContractNamespace)
        {
            Debug.Assert(attributes != null);

            var dataNode = new CollectionDataNode();

            InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);

            int         arraySize = attributes.ArraySZSize;
            XmlNodeType nodeType;

            while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement)
            {
                if (nodeType != XmlNodeType.Element)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader));
                }

                if (dataNode.ItemName == null)
                {
                    dataNode.ItemName      = xmlReader.LocalName;
                    dataNode.ItemNamespace = xmlReader.NamespaceURI;
                }
                if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace !))
                {
                    if (dataNode.Items == null)
                    {
                        dataNode.Items = new List <IDataNode?>();
                    }
                    dataNode.Items.Add(ReadExtensionDataValue(xmlReader));
                }
                else
                {
                    SkipUnknownElement(xmlReader);
                }
            }
            xmlReader.ReadEndElement();

            if (arraySize != -1)
            {
                dataNode.Size = arraySize;
                if (dataNode.Items == null)
                {
                    if (dataNode.Size > 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, 0)));
                    }
                }
                else if (dataNode.Size != dataNode.Items.Count)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, dataNode.Items.Count)));
                }
            }
            else
            {
                if (dataNode.Items != null)
                {
                    dataNode.Size = dataNode.Items.Count;
                }
                else
                {
                    dataNode.Size = 0;
                }
            }

            return(dataNode);
        }
        // Pattern-recognition logic: the method reads XML elements into DOM. To recognize as an array, it requires that
        // all items have the same name and namespace. To recognize as an ISerializable type, it requires that all
        // items be unqualified. If the XML only contains elements (no attributes or other nodes) is recognized as a
        // class/class hierarchy. Otherwise it is deserialized as XML.
        private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary <string, string>?namespaces,
                                                       string?dataContractName, string?dataContractNamespace)
        {
            bool   couldBeISerializableData = true;
            bool   couldBeCollectionData = true;
            bool   couldBeClassData = true;
            string?elementNs = null, elementName = null;
            var    xmlChildNodes               = new List <XmlNode>();
            IList <XmlAttribute>?xmlAttributes = null;

            if (namespaces != null)
            {
                xmlAttributes = new List <XmlAttribute>();
                foreach (KeyValuePair <string, string> prefixNsPair in namespaces)
                {
                    xmlAttributes.Add(AddNamespaceDeclaration(prefixNsPair.Key, prefixNsPair.Value));
                }
            }

            XmlNodeType nodeType;

            while ((nodeType = xmlReader.NodeType) != XmlNodeType.EndElement)
            {
                if (nodeType == XmlNodeType.Element)
                {
                    string ns   = xmlReader.NamespaceURI;
                    string name = xmlReader.LocalName;
                    if (couldBeISerializableData)
                    {
                        couldBeISerializableData = (ns.Length == 0);
                    }
                    if (couldBeCollectionData)
                    {
                        if (elementName == null)
                        {
                            elementName = name;
                            elementNs   = ns;
                        }
                        else
                        {
                            couldBeCollectionData = (string.CompareOrdinal(elementName, name) == 0) &&
                                                    (string.CompareOrdinal(elementNs, ns) == 0);
                        }
                    }
                }
                else if (xmlReader.EOF)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
                }
                else if (IsContentNode(xmlReader.NodeType))
                {
                    couldBeClassData = couldBeISerializableData = couldBeCollectionData = false;
                }

                if (_attributesInXmlData == null)
                {
                    _attributesInXmlData = new Attributes();
                }
                _attributesInXmlData.Read(xmlReader);

                XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader) !;
                xmlChildNodes.Add(childNode);

                if (namespaces == null)
                {
                    if (_attributesInXmlData.XsiTypeName != null)
                    {
                        childNode.Attributes !.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace));
                    }
                    if (_attributesInXmlData.FactoryTypeName != null)
                    {
                        childNode.Attributes !.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace));
                    }
                }
            }
            xmlReader.ReadEndElement();

            if (elementName != null && couldBeCollectionData)
            {
                return(ReadUnknownCollectionData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace));
            }
            else if (couldBeISerializableData)
            {
                return(ReadUnknownISerializableData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace));
            }
            else if (couldBeClassData)
            {
                return(ReadUnknownClassData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace));
            }
            else
            {
                XmlDataNode dataNode = new XmlDataNode();
                InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);
                dataNode.OwnerDocument = Document;
                dataNode.XmlChildNodes = xmlChildNodes;
                dataNode.XmlAttributes = xmlAttributes;
                return(dataNode);
            }
        }
Beispiel #18
0
 public override void WriteFullEndElement()
 {
     if (_depth == 0)
     {
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType())))));
     }
     _xmlWriter.WriteFullEndElement();
     _depth--;
 }
 internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
     : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
 {
     // Known types restricts the set of types that can be deserialized
     _unsafeTypeForwardingEnabled = true;
 }
 internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
     : this(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject, null)
 {
 }
 internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
     : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
 {
 }
        internal static Exception CreateSerializationException(string message)
#endif
        {
            return(XmlObjectSerializer.CreateSerializationException(message));
        }
        internal static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader)
#endif
        {
            return(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(string.Format(SRSerialization.ExpectingState, expectedState), xmlReader));
        }
 public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex])));
 }
        internal static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames)
#endif
        {
            StringBuilder stringBuilder = new StringBuilder();

            if (requiredIndex == memberNames.Length)
            {
                requiredIndex--;
            }
            for (int i = memberIndex + 1; i <= requiredIndex; i++)
            {
                if (stringBuilder.Length != 0)
                {
                    stringBuilder.Append(" | ");
                }
                stringBuilder.Append(memberNames[i].Value);
            }
            throw /*System.Runtime.Serialization.*/ DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, string.Format(SRSerialization.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString()))));
        }
        protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, ref DataContract dataContract)
        {
            object retObj = null;

            if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj))
            {
                return(retObj);
            }

            bool knownTypesAddedInCurrentScope = false;

            if (dataContract.KnownDataContracts != null)
            {
                scopedKnownTypes.Push(dataContract.KnownDataContracts);
                knownTypesAddedInCurrentScope = true;
            }

            if (attributes.XsiTypeName != null)
            {
                dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract);
                if (dataContract == null)
                {
                    if (DataContractResolver == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, string.Format(SRSerialization.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName))));
                    }
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, string.Format(SRSerialization.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName))));
                }
                knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope);
            }

            if (knownTypesAddedInCurrentScope)
            {
                object obj = ReadDataContractValue(dataContract, reader);
                scopedKnownTypes.Pop();
                return(obj);
            }
            else
            {
                return(ReadDataContractValue(dataContract, reader));
            }
        }
        protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj)
        {
            ReadAttributes(reader);

            if (attributes.Ref != Globals.NewObjectId)
            {
                if (_isGetOnlyCollection)
                {
                    throw /*System.Runtime.Serialization.*/ DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ErrorDeserializing, string.Format(SRSerialization.ErrorTypeInfo, DataContract.GetClrTypeFullName(declaredType)), string.Format(SRSerialization.XmlStartElementExpected, Globals.RefLocalName))));
                }
                else
                {
                    retObj = GetExistingObject(attributes.Ref, declaredType, name, ns);
                    reader.Skip();
                    return(true);
                }
            }
            else if (attributes.XsiNil)
            {
                reader.Skip();
                return(true);
            }
            return(false);
        }
        static void SerializePrimaryIdentity(IIdentity identity, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer)
        {
            if (identity != null && identity != SecurityUtils.AnonymousIdentity)
            {
                writer.WriteStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString);
                if (identity is WindowsIdentity)
                {
                    WindowsIdentity wid = (WindowsIdentity)identity;
                    writer.WriteStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString);
                    WriteSidAttribute(wid.User, dictionary, writer);

                    // This is to work around WOW64 bug Windows OS 1491447
                    string authenticationType = null;
                    using (WindowsIdentity self = WindowsIdentity.GetCurrent())
                    {
                        // is owner or admin?  AuthenticationType could throw un-authorized exception
                        if ((self.User == wid.Owner) || 
                            (wid.Owner != null && self.Groups.Contains(wid.Owner)) || 
                            (wid.Owner != SecurityUtils.AdministratorsSid && self.Groups.Contains(SecurityUtils.AdministratorsSid)))
                        {
                            authenticationType = wid.AuthenticationType;
                        }
                    }
                    if (!String.IsNullOrEmpty(authenticationType))
                        writer.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, authenticationType);
                    writer.WriteString(wid.Name);
                    writer.WriteEndElement();
                }
                else if (identity is WindowsSidIdentity)
                {
                    WindowsSidIdentity wsid = (WindowsSidIdentity)identity;
                    writer.WriteStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString);
                    WriteSidAttribute(wsid.SecurityIdentifier, dictionary, writer);
                    if (!String.IsNullOrEmpty(wsid.AuthenticationType))
                        writer.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, wsid.AuthenticationType);
                    writer.WriteString(wsid.Name);
                    writer.WriteEndElement();
                }
                else if (identity is GenericIdentity)
                {
                    GenericIdentity genericIdentity = (GenericIdentity)identity;
                    writer.WriteStartElement(dictionary.GenericIdentity, dictionary.EmptyString);
                    if (!String.IsNullOrEmpty(genericIdentity.AuthenticationType))
                        writer.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, genericIdentity.AuthenticationType);
                    writer.WriteString(genericIdentity.Name);
                    writer.WriteEndElement();
                }
                else
                {
                    serializer.WriteObject(writer, identity);
                }
                writer.WriteEndElement();
            }
        }
 static IIdentity DeserializePrimaryIdentity(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer)
 {
     IIdentity identity = null;
     if (reader.IsStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString))
     {
         reader.ReadStartElement();
         if (reader.IsStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString))
         {
             SecurityIdentifier sid = ReadSidAttribute(reader, dictionary);
             string authenticationType = reader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyString);
             reader.ReadStartElement();
             string name = reader.ReadContentAsString();
             identity = new WindowsSidIdentity(sid, name, authenticationType ?? String.Empty);
             reader.ReadEndElement();
         }
         else if (reader.IsStartElement(dictionary.GenericIdentity, dictionary.EmptyString))
         {
             string authenticationType = reader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyString);
             reader.ReadStartElement();
             string name = reader.ReadContentAsString();
             identity = SecurityUtils.CreateIdentity(name, authenticationType ?? String.Empty);
             reader.ReadEndElement();
         }
         else
         {
             identity = (IIdentity)serializer.ReadObject(reader);
         }
         reader.ReadEndElement();
     }
     return identity;
 }
        internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type)
#endif
        {
            throw /*System.Runtime.Serialization.*/ DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type))));
        }
Beispiel #31
0
		object ReadHeaderObject (Type type, XmlObjectSerializer serializer, XmlDictionaryReader reader)
		{
			// FIXME: it's a nasty workaround just to avoid UniqueId output as a string.
			// Seealso MessageHeader.DefaultMessageHeader.OnWriteHeaderContents().
			// Note that msg.Headers.GetHeader<UniqueId> () simply fails (on .NET too) and it is useless. The API is lame by design.
			if (type == typeof (UniqueId))
				return new UniqueId (reader.ReadElementContentAsString ());
			else
				return serializer.ReadObject (reader);
		}
        internal static void ThrowArrayExceededSizeException(int arraySize, Type type)
#endif
        {
            throw /*System.Runtime.Serialization.*/ DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type))));
        }
Beispiel #33
0
 private void ThrowConversionException(string value, string type)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, type))));
 }
 public XmlWriterDelegator(XmlWriter writer)
 {
     XmlObjectSerializer.CheckNull(writer, nameof(writer));
     this.writer           = writer;
     this.dictionaryWriter = writer as XmlDictionaryWriter;
 }
Beispiel #35
0
 public override void Close()
 {
     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableIllegalOperation)));
 }
Beispiel #36
0
        internal void Add(string id, object obj)
        {
            if (_objectDictionary == null)
            {
                _objectDictionary = new Dictionary <string, object>();
            }

            object existingObject;

            if (_objectDictionary.TryGetValue(id, out existingObject))
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.MultipleIdDefinition, id)));
            }
            _objectDictionary.Add(id, obj);
        }
Beispiel #37
0
 internal void EndWrite()
 {
     if (_depth != 0)
     {
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableMissingEndElements, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType())))));
     }
     _obj = null;
 }
Beispiel #38
0
 private void ReadRef(XmlReaderDelegator reader)
 {
     Ref = reader.ReadContentAsString();
     if (string.IsNullOrEmpty(Ref))
     {
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidXsRefDefinition, Ref)));
     }
 }
Beispiel #39
0
 private void ReadArraySize(XmlReaderDelegator reader)
 {
     ArraySZSize = reader.ReadContentAsInt();
     if (ArraySZSize < 0)
     {
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidSizeDefinition, ArraySZSize)));
     }
 }
Beispiel #40
0
			internal DefaultMessageHeader (string name, string ns, object value, XmlObjectSerializer formatter, 
						       bool isReferenceParameter,
						       bool mustUnderstand, string actor, bool relay)
			{
				this.name = name;
				this.ns = ns;
				this.value = value;
				this.formatter = formatter;
				this.is_ref = isReferenceParameter;
				this.must_understand = mustUnderstand;
				this.actor = actor;
				this.relay = relay;
			}
        public static Claim DeserializeClaim(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer)
        {
            if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return null;
            }
            else if (reader.IsStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] sidBytes = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Sid, new SecurityIdentifier(sidBytes, 0), right);
            }
            else if (reader.IsStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] sidBytes = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.DenyOnlySid, new SecurityIdentifier(sidBytes, 0), right);
            }
            else if (reader.IsStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] rawData = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.X500DistinguishedName, new X500DistinguishedName(rawData), right);
            }
            else if (reader.IsStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] thumbprint = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Thumbprint, thumbprint, right);
            }
            else if (reader.IsStartElement(dictionary.NameClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string name = reader.ReadString();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Name, name, right);
            }
            else if (reader.IsStartElement(dictionary.DnsClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string dns = reader.ReadString();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Dns, dns, right);
            }
            else if (reader.IsStartElement(dictionary.RsaClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string rsaXml = reader.ReadString();
                reader.ReadEndElement();

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.FromXmlString(rsaXml);
                return new Claim(ClaimTypes.Rsa, rsa, right);
            }
            else if (reader.IsStartElement(dictionary.MailAddressClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string address = reader.ReadString();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Email, new System.Net.Mail.MailAddress(address), right);
            }
            else if (reader.IsStartElement(dictionary.SystemClaim, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return Claim.System;
            }
            else if (reader.IsStartElement(dictionary.HashClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] hash = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Hash, hash, right);
            }
            else if (reader.IsStartElement(dictionary.SpnClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string spn = reader.ReadString();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Spn, spn, right);
            }
            else if (reader.IsStartElement(dictionary.UpnClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string upn = reader.ReadString();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Upn, upn, right);
            }
            else if (reader.IsStartElement(dictionary.UrlClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string url = reader.ReadString();
                reader.ReadEndElement();
                return new Claim(ClaimTypes.Uri, new Uri(url), right);
            }
            else
            {
                return (Claim)serializer.ReadObject(reader);
            }
        }
Beispiel #42
0
		public static MessageHeader CreateHeader (string name, string ns, object value, XmlObjectSerializer formatter,
						   bool must_understand, string actor, bool relay)
		{
			// FIXME: how to get IsReferenceParameter ?
			return new DefaultMessageHeader (name, ns, value, formatter, default_is_ref, must_understand, actor, relay);
		}
 public static void SerializeIdentities(AuthorizationContext authContext, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer)
 {
     object obj;
     IList<IIdentity> identities;
     if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
     {
         identities = obj as IList<IIdentity>;
         if (identities != null && identities.Count > 0)
         {
             writer.WriteStartElement(dictionary.Identities, dictionary.EmptyString);
             for (int i = 0; i < identities.Count; ++i)
             {
                 SerializePrimaryIdentity(identities[i], dictionary, writer, serializer);
             }
             writer.WriteEndElement();
         }
     }
 }
Beispiel #44
0
        private int FindElement(object obj, out bool isEmpty, out bool isWrapped)
        {
            isWrapped = false;
            int position = ComputeStartPosition(obj);

            for (int i = position; i != (position - 1); i++)
            {
                if (m_objs[i] == null)
                {
                    isEmpty = true;
                    return(i);
                }
                if (m_objs[i] == obj)
                {
                    isEmpty = false;
                    return(i);
                }
                if (i == (m_objs.Length - 1))
                {
                    isWrapped = true;
                    i         = -1;
                }
            }
            // m_obj must ALWAYS have at least one slot empty (null).
            DiagnosticUtility.DebugAssert("Object table overflow");
            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ObjectTableOverflow)));
        }
 public static IList<IIdentity> DeserializeIdentities(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer)
 {
     List<IIdentity> identities = null;
     if (reader.IsStartElement(dictionary.Identities, dictionary.EmptyString))
     {
         identities = new List<IIdentity>();
         reader.ReadStartElement();
         while (reader.IsStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString))
         {
             IIdentity identity = DeserializePrimaryIdentity(reader, dictionary, serializer);
             if (identity != null && identity != SecurityUtils.AnonymousIdentity)
             {
                 identities.Add(identity);
             }
         }
         reader.ReadEndElement();
     }
     return identities;
 }
Beispiel #46
0
        object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
        {
            object retObj = null;

            if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
            {
                return(retObj);
            }

            DataContract dataContract;
            string       assemblyName = attributes.ClrAssembly;
            string       typeName     = attributes.ClrType;

            if (assemblyName != null && typeName != null)
            {
                Assembly assembly;
                Type     type;
                dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
                if (dataContract == null)
                {
                    if (assembly == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.AssemblyNotFound, assemblyName)));
                    }
                    if (type == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ClrTypeNotFound, assembly.FullName, typeName)));
                    }
                }
                //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
                if (declaredType != null && declaredType.IsArray)
                {
                    dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
                }
            }
            else
            {
                if (assemblyName != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))));
                }
                else if (typeName != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))));
                }
                else if (declaredType == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))));
                }
                dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
            }
            return(ReadDataContractValue(dataContract, xmlReader));
        }
 public static void SerializeClaim(Claim claim, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer)
 {
     // the order in which known claim types are checked is optimized for use patterns
     if (claim == null)
     {
         writer.WriteElementString(dictionary.NullValue, dictionary.EmptyString, string.Empty);
         return;
     }
     else if (ClaimTypes.Sid.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         SerializeSid((SecurityIdentifier)claim.Resource, dictionary, writer);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.DenyOnlySid.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         SerializeSid((SecurityIdentifier)claim.Resource, dictionary, writer);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.X500DistinguishedName.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         byte[] rawData = ((X500DistinguishedName)claim.Resource).RawData;
         writer.WriteBase64(rawData, 0, rawData.Length);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Thumbprint.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         byte[] thumbprint = (byte[])claim.Resource;
         writer.WriteBase64(thumbprint, 0, thumbprint.Length);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Name.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.NameClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString((string)claim.Resource);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Dns.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.DnsClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString((string)claim.Resource);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Rsa.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.RsaClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString(((RSA)claim.Resource).ToXmlString(false));
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Email.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.MailAddressClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString(((MailAddress)claim.Resource).Address);
         writer.WriteEndElement();
         return;
     }
     else if (claim == Claim.System)
     {
         writer.WriteElementString(dictionary.SystemClaim, dictionary.EmptyString, string.Empty);
         return;
     }
     else if (ClaimTypes.Hash.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.HashClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         byte[] hash = (byte[])claim.Resource;
         writer.WriteBase64(hash, 0, hash.Length);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Spn.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.SpnClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString((string)claim.Resource);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Upn.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.UpnClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString((string)claim.Resource);
         writer.WriteEndElement();
         return;
     }
     else if (ClaimTypes.Uri.Equals(claim.ClaimType))
     {
         writer.WriteStartElement(dictionary.UrlClaim, dictionary.EmptyString);
         WriteRightAttribute(claim, dictionary, writer);
         writer.WriteString(((Uri)claim.Resource).AbsoluteUri);
         writer.WriteEndElement();
         return;
     }
     else
     {
         // this is an extensible claim... need to delegate to xml object serializer
         serializer.WriteObject(writer, claim);
     }
 }
Beispiel #48
0
        private void RemoveAt(int position)
        {
            int cacheSize          = m_objs.Length;
            int lastVacantPosition = position;

            for (int next = (position == cacheSize - 1) ? 0 : position + 1; next != position; next++)
            {
                if (m_objs[next] == null)
                {
                    m_objs[lastVacantPosition]      = null;
                    m_ids[lastVacantPosition]       = 0;
                    m_isWrapped[lastVacantPosition] = false;
                    return;
                }
                int nextStartPosition = ComputeStartPosition(m_objs[next]);
                // If we wrapped while placing an object, then it must be that the start position wasn't wrapped to begin with
                bool isNextStartPositionWrapped  = next < position && !m_isWrapped[next];
                bool isLastVacantPositionWrapped = lastVacantPosition < position;

                // We want to avoid moving objects in the cache if the next bucket position is wrapped, but the last vacant position isn't
                // and we want to make sure to move objects in the cache when the last vacant position is wrapped but the next bucket position isn't
                if ((nextStartPosition <= lastVacantPosition && !(isNextStartPositionWrapped && !isLastVacantPositionWrapped)) ||
                    (isLastVacantPositionWrapped && !isNextStartPositionWrapped))
                {
                    m_objs[lastVacantPosition] = m_objs[next];
                    m_ids[lastVacantPosition]  = m_ids[next];
                    // A wrapped object might become unwrapped if it moves from the front of the array to the end of the array
                    m_isWrapped[lastVacantPosition] = m_isWrapped[next] && next > lastVacantPosition;
                    lastVacantPosition = next;
                }
                if (next == (cacheSize - 1))
                {
                    next = -1;
                }
            }
            // m_obj must ALWAYS have at least one slot empty (null).
            DiagnosticUtility.DebugAssert("Object table overflow");
            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ObjectTableOverflow)));
        }
 public static XmlSyndicationContent CreateXmlContent(object dataContractObject, XmlObjectSerializer dataContractSerializer)
 {
     return new XmlSyndicationContent(Atom10Constants.XmlMediaType, dataContractObject, dataContractSerializer);
 }
Beispiel #50
0
 private void ReadId(XmlReaderDelegator reader)
 {
     Id = reader.ReadContentAsString();
     if (string.IsNullOrEmpty(Id))
     {
         throw /*System.Runtime.Serialization.*/ DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.InvalidXsIdDefinition, Id)));
     }
 }
        protected object?InternalDeserialize(XmlReaderDelegator reader, string?name, string?ns, Type declaredType, ref DataContract dataContract)
        {
            object?retObj = null;

            if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj))
            {
                return(retObj);
            }

            bool knownTypesAddedInCurrentScope = false;

            if (dataContract.KnownDataContracts != null)
            {
                scopedKnownTypes.Push(dataContract.KnownDataContracts);
                knownTypesAddedInCurrentScope = true;
            }

            Debug.Assert(attributes != null);

            if (attributes.XsiTypeName != null)
            {
                DataContract?tempDataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType);
                if (tempDataContract == null)
                {
                    if (DataContractResolver == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName))));
                    }
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName))));
                }
                dataContract = tempDataContract;
                knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope);
            }

            if (dataContract.IsISerializable && attributes.FactoryTypeName != null)
            {
                DataContract?factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType);
                if (factoryDataContract != null)
                {
                    if (factoryDataContract.IsISerializable)
                    {
                        dataContract = factoryDataContract;
                        knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryTypeNotISerializable, DataContract.GetClrTypeFullName(factoryDataContract.UnderlyingType), DataContract.GetClrTypeFullName(dataContract.UnderlyingType))));
                    }
                }
            }

            if (knownTypesAddedInCurrentScope)
            {
                object?obj = ReadDataContractValue(dataContract, reader);
                scopedKnownTypes.Pop();
                return(obj);
            }
            else
            {
                return(ReadDataContractValue(dataContract, reader));
            }
        }
 protected virtual void WriteNull(XmlWriterDelegator xmlWriter)
 {
     XmlObjectSerializer.WriteNull(xmlWriter);
 }
        public static XmlNode[] ReadNodes(XmlReader xmlReader)
        {
            if (xmlReader == null)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlReader");
            }
            XmlDocument    doc      = new XmlDocument();
            List <XmlNode> nodeList = new List <XmlNode>();

            if (xmlReader.MoveToFirstAttribute())
            {
                do
                {
                    if (IsValidAttribute(xmlReader))
                    {
                        XmlNode node = doc.ReadNode(xmlReader);
                        if (node == null)
                        {
                            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.UnexpectedEndOfFile)));
                        }
                        nodeList.Add(node);
                    }
                } while (xmlReader.MoveToNextAttribute());
            }
            xmlReader.MoveToElement();
            if (!xmlReader.IsEmptyElement)
            {
                int startDepth = xmlReader.Depth;
                xmlReader.Read();
                while (xmlReader.Depth > startDepth && xmlReader.NodeType != XmlNodeType.EndElement)
                {
                    XmlNode node = doc.ReadNode(xmlReader);
                    if (node == null)
                    {
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.UnexpectedEndOfFile)));
                    }
                    nodeList.Add(node);
                }
            }
            return(nodeList.ToArray());
        }
Beispiel #54
0
 public XmlReaderDelegator(XmlReader reader)
 {
     XmlObjectSerializer.CheckNull(reader, "reader");
     this.reader           = reader;
     this.dictionaryReader = reader as XmlDictionaryReader;
 }
Beispiel #55
0
		public static MessageHeader CreateHeader (string name, string ns, object value, XmlObjectSerializer formatter,
						   bool must_understand, string actor)
		{
			return CreateHeader (name, ns, value, formatter, must_understand, actor, default_relay);
		}
Beispiel #56
0
        internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
        {
            if (MaxItemsInObjectGraph == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
            }

            DataContract contract     = RootContract;
            Type         declaredType = contract.UnderlyingType;
            Type         graphType    = (graph == null) ? declaredType : graph.GetType();

            if (_serializationSurrogateProvider != null)
            {
                graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType);
            }

            if (dataContractResolver == null)
            {
                dataContractResolver = this.DataContractResolver;
            }

            if (graph == null)
            {
                if (IsRootXmlAny(_rootName, contract))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeNull, declaredType)));
                }
                WriteNull(writer);
            }
            else
            {
                if (declaredType == graphType)
                {
                    if (contract.CanContainReferences)
                    {
                        XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract
                                                                                                                , dataContractResolver
                                                                                                                );
                        context.HandleGraphAtTopLevel(writer, graph, contract);
                        context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
                    }
                    else
                    {
                        contract.WriteXmlValue(writer, graph, null);
                    }
                }
                else
                {
                    XmlObjectSerializerWriteContext context = null;
                    if (IsRootXmlAny(_rootName, contract))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType)));
                    }

                    contract = GetDataContract(contract, declaredType, graphType);
                    context  = XmlObjectSerializerWriteContext.CreateContext(this, RootContract
                                                                             , dataContractResolver
                                                                             );
                    if (contract.CanContainReferences)
                    {
                        context.HandleGraphAtTopLevel(writer, graph, contract);
                    }
                    context.OnHandleIsReference(writer, contract, graph);
                    context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
                }
            }
        }
 public SingleParameterBodyWriter(object body, XmlObjectSerializer serializer)
     : base(false)
 {
     if (body != null && serializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
     }
     this.body = body;
     this.serializer = serializer;
 }
 internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
     : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
 {
 }
        public static void Serialize(object instance, out string xmlContent, out string serializerType)
        {
            SerializerTypes serializerTypeValue = SerializerTypes.Primitive;
            xmlContent = string.Empty;
            Type instanceType = typeof(object);
            if (instance != null)
            {
                if (instanceType.IsPrimitive || instanceType == typeof(string))
                {
                    xmlContent = string.Format("<{0}>{1}</{0}>", instanceType.Name, instance);
                }
                else if (instanceType.GetCustomAttributes(typeof(SerializableAttribute), true).FirstOrDefault() != null)
                {
                    serializerTypeValue = SerializerTypes.XmlSerializer;
                    StringWriter sww = new StringWriter();
                    XmlWriter writer = XmlWriter.Create(sww);
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(instanceType);
                    serializer.Serialize(sww, instanceType);
                    xmlContent = sww.ToString();
                }
                else
                {
                    serializerTypeValue = SerializerTypes.XmlObjectSerializer;
                    XmlObjectSerializer serializer = new XmlObjectSerializer();
                    xmlContent = serializer.Serialize(instance, instanceType).OuterXml;
                }
            }

            serializerType = string.Format(SerializerTypeFormat, serializerTypeValue, instanceType.AssemblyQualifiedName);
        }
 internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
     : this(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject, null)
 {
 }