public static void XmlBaseWriter_WriteStartEndElementAsync()
    {
        string actual;
        int byteSize = 1024;
        byte[] bytes = GetByteArray(byteSize);
        string expect = GetExpectString(bytes, byteSize);
        using (var ms = new AsyncMemoryStream())
        {
            var writer = XmlDictionaryWriter.CreateTextWriter(ms);
            writer.WriteStartDocument();
            // NOTE: the async method has only one overload that takes 3 params
            var t1 = writer.WriteStartElementAsync(null, "data", null);
            t1.Wait();
            writer.WriteBase64(bytes, 0, byteSize);
            var t2 = writer.WriteEndElementAsync();
            t2.Wait();
            writer.WriteEndDocument();
            writer.Flush();
            ms.Position = 0;
            var sr = new StreamReader(ms);
            actual = sr.ReadToEnd();
        }

        Assert.StrictEqual(expect, actual);
    }
示例#2
0
    public static void XmlBaseWriter_FlushAsync()
    {
        string actual;
        int    byteSize = 1024;

        byte[] bytes  = GetByteArray(byteSize);
        string expect = GetExpectString(bytes, byteSize);

        using (var ms = new AsyncMemoryStream())
        {
            var writer = XmlDictionaryWriter.CreateTextWriter(ms);
            writer.WriteStartDocument();
            writer.WriteStartElement("data");
            writer.WriteBase64(bytes, 0, byteSize);
            writer.WriteEndElement();
            writer.WriteEndDocument();
            var task = writer.FlushAsync();
            task.Wait();
            ms.Position = 0;
            var sr = new StreamReader(ms);
            actual = sr.ReadToEnd();
        }

        Assert.StrictEqual(expect, actual);
    }
    public static void CreateTextReaderWriterTest()
    {
        string expected = "<localName>the value</localName>";
        using (MemoryStream stream = new MemoryStream())
        {
            using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false))
            {
                writer.WriteElementString("localName", "the value");
                writer.Flush();
                byte[] bytes = stream.ToArray();
                StreamReader reader = new StreamReader(stream);
                stream.Position = 0;
                string content = reader.ReadToEnd();
                Assert.Equal(expected, content);
                reader.Close();

                using (XmlDictionaryReader xreader = XmlDictionaryReader.CreateTextReader(bytes, new XmlDictionaryReaderQuotas()))
                {
                    xreader.Read();
                    string xml = xreader.ReadOuterXml();
                    Assert.Equal(expected, xml);
                }
            }
        }
    }
示例#4
0
        private static Stream ToStream <T>(T item)
        {
            var ds = new DataContractSerializer(typeof(T));

            MemoryStream stream = null;

            try
            {
                stream = new MemoryStream();

                using (WrapperStream wrapperStream = new WrapperStream(stream, true))
                    using (XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(wrapperStream, new UTF8Encoding(false)))
                    {
                        ds.WriteObject(xmlDictionaryWriter, item);
                    }
            }
            catch (Exception)
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return(stream);
        }
示例#5
0
        private void Serialize(string path)
        {
            FileStream someStream = new FileStream(path, FileMode.Open);

            //<snippet8>
            Person p = new Person();
            DataContractSerializer dcs =
                new DataContractSerializer(typeof(Person));
            XmlDictionaryWriter xdw =
                XmlDictionaryWriter.CreateTextWriter(someStream, Encoding.UTF8);

            dcs.WriteObject(xdw, p);
            //</snippet8>

            //<snippet9>
            dcs.WriteStartObject(xdw, p);
            xdw.WriteAttributeString("serializedBy", "myCode");
            dcs.WriteObjectContent(xdw, p);
            dcs.WriteEndObject(xdw);
            //</snippet9>

            //<snippet10>
            xdw.WriteStartElement("MyCustomWrapper");
            dcs.WriteObjectContent(xdw, p);
            xdw.WriteEndElement();
            //</snippet10>
        }
示例#6
0
        public virtual Task WriteMessageAsync(Message message, Stream stream)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            ThrowIfMismatchedMessageVersion(message);

            XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateTextWriter(stream, _writeEncoding, false);

            if (_optimizeWriteForUtf8)
            {
                message.WriteMessage(xmlWriter);
            }
            else
            {
                xmlWriter.WriteStartDocument();
                message.WriteMessage(xmlWriter);
                xmlWriter.WriteEndDocument();
            }

            xmlWriter.Flush();

            xmlWriter.Dispose();

            return(Task.CompletedTask);
        }
示例#7
0
        private static void WriteTraceData(TraceEventType eventType, int id, string traceIdentifier, string description, string methodName, Exception exception)
        {
            if (source.Switch.ShouldTrace(eventType))
            {
                MemoryStream        strm   = new MemoryStream();
                XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(strm);
                writer.WriteStartElement(TraceRecordName);
                writer.WriteAttributeString("xmlns", TraceRecordNs);
                writer.WriteElementString("TraceIdentifier", traceIdentifier);
                writer.WriteElementString("Description", description);
                writer.WriteElementString("AppDomain", AppDomain.CurrentDomain.FriendlyName);
                writer.WriteElementString("MethodName", methodName);
                writer.WriteElementString("Source", TraceHelper.TraceSourceName);
                if (exception != null)
                {
                    WriteException(writer, exception);
                }
                writer.WriteEndElement();
                writer.Flush();
                strm.Position = 0;
                XPathDocument doc = new XPathDocument(strm);

                source.TraceData(eventType, id, doc.CreateNavigator());
                writer.Close();
                strm.Close();
            }
        }
示例#8
0
        XmlElement CreateXmlTokenElement(SecurityToken token, string prefix, string name, string ns, string usage)
        {
            Stream stream = new MemoryStream();

            using (XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false))
            {
                xmlWriter.WriteStartElement(prefix, name, ns);
                WriteToken(xmlWriter, token, usage);
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
            }

            stream.Seek(0, SeekOrigin.Begin);

            XmlDocument dom = new XmlDocument();

            dom.PreserveWhitespace = true;
            dom.Load(new XmlTextReader(stream)
            {
                DtdProcessing = DtdProcessing.Prohibit
            });
            stream.Close();

            return(dom.DocumentElement);
        }
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            _communicationObject.ThrowIfClosedOrNotOpen();
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    try
                    {
                        channel.Open();
                        Message reply = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                        SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                        trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                        CacheSecurityTokenResponse(request, trustResponse);
                    }
                    finally
                    {
                        channel.Close();
                    }
                }
            }

            return(CreateGenericXmlSecurityToken(request, trustResponse));
        }
示例#10
0
        public static XmlWriter CreateXmlWriter(ReaderWriterType rwType, Stream stream, Encoding encoding, IXmlDictionary dictionary)
        {
            XmlWriter result = null;

            switch (rwType)
            {
            case ReaderWriterType.Binary:
                result = XmlDictionaryWriter.CreateBinaryWriter(stream, dictionary);
                break;

            case ReaderWriterType.Text:
                result = XmlDictionaryWriter.CreateTextWriter(stream, encoding);
                break;

            case ReaderWriterType.WebData:
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = encoding;
                result            = XmlWriter.Create(stream, settings);
                break;

            case ReaderWriterType.WrappedWebData:
                XmlWriterSettings settings2 = new XmlWriterSettings();
                settings2.Encoding = encoding;
                result             = XmlWriter.Create(stream, settings2);
                result             = XmlDictionaryWriter.CreateDictionaryWriter(result);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(rwType));
            }

            return(result);
        }
示例#11
0
        /// <summary>
        /// Adds the specified facts into the internal collection by serializing these using DataContractSerializer.
        /// </summary>
        /// <param name="facts">A collection of facts.</param>
        public void AddFacts(IEnumerable <object> facts)
        {
            Guard.ArgumentNotNull(facts, "facts");

            foreach (object fact in facts)
            {
                var dcAttribute = FrameworkUtility.GetDeclarativeAttribute <DataContractAttribute>(fact);

                if (dcAttribute != null)
                {
                    DataContractSerializer serializer = !String.IsNullOrEmpty(dcAttribute.Name) && !String.IsNullOrEmpty(dcAttribute.Namespace) ? new DataContractSerializer(fact.GetType(), dcAttribute.Name, dcAttribute.Namespace) : new DataContractSerializer(fact.GetType());

                    using (MemoryStream serializationBuffer = new MemoryStream())
                    {
                        using (var xmlWriter = XmlDictionaryWriter.CreateTextWriter(serializationBuffer, Encoding.UTF8, false))
                        {
                            serializer.WriteObject(xmlWriter, fact);
                        }

                        serializationBuffer.Seek(0, SeekOrigin.Begin);

                        using (StreamReader dataReader = new StreamReader(serializationBuffer))
                        {
                            this.facts[fact.GetType().AssemblyQualifiedName] = dataReader.ReadToEnd();
                        }
                    }
                }
                else
                {
                    throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.MustSupplyDataContractAttribute, fact.GetType().FullName));
                }
            }
        }
示例#12
0
        public void WriteBodyToEncryptThenSign(Stream canonicalStream, EncryptedData encryptedData, SymmetricAlgorithm algorithm)
        {
            encryptedData.Id = this.securityHeader.GenerateId();
            this.SetBodyId();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null);

            writer.WriteStartElement("a");
            MemoryStream stream = new MemoryStream();

            ((IFragmentCapableXmlDictionaryWriter)writer).StartFragment(stream, true);
            base.InnerMessage.WriteBodyContents(writer);
            ((IFragmentCapableXmlDictionaryWriter)writer).EndFragment();
            writer.WriteEndElement();
            stream.Flush();
            encryptedData.SetUpEncryption(algorithm, new ArraySegment <byte>(stream.GetBuffer(), 0, (int)stream.Length));
            this.fullBodyBuffer = new XmlBuffer(0x7fffffff);
            XmlDictionaryWriter writer2 = this.fullBodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max);

            writer2.StartCanonicalization(canonicalStream, false, null);
            this.WriteStartInnerMessageWithId(writer2);
            encryptedData.WriteTo(writer2, ServiceModelDictionaryManager.Instance);
            writer2.WriteEndElement();
            writer2.EndCanonicalization();
            writer2.Flush();
            this.fullBodyBuffer.CloseSection();
            this.fullBodyBuffer.Close();
            this.state = BodyState.EncryptedThenSigned;
        }
        public static void WriteObjectData(string path)
        {
            // Create the object to serialize.
            Person p = new Person("Lynn", "Tsoflias", 9876);

            // Create the writer.
            FileStream fs = new FileStream(path, FileMode.Create);
            XmlDictionaryWriter writer =
                XmlDictionaryWriter.CreateTextWriter(fs);

            NetDataContractSerializer ser =
                new NetDataContractSerializer();

            // Use the writer to start a document.
            writer.WriteStartDocument(true);

            // Use the serializer to write the start of the 
            // object data. Use it again to write the object
            // data. 
            ser.WriteStartObject(writer, p);
            ser.WriteObjectContent(writer, p);

            // Use the serializer to write the end of the 
            // object data. Then use the writer to write the end
            // of the document.
            ser.WriteEndObject(writer);
            writer.WriteEndDocument();

            Console.WriteLine("Done");

            // Close and release the writer resources.
            writer.Flush();
            fs.Flush();
            fs.Close();
        }
        public void WriteTo(Stream canonicalStream)
        {
            if (this.reader != null)
            {
                XmlDictionaryReader dicReader = this.reader as XmlDictionaryReader;
                if ((dicReader != null) && (dicReader.CanCanonicalize))
                {
                    dicReader.MoveToContent();
                    dicReader.StartCanonicalization(canonicalStream, this.includeComments, this.inclusivePrefixes);
                    dicReader.Skip();
                    dicReader.EndCanonicalization();
                }
                else
                {
                    XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null);
                    if (this.inclusivePrefixes != null)
                    {
                        // Add a dummy element at the top and populate the namespace
                        // declaration of all the inclusive prefixes.
                        writer.WriteStartElement("a", reader.LookupNamespace(String.Empty));
                        for (int i = 0; i < this.inclusivePrefixes.Length; ++i)
                        {
                            string ns = reader.LookupNamespace(this.inclusivePrefixes[i]);
                            if (ns != null)
                            {
                                writer.WriteXmlnsAttribute(this.inclusivePrefixes[i], ns);
                            }
                        }
                    }
                    writer.StartCanonicalization(canonicalStream, this.includeComments, this.inclusivePrefixes);
                    if (reader is WrappedReader)
                    {
                        ((WrappedReader)reader).XmlTokens.GetWriter().WriteTo(writer, new DictionaryManager());
                    }
                    else
                    {
                        writer.WriteNode(reader, false);
                    }
                    writer.Flush();
                    writer.EndCanonicalization();

                    if (this.inclusivePrefixes != null)
                    {
                        writer.WriteEndElement();
                    }

                    writer.Close();
                }
                if (this.closeReadersAfterProcessing)
                {
                    this.reader.Close();
                }
                this.reader = null;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoInputIsSetForCanonicalization)));
            }
        }
示例#15
0
        public void save(Stream s)
        {
            XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(s, Encoding.UTF8);

            xdw.WriteStartDocument();
            dcs.WriteObject(xdw, this);
            xdw.Close();
        }
 public SqlValueSerializerCsvWithXmlDictionaryWriter(Encoding p_Encoding) : base(p_Encoding)
 {
     _StreamXml           = new MemoryStream();
     _XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(_StreamXml, p_Encoding, false);
     _EndLineBuffer       = Encoding.UTF8.GetBytes(RowSplitter.ToString());
     _SplitterBuffer      = Encoding.UTF8.GetBytes(ColumnSplitter.ToString());
     _Buffer = new byte[0];
 }
示例#17
0
 private static void SerializeDataContractXml <T>(T instance, Stream stream)
 {
     using (var writer = XmlDictionaryWriter.CreateTextWriter(stream, new UTF8Encoding(), false))
     {
         var serializer = new DataContractSerializer(typeof(T));
         serializer.WriteObject(writer, instance);
     }
 }
示例#18
0
        public virtual void WriteObject(Stream stream, object graph)
        {
            CheckNull(stream, "stream");
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/);

            WriteObject(writer, graph);
            writer.Flush();
        }
示例#19
0
        public virtual void WriteObject(Stream stream, object graph)
        {
            stream = stream ?? throw new ArgumentNullException(nameof(stream));
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream: stream, encoding: Encoding.UTF8, ownsStream: false);

            WriteObject(writer, graph);
            writer.Flush();
        }
        private static void AddToDigest(SspiNegotiationTokenAuthenticatorState sspiState, RequestSecurityToken rst)
        {
            MemoryStream        stream = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);

            rst.RequestSecurityTokenXml.WriteTo(writer);
            writer.Flush();
            AddToDigest(sspiState.NegotiationDigest, stream);
        }
示例#21
0
        public static void C14NWriterNegativeTests()
        {
            const string TestTypeNullStream = "Null Stream";
            const string TestTypeNullElementInIncludePrefixes = "Null element in IncludePrefixes";

            TestCase tc = TestConfigHelper.GetTest("C14NWriterNegativeTests");

            foreach (var input in tc.Inputs)
            {
                string testType = input.Arguments[0].Value;
                if (testType == TestTypeNullStream)
                {
                    try
                    {
                        //creating XmlC14NWriter with a null stream;
                        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null);
                        writer.StartCanonicalization(null, true, new string[] { "p1", "p2" });
                        Assert.False(true, "Error, creating XmlC14NWriter with a null stream should have thrown!");
                    }
                    catch (Exception ex)
                    {
                        //System.ArgumentNullException: {{ResLookup:;Value cannot be null.;ManagedString;mscorlib.dll;mscorlib;ArgumentNull_Generic}}
                        Assert.Equal(input.Arguments[1].Value, ex.GetType().FullName);
                    }
                }
                else if (testType == TestTypeNullElementInIncludePrefixes)
                {
                    MemoryStream        ms1    = new MemoryStream();
                    MemoryStream        ms2    = new MemoryStream();
                    XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms1);
                    try
                    {
                        //Creating the C14N writer with null elements in the IncludePrefixes array;
                        writer.WriteStartElement("p2", "Root", "http://namespace");
                        //Starting the canonicalization;
                        writer.StartCanonicalization(ms2, true, new string[] { "p1", null, "p2" });
                        //Writing the first element in the C14N writer;
                        writer.WriteStartElement("Wee");
                        //Writing some content to finish the start element. Last chance for it to throw
                        writer.WriteQualifiedName("foo", "http://namespace");
                        writer.WriteEndElement();
                        writer.EndCanonicalization();
                        writer.WriteEndElement();
                        Assert.False(true, "Error, creating XmlC14NWriter with null elements in include prefixes should have thrown!");
                    }
                    catch (Exception ex)
                    {
                        //System.ArgumentException: {{ResLookup:;The inclusive namespace prefix collection cannot contain null as one of the items.;ManagedString;System.Runtime.Serialization.dll;System.Runtime.Serialization;InvalidInclusivePrefixListCollection}}
                        Assert.Equal(input.Arguments[1].Value, ex.GetType().FullName);
                    }
                }
                else
                {
                    throw new ArgumentException("Don't know how to run test " + testType);
                }
            }
        }
示例#22
0
        private void WriteJwts(SecurityTokenDescriptor tokenDescriptor, SignatureProvider signatureProvider)
        {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken        jwt          = new JwtSecurityToken(tokenDescriptor.TokenIssuerName, tokenDescriptor.AppliesToAddress, tokenDescriptor.Subject.Claims, tokenDescriptor.Lifetime, tokenDescriptor.SigningCredentials);
            MemoryStream            ms           = new MemoryStream();
            XmlDictionaryWriter     writer       = XmlDictionaryWriter.CreateTextWriter(ms);

            tokenHandler.WriteToken(writer, jwt);
        }
示例#23
0
        private void CreateSamlTokens(SecurityTokenDescriptor tokenDescriptor)
        {
            SamlSecurityTokenHandler samlTokenHandler = new SamlSecurityTokenHandler();
            SamlSecurityToken        token            = samlTokenHandler.CreateToken(tokenDescriptor) as SamlSecurityToken;
            MemoryStream             ms     = new MemoryStream();
            XmlDictionaryWriter      writer = XmlDictionaryWriter.CreateTextWriter(ms);

            samlTokenHandler.WriteToken(writer, token);
        }
示例#24
0
        public void PutData(Message m)
        {
            FileStream          stream = new FileStream("myfile.xml", FileMode.Create);
            XmlDictionaryWriter xdw    =
                XmlDictionaryWriter.CreateTextWriter(stream);

            m.WriteBodyContents(xdw);
            xdw.Flush();
        }
示例#25
0
        public System.IO.MemoryStream ToXml(object o)
        {
            var result = new System.IO.MemoryStream();

            if (o == null)
            {
                return(result);
            }

            using (var writer = XmlDictionaryWriter.CreateTextWriter(result, Encoding.UTF8, false))
            {
                var serializer = serializers[o.GetType()];
                serializer.WriteObject(writer, o);
            }
            result.Seek(0, System.IO.SeekOrigin.Begin);

            if (oldMonoSerializer)
            {
                var xml = new XmlDocument
                {
                    PreserveWhitespace = true
                };
                xml.Load(result);
                result.Close();

                //remove incorrect ns
                foreach (XmlNode entry in xml.SelectNodes("//entry"))
                {
                    var nsattr = entry.Attributes.Cast <XmlAttribute>().FirstOrDefault(a => a.Value == typeof(FileEntry <>).Name);
                    if (nsattr != null)
                    {
                        foreach (XmlAttribute a in entry.Attributes)
                        {
                            if (a.Value.StartsWith(nsattr.LocalName + ":"))
                            {
                                a.Value = a.Value.Substring(nsattr.LocalName.Length + 1);
                            }
                        }
                        entry.Attributes.Remove(nsattr);
                    }
                }

                //http://stackoverflow.com/questions/13483138/mono-does-not-honor-system-runtime-serialization-datamemberattribute-emitdefault
                var nsmanager = new XmlNamespaceManager(xml.NameTable);
                nsmanager.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
                foreach (XmlNode nil in xml.SelectNodes("//*[@i:nil='true']", nsmanager))
                {
                    nil.ParentNode.RemoveChild(nil);
                }

                result = new System.IO.MemoryStream();
                xml.Save(result);
                result.Seek(0, System.IO.SeekOrigin.Begin);
            }

            return(result);
        }
示例#26
0
        public virtual void WriteObject(Stream stream, object?graph)
        {
            ArgumentNullException.ThrowIfNull(stream);

            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/);

            WriteObject(writer, graph);
            writer.Flush();
        }
示例#27
0
        private void WriteObjectWithInstance(XmlObjectSerializer xm, Company graph, string fileName)
        {
            Console.WriteLine(xm.GetType());
            FileStream          fs     = new FileStream(fileName, FileMode.Create);
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);

            xm.WriteObject(writer, graph);
            Console.WriteLine("Done writing {0}", fileName);
        }
        public static string BuildWaSignInMessage(SecurityToken securityToken, SecurityTokenHandler tokenHandler, string tokenType)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var writer = XmlDictionaryWriter.CreateTextWriter(memoryStream, Encoding.UTF8, false))
                {
                    // <RequestSecurityTokenResponse>
                    writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestSecurityTokenResponse, WsTrustConstants_1_3.Namespace);

                    // <Lifetime>
                    writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.Lifetime, WsTrustConstants.Namespaces.WsTrust1_3);

                    writer.WriteElementString(WsUtility.PreferredPrefix, WsUtility.Elements.Created, WsUtility.Namespace, Default.IssueInstantString);
                    writer.WriteElementString(WsUtility.PreferredPrefix, WsUtility.Elements.Expires, WsUtility.Namespace, Default.ExpiresString);

                    // </Lifetime>
                    writer.WriteEndElement();

                    // <AppliesTo>
                    writer.WriteStartElement(WsPolicy.PreferredPrefix, WsPolicy.Elements.AppliesTo, WsPolicy.Namespace);

                    // <EndpointReference>
                    writer.WriteStartElement(WsAddressing.PreferredPrefix, WsAddressing.Elements.EndpointReference, WsAddressing.Namespace);
                    writer.WriteElementString(WsAddressing.PreferredPrefix, WsAddressing.Elements.Address, WsAddressing.Namespace, Default.Audience);

                    // </EndpointReference>
                    writer.WriteEndElement();

                    // </AppliesTo>
                    writer.WriteEndElement();

                    // <RequestedSecurityToken>token</RequestedSecurityToken>
                    writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestedSecurityToken, WsTrustConstants_1_3.Namespace);

                    tokenHandler.WriteToken(writer, securityToken);

                    writer.WriteEndElement();

                    // <TokenType>tokenType</TokenType>
                    writer.WriteElementString(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.TokenType, WsTrustConstants_1_3.Namespace, tokenType);

                    //<RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</RequestType>
                    writer.WriteElementString(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestType, WsTrustConstants_1_3.Namespace, WsTrustConstants_1_3.Actions.Issue);

                    //<KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</KeyType>
                    writer.WriteElementString(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.KeyType, WsTrustConstants_1_3.Namespace, "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey");

                    // </RequestSecurityTokenResponse>
                    writer.WriteEndElement();

                    writer.Flush();
                    var rstr = Encoding.UTF8.GetString(memoryStream.ToArray());

                    return("wa=wsignin1.0&wresult=" + Uri.EscapeDataString(rstr));
                }
            }
        }
        /// <summary>
        /// Makes a WSTrust call to the STS to obtain a <see cref="SecurityToken"/> first checking if the token is available in the cache.
        /// </summary>
        /// <returns>A <see cref="GenericXmlSecurityToken"/>.</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            WsTrustRequest  request       = CreateWsTrustRequest();
            WsTrustResponse trustResponse = GetCachedResponse(request);

            if (trustResponse is null)
            {
                using (var memeoryStream = new MemoryStream())
                {
                    var writer     = XmlDictionaryWriter.CreateTextWriter(memeoryStream, Encoding.UTF8);
                    var serializer = new WsTrustSerializer();
                    serializer.WriteRequest(writer, _requestSerializationContext.TrustVersion, request);
                    writer.Flush();
                    var             reader  = XmlDictionaryReader.CreateTextReader(memeoryStream.ToArray(), XmlDictionaryReaderQuotas.Max);
                    IRequestChannel channel = ChannelFactory.CreateChannel();
                    Message         reply   = channel.Request(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, _requestSerializationContext.TrustActions.IssueRequest, reader));
                    SecurityUtils.ThrowIfNegotiationFault(reply, channel.RemoteAddress);
                    trustResponse = serializer.ReadResponse(reply.GetReaderAtBodyContents());
                    CacheSecurityTokenResponse(request, trustResponse);
                }
            }

            // Create GenericXmlSecurityToken
            // Assumes that token is first and Saml2SecurityToken.
            using (var stream = new MemoryStream())
            {
                RequestSecurityTokenResponse response = trustResponse.RequestSecurityTokenResponseCollection[0];

                // Get attached and unattached references
                GenericXmlSecurityKeyIdentifierClause internalSecurityKeyIdentifierClause = null;
                if (response.AttachedReference != null)
                {
                    internalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.AttachedReference);
                }

                GenericXmlSecurityKeyIdentifierClause externalSecurityKeyIdentifierClause = null;
                if (response.UnattachedReference != null)
                {
                    externalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.UnattachedReference);
                }

                // Get proof token
                IdentityModel.Tokens.SecurityToken proofToken = GetProofToken(request, response);

                // Get lifetime
                DateTime created = response.Lifetime?.Created ?? DateTime.UtcNow;
                DateTime expires = response.Lifetime?.Expires ?? created.AddDays(1);

                return(new GenericXmlSecurityToken(response.RequestedSecurityToken.TokenElement,
                                                   proofToken,
                                                   created,
                                                   expires,
                                                   internalSecurityKeyIdentifierClause,
                                                   externalSecurityKeyIdentifierClause,
                                                   null));
            }
        }
 private void WriteMapToFile(SerializableMapData map, string path)
 {
     using (var fileStream = new FileStream(path, FileMode.Create)) {
         using (var xmlWriter = XmlDictionaryWriter.CreateTextWriter(fileStream)) {
             var serializer = new DataContractSerializer(typeof(SerializableMapData), KnownSerializableTypes);
             serializer.WriteObject(fileStream, map);
         }
     }
 }