Ejemplo n.º 1
0
        public void SerializeDeserializeJson()
        {
            var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
            var message    = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);

            var ms     = new MemoryStream();
            var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.UTF8);

            MessageSerializer.Serialize(this.MessageDescriptions.GetAccessor(message), writer);
            writer.Flush();

            string actual   = Encoding.UTF8.GetString(ms.ToArray());
            string expected = @"{""age"":15,""Name"":""Andrew"",""Location"":""http:\/\/localtest\/path"",""Timestamp"":""2008-09-19T08:00:00Z""}";

            Assert.AreEqual(expected, actual);

            ms.Position = 0;
            var deserialized = new Mocks.TestDirectedMessage();
            var reader       = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);

            MessageSerializer.Deserialize(this.MessageDescriptions.GetAccessor(deserialized), reader);
            Assert.AreEqual(message.Age, deserialized.Age);
            Assert.AreEqual(message.EmptyMember, deserialized.EmptyMember);
            Assert.AreEqual(message.Location, deserialized.Location);
            Assert.AreEqual(message.Name, deserialized.Name);
            Assert.AreEqual(message.Timestamp, deserialized.Timestamp);
        }
Ejemplo n.º 2
0
        public void DeserializeVerifyElementOrdering()
        {
            var serializer = MessageSerializer.Get(typeof(Mocks.TestDerivedMessage));
            Dictionary <string, string> fields = new Dictionary <string, string>(StringComparer.Ordinal);

            // We deliberately do this OUT of order,
            // since DataContractSerializer demands elements to be in
            // 1) inheritance then 2) alphabetical order.
            // Proper xml element order would be: Name, age, Second..., TheFirst...
            fields["TheFirstDerivedElement"] = "first";
            fields["age"]  = "15";
            fields["Name"] = "Andrew";
            fields["SecondDerivedElement"] = "second";
            fields["explicit"]             = "explicitValue";
            fields["private"] = "privateValue";
            var actual = new Mocks.TestDerivedMessage();

            serializer.Deserialize(fields, this.MessageDescriptions.GetAccessor(actual));
            Assert.AreEqual(15, actual.Age);
            Assert.AreEqual("Andrew", actual.Name);
            Assert.AreEqual("first", actual.TheFirstDerivedElement);
            Assert.AreEqual("second", actual.SecondDerivedElement);
            Assert.AreEqual("explicitValue", ((Mocks.IBaseMessageExplicitMembers)actual).ExplicitProperty);
            Assert.AreEqual("privateValue", actual.PrivatePropertyAccessor);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Serializes the <see cref="DataBag"/> instance to a buffer.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>The buffer containing the serialized data.</returns>
        protected override byte[] SerializeCore(T message)
        {
            var    fields = MessageSerializer.Get(message.GetType()).Serialize(MessageDescriptions.GetAccessor(message));
            string value  = MessagingUtilities.CreateQueryString(fields);

            return(Encoding.UTF8.GetBytes(value));
        }
Ejemplo n.º 4
0
        public void DeserializeInvalidMessage()
        {
            IProtocolMessage message = new Mocks.TestDirectedMessage();
            var serializer           = MessageSerializer.Get(message.GetType());
            var fields = GetStandardTestFields(FieldFill.AllRequired);

            fields["age"] = "-1";             // Set an disallowed value.
            serializer.Deserialize(fields, this.MessageDescriptions.GetAccessor(message));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Deserializes the <see cref="DataBag"/> instance from a buffer.
        /// </summary>
        /// <param name="message">The message instance to initialize with data from the buffer.</param>
        /// <param name="data">The data buffer.</param>
        protected override void DeserializeCore(T message, byte[] data)
        {
            string value = Encoding.UTF8.GetString(data);

            // Deserialize into message newly created instance.
            var serializer = MessageSerializer.Get(message.GetType());
            var fields     = MessageDescriptions.GetAccessor(message);

            serializer.Deserialize(HttpUtility.ParseQueryString(value).ToDictionary(), fields);
        }
        /// <summary>
        /// Prepares a message for sending based on the rules of this channel binding element.
        /// </summary>
        /// <param name="message">The message to prepare for sending.</param>
        /// <returns>
        /// True if the <paramref name="message"/> applied to this binding element
        /// and the operation was successful.  False otherwise.
        /// </returns>
        /// <remarks>
        /// Implementations that provide message protection must honor the
        /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
        /// </remarks>
        public bool PrepareMessageForSending(IProtocolMessage message)
        {
            ErrorUtilities.VerifyArgumentNotNull(message, "message");

            var extendableMessage = message as IProtocolMessageWithExtensions;

            if (extendableMessage != null)
            {
                Protocol          protocol = Protocol.Lookup(message.Version);
                MessageDictionary baseMessageDictionary = new MessageDictionary(message);

                // We have a helper class that will do all the heavy-lifting of organizing
                // all the extensions, their aliases, and their parameters.
                var extensionManager = ExtensionArgumentsManager.CreateOutgoingExtensions(protocol);
                foreach (IExtensionMessage protocolExtension in extendableMessage.Extensions)
                {
                    var extension = protocolExtension as IOpenIdMessageExtension;
                    if (extension != null)
                    {
                        // Give extensions that require custom serialization a chance to do their work.
                        var customSerializingExtension = extension as IMessageWithEvents;
                        if (customSerializingExtension != null)
                        {
                            customSerializingExtension.OnSending();
                        }

                        // OpenID 2.0 Section 12 forbids two extensions with the same TypeURI in the same message.
                        ErrorUtilities.VerifyProtocol(!extensionManager.ContainsExtension(extension.TypeUri), OpenIdStrings.ExtensionAlreadyAddedWithSameTypeURI, extension.TypeUri);

                        var extensionDictionary = MessageSerializer.Get(extension.GetType()).Serialize(extension);
                        extensionManager.AddExtensionArguments(extension.TypeUri, extensionDictionary);
                    }
                    else
                    {
                        Logger.WarnFormat("Unexpected extension type {0} did not implement {1}.", protocolExtension.GetType(), typeof(IOpenIdMessageExtension).Name);
                    }
                }

                // We use a cheap trick (for now at least) to determine whether the 'openid.' prefix
                // belongs on the parameters by just looking at what other parameters do.
                // Technically, direct message responses from Provider to Relying Party are the only
                // messages that leave off the 'openid.' prefix.
                bool includeOpenIdPrefix = baseMessageDictionary.Keys.Any(key => key.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal));

                // Add the extension parameters to the base message for transmission.
                extendableMessage.AddExtraParameters(extensionManager.GetArgumentsToSend(includeOpenIdPrefix));
                return(true);
            }

            return(false);
        }
Ejemplo n.º 7
0
        public void ParameterNames()
        {
            this.response.ErrorMessage = "Some Error";
            this.response.Contact      = "Andrew Arnott";
            this.response.Reference    = "http://blog.nerdbank.net/";

            MessageSerializer serializer = MessageSerializer.Get(this.response.GetType());
            var fields = this.MessageDescriptions.GetAccessor(this.response).Serialize();

            Assert.AreEqual(Protocol.OpenId2Namespace, fields["ns"]);
            Assert.AreEqual("Some Error", fields["error"]);
            Assert.AreEqual("Andrew Arnott", fields["contact"]);
            Assert.AreEqual("http://blog.nerdbank.net/", fields["reference"]);
        }
Ejemplo n.º 8
0
        public void DeserializeSimple()
        {
            var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
            Dictionary <string, string> fields = new Dictionary <string, string>(StringComparer.Ordinal);

            fields["Name"]      = "Andrew";
            fields["age"]       = "15";
            fields["Timestamp"] = "1990-01-01T00:00:00";
            var actual = new Mocks.TestDirectedMessage();

            serializer.Deserialize(fields, this.MessageDescriptions.GetAccessor(actual));
            Assert.AreEqual(15, actual.Age);
            Assert.AreEqual("Andrew", actual.Name);
            Assert.AreEqual(DateTime.Parse("1/1/1990"), actual.Timestamp);
            Assert.IsNull(actual.EmptyMember);
        }
        public void ParameterNames()
        {
            this.response.AssociationHandle = "HANDLE";
            this.response.AssociationType   = "HMAC-SHA1";
            this.response.SessionType       = "DH-SHA1";
            this.response.ExpiresIn         = 50;

            MessageSerializer serializer = MessageSerializer.Get(this.response.GetType());
            var fields = this.MessageDescriptions.GetAccessor(this.response).Serialize();

            Assert.AreEqual(Protocol.OpenId2Namespace, fields["ns"]);
            Assert.AreEqual("HANDLE", fields["assoc_handle"]);
            Assert.AreEqual("HMAC-SHA1", fields["assoc_type"]);
            Assert.AreEqual("DH-SHA1", fields["session_type"]);
            Assert.AreEqual("50", fields["expires_in"]);
        }
Ejemplo n.º 10
0
        public void DeserializeWithExtraFields()
        {
            var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
            Dictionary <string, string> fields = new Dictionary <string, string>(StringComparer.Ordinal);

            fields["age"]       = "15";
            fields["Name"]      = "Andrew";
            fields["Timestamp"] = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
            // Add some field that is not recognized by the class.  This simulates a querystring with
            // more parameters than are actually interesting to the protocol message.
            fields["someExtraField"] = "asdf";
            var actual = new Mocks.TestDirectedMessage();

            serializer.Deserialize(fields, this.MessageDescriptions.GetAccessor(actual));
            Assert.AreEqual(15, actual.Age);
            Assert.AreEqual("Andrew", actual.Name);
            Assert.IsNull(actual.EmptyMember);
        }
Ejemplo n.º 11
0
        internal static UnauthorizedTokenRequest CreateTestRequestTokenMessageNoOAuthVersion(MessageDescriptionCollection messageDescriptions, MessageReceivingEndpoint endpoint)
        {
            endpoint = endpoint ?? new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
            var parts = new Dictionary <string, string>();

            parts["oauth_consumer_key"] = "nerdbank.org";
            parts["oauth_timestamp"]    = "1222665749";
            parts["oauth_nonce"]        = "fe4045a3f0efdd1e019fa8f8ae3f5c38";
            parts["scope"] = "http://www.google.com/m8/feeds/";
            parts["oauth_signature_method"] = "HMAC-SHA1";
            parts["oauth_signature"]        = "anything non-empty";

            UnauthorizedTokenRequest message    = new UnauthorizedTokenRequest(endpoint, Protocol.V10.Version);
            MessageDictionary        dictionary = messageDescriptions.GetAccessor(message);

            MessageSerializer.Get(typeof(UnauthorizedTokenRequest)).Deserialize(parts, dictionary);

            return(message);
        }
Ejemplo n.º 12
0
        public void SerializeTest()
        {
            var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
            var message    = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
            var expected   = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
            IDictionary <string, string> actual = serializer.Serialize(this.MessageDescriptions.GetAccessor(message));

            Assert.AreEqual(4, actual.Count);

            // Test case sensitivity of generated dictionary
            Assert.IsFalse(actual.ContainsKey("Age"));
            Assert.IsTrue(actual.ContainsKey("age"));

            // Test contents of dictionary
            Assert.AreEqual(expected["age"], actual["age"]);
            Assert.AreEqual(expected["Name"], actual["Name"]);
            Assert.AreEqual(expected["Location"], actual["Location"]);
            Assert.AreEqual(expected["Timestamp"], actual["Timestamp"]);
            Assert.IsFalse(actual.ContainsKey("EmptyMember"));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Queues a message for sending in the response stream where the fields
        /// are sent in the response stream in querystring style.
        /// </summary>
        /// <param name="response">The message to send as a response.</param>
        /// <returns>
        /// The pending user agent redirect based message to be sent as an HttpResponse.
        /// </returns>
        /// <remarks>
        /// This method implements spec V1.0 section 5.3.
        /// </remarks>
        protected override UserAgentResponse SendDirectMessageResponse(IProtocolMessage response)
        {
            ErrorUtilities.VerifyArgumentNotNull(response, "response");

            var serializer = MessageSerializer.Get(response.GetType());
            var fields     = serializer.Serialize(response);

            byte[] keyValueEncoding = KeyValueFormEncoding.GetBytes(fields);

            UserAgentResponse preparedResponse = new UserAgentResponse();

            preparedResponse.Headers.Add(HttpResponseHeader.ContentType, KeyValueFormContentType);
            preparedResponse.OriginalMessage = response;
            preparedResponse.ResponseStream  = new MemoryStream(keyValueEncoding);

            IHttpDirectResponse httpMessage = response as IHttpDirectResponse;

            if (httpMessage != null)
            {
                preparedResponse.Status = httpMessage.HttpStatusCode;
            }

            return(preparedResponse);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Queues a message for sending in the response stream where the fields
        /// are sent in the response stream in querystring style.
        /// </summary>
        /// <param name="response">The message to send as a response.</param>
        /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
        /// <remarks>
        /// This method implements spec V1.0 section 5.3.
        /// </remarks>
        protected override UserAgentResponse SendDirectMessageResponse(IProtocolMessage response)
        {
            ErrorUtilities.VerifyArgumentNotNull(response, "response");

            MessageSerializer serializer = MessageSerializer.Get(response.GetType());
            var    fields       = serializer.Serialize(response);
            string responseBody = MessagingUtilities.CreateQueryString(fields);

            UserAgentResponse encodedResponse = new UserAgentResponse {
                Body            = responseBody,
                OriginalMessage = response,
                Status          = HttpStatusCode.OK,
                Headers         = new System.Net.WebHeaderCollection(),
            };

            IHttpDirectResponse httpMessage = response as IHttpDirectResponse;

            if (httpMessage != null)
            {
                encodedResponse.Status = httpMessage.HttpStatusCode;
            }

            return(encodedResponse);
        }
Ejemplo n.º 15
0
 public void GetInvalidMessageType()
 {
     MessageSerializer.Get(typeof(string));
 }
Ejemplo n.º 16
0
 public void GetNullType()
 {
     MessageSerializer.Get(null);
 }
Ejemplo n.º 17
0
        public void DeserializeNull()
        {
            var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));

            MessageSerializer.Deserialize(null, null);
        }