Ejemplo n.º 1
0
 internal static bool IsDefined(WebContentFormat format)
 {
     return(format == WebContentFormat.Default ||
            format == WebContentFormat.Xml ||
            format == WebContentFormat.Json ||
            format == WebContentFormat.Raw);
 }
 internal static bool IsDefined(WebContentFormat format)
 {
     return (format == WebContentFormat.Default
         || format == WebContentFormat.Xml
         || format == WebContentFormat.Json
         || format == WebContentFormat.Raw);
 }
Ejemplo n.º 3
0
        public void PutShouldRespectIfMatch(WebContentFormat format, string serviceUri = null)
        {
            // Arrange
            int resourceKey = 1;
            var testHelper  = new HttpTestHelper <int, Resource>(serviceUri ?? ServiceUri);

            // Act
            var resultGet = testHelper.GetResource(resourceKey, requestUri: ServiceUri);

            Assert.AreEqual(HttpStatusCode.OK, resultGet.Status);

            var putResource = resultGet.Resource;

            putResource.Data = "modified";

            // Put without an entity tag
            var resultPut1 = testHelper.PutResource(resourceKey, putResource, format: format);

            // Put with an entity tag
            var resultPut2 = testHelper.PutResource(resourceKey, putResource, new EntityTag(putResource.Version.ToString()), format: format);

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, resultPut1.Status);
            Assert.AreEqual(HttpStatusCode.PreconditionFailed, resultPut2.Status);
        }
Ejemplo n.º 4
0
        private void PutShouldBeIdempotent(WebContentFormat format, string serviceUri = null)
        {
            // Arrange
            int resourceKey = 1;
            var testHelper  = new HttpTestHelper <int, Resource>(serviceUri ?? ServiceUri);

            // Act
            var resultGet = testHelper.GetResource(resourceKey, requestUri: ServiceUri);

            Assert.AreEqual(HttpStatusCode.OK, resultGet.Status);

            var putResource = resultGet.Resource;

            putResource.Data = "modified";

            // Put without an entity tag
            var resultPut1 = testHelper.PutResource(resourceKey, putResource);

            // Put without an entity tag
            var resultPut2 = testHelper.PutResource(resourceKey, putResource);

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, resultPut1.Status);
            Assert.AreEqual(HttpStatusCode.OK, resultPut2.Status);
        }
Ejemplo n.º 5
0
        public void POST_MUST_append_a_valid_resource_to_the_resource_collection(WebContentFormat format)
        {
            // Arrange
            string expectedData     = "Post Data";
            var    expectedResource = new Resource()
            {
                Data = expectedData
            };
            var testHelper = new HttpTestHelper <int, Resource>(ServiceUri);

            // Act
            var result = testHelper.Post(expectedResource, format);

            // Assert
            Assert.AreEqual(HttpStatusCode.Created, result.Status);

            // Check entity
            Assert.AreEqual(expectedData, result.Resource.Data);

            // Check headers
            Assert.IsNotNull(result.ResponseHeaders.ETag, "Null etag");
            Assert.IsNotNull(result.ResponseHeaders.Location, "Null location");

            // Check server generated key and location header
            Assert.AreEqual(result.Resource.Key, int.Parse(result.LocationKey), "Location header key should match entity key");
            Assert.IsTrue(result.Resource.Key > 5, "Server generated key should be > 5 on test data set");
        }
Ejemplo n.º 6
0
            public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
            {
                if (stream == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
                }

                WebContentFormat format = GetFormatForContentType(contentType);
                Message          message;

                switch (format)
                {
                case WebContentFormat.Json:
                    message = JsonMessageEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
                    message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
                    break;

                case WebContentFormat.Xml:
                    message = TextMessageEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
                    message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
                    break;

                case WebContentFormat.Raw:
                    message = RawMessageEncoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
                    message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
                    break;

                default:
                    throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                }
                return(message);
            }
Ejemplo n.º 7
0
            bool TryGetContentTypeMapping(string contentType, out WebContentFormat format)
            {
                if (contentTypeMapper == null)
                {
                    format = WebContentFormat.Default;
                    return(false);
                }

                try
                {
                    format = contentTypeMapper.GetMessageFormatForContentType(contentType);
                    if (!WebContentFormatHelper.IsDefined(format))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR2.GetString(SR2.UnknownWebEncodingFormat, contentType, format)));
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                                  SR2.GetString(SR2.ErrorEncounteredInContentTypeMapper), e));
                }
            }
Ejemplo n.º 8
0
        protected XmlObjectSerializer GetSerializer(WebContentFormat msgfmt)
        {
            switch (msgfmt)
            {
            case WebContentFormat.Xml:
                if (IsResponseBodyWrapped)
                {
                    return(GetSerializer(ref xml_serializer, p => new DataContractSerializer(p.Type, p.Name, p.Namespace)));
                }
                else
                {
                    return(GetSerializer(ref xml_serializer, p => new DataContractSerializer(p.Type)));
                }
                break;

            case WebContentFormat.Json:
                // FIXME: after name argument they are hack
#if !NET_2_1 || MONOTOUCH
                if (IsResponseBodyWrapped)
                {
                    return(GetSerializer(ref json_serializer, p => new DataContractJsonSerializer(p.Type, BodyName ?? p.Name, null, 0x100000, false, null, true)));
                }
                else
#endif
                return(GetSerializer(ref json_serializer, p => new DataContractJsonSerializer(p.Type)));

                break;

            default:
                throw new NotImplementedException();
            }
        }
        protected XmlObjectSerializer GetSerializer(WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
        {
            if (part.Type == typeof(void))
            {
                return(null); // no serialization should be done.
            }
            switch (msgfmt)
            {
            case WebContentFormat.Xml:
                if (xml_serializer == null)
                {
                    xml_serializer = isWrapped ? new DataContractSerializer(part.Type, part.Name, part.Namespace) : new DataContractSerializer(part.Type);
                }
                return(xml_serializer);

            case WebContentFormat.Json:
                // FIXME: after name argument they are hack
                if (json_serializer == null)
#if MOONLIGHT
                { json_serializer = new DataContractJsonSerializer(part.Type); }
#else
                { json_serializer = isWrapped ? new DataContractJsonSerializer(part.Type, BodyName ?? part.Name, null, 0x100000, false, null, true) : new DataContractJsonSerializer(part.Type); }
#endif
                return(json_serializer);

            default:
                throw new NotImplementedException(msgfmt.ToString());
            }
        }
 public WebBodyFormatMessageProperty(WebContentFormat format)
 {
     if (format == WebContentFormat.Default)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR2.GetString(SR2.DefaultContentFormatNotAllowedInProperty)));
     }
     this.format = format;
 }
Ejemplo n.º 11
0
 public WebBodyFormatMessageProperty(WebContentFormat format)
 {
     if (format == WebContentFormat.Default)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR2.GetString(SR2.DefaultContentFormatNotAllowedInProperty)));
     }
     this.format = format;
 }
        public static void SetWebContentFormatProperty(this Message message, WebContentFormat format)
        {
            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
                message.Properties.Remove(WebBodyFormatMessageProperty.Name);

            message.Properties.Add(WebBodyFormatMessageProperty.Name,
                            new WebBodyFormatMessageProperty(format));
        }
Ejemplo n.º 13
0
 public ResourceResult <TResource> Post(TResource resource, WebContentFormat format = WebContentFormat.Xml)
 {
     return(SendRequest(
                "POST",
                new Uri(ServiceUri),
                format,
                resource));
 }
Ejemplo n.º 14
0
        public static string MessageToString(ref Message message)
        {
            WebContentFormat messageFormat = message.GetContentFormat();

            MemoryStream        ms     = new MemoryStream();
            XmlDictionaryWriter writer = null;

            switch (messageFormat)
            {
            case WebContentFormat.Default:
            case WebContentFormat.Xml:
                writer = XmlDictionaryWriter.CreateTextWriter(ms);
                break;

            case WebContentFormat.Json:
                writer = JsonReaderWriterFactory.CreateJsonWriter(ms);
                break;

            case WebContentFormat.Raw:
                return(ReadRawBody(ref message));
            }

            message.WriteMessage(writer);

            writer.Flush();

            string messageBody = Encoding.UTF8.GetString(ms.ToArray());

            // The messageBody can be modified here...

            // Then recreate the message...

            ms.Position = 0;

            // if the message body was modified, needs to reencode it, as show below
            // ms = new MemoryStream(Encoding.UTF8.GetBytes(messageBody));

            XmlDictionaryReader reader;

            if (messageFormat == WebContentFormat.Json)
            {
                reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
            }
            else
            {
                reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
            }

            var newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);

            message = newMessage;

            return(messageBody);
        }
Ejemplo n.º 15
0
        public static void SetWebContentFormatProperty(this Message message, WebContentFormat format)
        {
            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
            {
                message.Properties.Remove(WebBodyFormatMessageProperty.Name);
            }

            message.Properties.Add(WebBodyFormatMessageProperty.Name,
                                   new WebBodyFormatMessageProperty(format));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets the format used for the message body.
        /// </summary>
        ///
        /// <param name="message">
        /// The message.
        /// </param>
        ///
        /// <returns>
        /// The System.ServiceModel.Channels.WebContentFormat that specifies the format used for the message body.
        /// </returns>
        public static WebContentFormat GetContentFormat(this Message message)
        {
            WebContentFormat format = WebContentFormat.Default;

            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
            {
                format = ((WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name]).Format;
            }

            return(format);
        }
 public WebHttpErrorHandler(WebMessageFormat format)
 {
     if (format == WebMessageFormat.Json)
     {
         this.format = WebContentFormat.Json;
     }
     else
     {
         this.format = WebContentFormat.Xml;
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Get the message's classified format
        /// </summary>
        private WebContentFormat GetContentFormat(Message message)
        {
            WebContentFormat retVal = WebContentFormat.Default;

            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
            {
                WebBodyFormatMessageProperty propertyValue = message.Properties[WebBodyFormatMessageProperty.Name] as WebBodyFormatMessageProperty;
                retVal = propertyValue.Format;
            }
            return(retVal);
        }
        private WebContentFormat GetMessageContentFormat(Message message)
        {
            WebContentFormat format = WebContentFormat.Default;

            if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
            {
                WebBodyFormatMessageProperty bodyFormat = (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name];
                format = bodyFormat.Format;
            }

            return(format);
        }
Ejemplo n.º 20
0
        public static string MessageToString(ref Message message)
        {
            WebContentFormat    messageFormat = GetMessageContentFormat(message);
            MemoryStream        ms            = new MemoryStream();
            XmlDictionaryWriter writer        = null;

            switch (messageFormat)
            {
            case WebContentFormat.Default:
            case WebContentFormat.Xml:
                writer = XmlDictionaryWriter.CreateTextWriter(ms);
                break;

            case WebContentFormat.Json:
                writer = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonWriter(ms);
                break;

            case WebContentFormat.Raw:
                // special case for raw, easier implemented separately
                return(ReadRawBody(ref message));
            }

            message.WriteMessage(writer);
            writer.Flush();

            string messageBody = System.Text.Encoding.UTF8.GetString(ms.ToArray());

            // Here would be a good place to change the message body, if so desired.

            // now that the message was read, it needs to be recreated.
            ms.Position = 0;

            // if the message body was modified, needs to reencode it, as show below
            //ms = new MemoryStream(Encoding.UTF8.GetBytes(messageBody));

            XmlDictionaryReader reader;

            if (messageFormat == WebContentFormat.Json)
            {
                reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
            }
            else
            {
                reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
            }

            Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            message = newMessage;

            return(messageBody);
        }
Ejemplo n.º 21
0
            public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                if (message == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
                }
                if (bufferManager == null)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentNullException("bufferManager"), message);
                }
                if (maxMessageSize < 0)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
                                                                                        SR2.GetString(SR2.ValueMustBeNonNegative)), message);
                }
                if (messageOffset < 0 || messageOffset > maxMessageSize)
                {
                    throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
                                                                                        SR2.GetString(SR2.JsonValueMustBeInRange, 0, maxMessageSize)), message);
                }
                ThrowIfMismatchedMessageVersion(message);

                WebContentFormat messageFormat = ExtractFormatFromMessage(message);
                JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;

                switch (messageFormat)
                {
                case WebContentFormat.Json:
                    return(JsonMessageEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset));

                case WebContentFormat.Xml:
                    if (message.Properties.TryGetValue <JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                        javascriptResponseMessageProperty != null &&
                        !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                    {
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                    }
                    return(TextMessageEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset));

                case WebContentFormat.Raw:
                    if (message.Properties.TryGetValue <JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                        javascriptResponseMessageProperty != null &&
                        !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                    {
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                    }
                    return(RawMessageEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset));

                default:
                    throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                }
            }
Ejemplo n.º 22
0
        private string MessageToString(ref Message message, bool isReturn, ref ReturnMessage <object> returnMessage)
        {
            WebContentFormat    messageFormat = this.GetMessageContentFormat(message);
            MemoryStream        ms            = new MemoryStream();
            XmlDictionaryWriter writer        = null;

            switch (messageFormat)
            {
            case WebContentFormat.Default:
            case WebContentFormat.Xml:
                writer = XmlDictionaryWriter.CreateTextWriter(ms);
                break;

            case WebContentFormat.Json:
                writer = JsonReaderWriterFactory.CreateJsonWriter(ms);
                break;

            case WebContentFormat.Raw:
                // special case for raw, easier implemented separately
                return(this.ReadRawBody(ref message, isReturn, ref returnMessage));
            }
            message.WriteMessage(writer);
            writer.Flush();
            if (isReturn)
            {
                StreamReader   sr         = new StreamReader(ms);
                JsonSerializer serializer = JsonHelper.GetDefaultJsonSerializer();
                object         obj        = serializer.Deserialize(sr, typeof(ReturnMessage <object>));
                returnMessage = obj as ReturnMessage <object>;
            }
            string messageBody = Encoding.UTF8.GetString(ms.ToArray());

            if (string.IsNullOrEmpty(messageBody))
            {
                return(messageBody);
            }
            // Here would be a good place to change the message body, if so desired.
            // now that the message was read, it needs to be recreated.
            ms.Position = 0;
            // if the message body was modified, needs to reencode it, as show below
            // ms = new MemoryStream(Encoding.UTF8.GetBytes(messageBody));
            XmlDictionaryReader reader;

            reader = messageFormat == WebContentFormat.Json
                ? JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max)
                : XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
            Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);

            newMessage.Properties.CopyProperties(message.Properties);
            message = newMessage;
            return(messageBody);
        }
 internal static bool TryGetEncodingFormat(Message message, out WebContentFormat format)
 {
     object prop;
     message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop);
     WebBodyFormatMessageProperty formatProperty = prop as WebBodyFormatMessageProperty;
     if (formatProperty == null)
     {
         format = WebContentFormat.Default;
         return false;
     }
     format = formatProperty.Format;
     return true;
 }
Ejemplo n.º 24
0
        private StringWithOptionalQuality WebContentFormatString(WebContentFormat format)
        {
            switch (format)
            {
            case WebContentFormat.Xml:
                return("application/xml");

            case WebContentFormat.Json:
                return("application/json");

            default:
                throw new ArgumentException(string.Format("Invalid content type for accept header: {0}", format));
            }
        }
Ejemplo n.º 25
0
 private void ReadContent(
     ResourceResult <TResource> result,
     HttpResponseMessage response,
     WebContentFormat format = WebContentFormat.Xml)
 {
     if (ReadResourceContent == null)
     {
         result.ResponseContent = response.Content.ReadAsString();
     }
     else
     {
         result.Resource = ReadResourceContent(response.Content, format);
     }
 }
Ejemplo n.º 26
0
        public TResource ReadResourceAsDataContract(HttpContent content, WebContentFormat format = WebContentFormat.Xml)
        {
            switch (format)
            {
            case WebContentFormat.Xml:
                return(content.ReadAsDataContract <TResource>());

            case WebContentFormat.Json:
                return(content.ReadAsJsonDataContract <TResource>());

            default:
                throw new NotImplementedException("Unsupported WebContentFormat");
            }
        }
Ejemplo n.º 27
0
        public HttpContent CreateResourceDataContract(TResource resource, WebContentFormat format = WebContentFormat.Xml)
        {
            switch (format)
            {
            case WebContentFormat.Xml:
                return(HttpContentExtensions.CreateDataContract <TResource>(resource));

            case WebContentFormat.Json:
                return(HttpContentExtensions.CreateJsonDataContract <TResource>(resource));

            default:
                throw new NotImplementedException("Unsupported WebContentFormat");
            }
        }
Ejemplo n.º 28
0
        public void GET_With_Name_Should_Say_Hello(WebContentFormat format)
        {
            // Arrange
            var    testHelper      = new HttpTestHelper <int, string>(ServiceUri);
            string expectedName    = "Test Name";
            string expectedMessage = string.Format(HelloWorldMessageFormat, expectedName);
            string requestUri      = string.Format(HelloWorldUriFormat, ServiceUri, expectedName);

            // Act
            var result = testHelper.SendRequest("GET", new Uri(requestUri), format);

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, result.Status);
            Assert.AreEqual(expectedMessage, result.Resource);
        }
        internal static bool TryGetEncodingFormat(Message message, out WebContentFormat format)
        {
            object prop;

            message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out prop);
            WebBodyFormatMessageProperty formatProperty = prop as WebBodyFormatMessageProperty;

            if (formatProperty == null)
            {
                format = WebContentFormat.Default;
                return(false);
            }
            format = formatProperty.Format;
            return(true);
        }
        protected string GetMediaTypeString(WebContentFormat fmt)
        {
            switch (fmt)
            {
            case WebContentFormat.Raw:
                return("application/octet-stream");

            case WebContentFormat.Json:
                return("application/json");

            case WebContentFormat.Xml:
            default:
                return("application/xml");
            }
        }
Ejemplo n.º 31
0
        public void GET_MUST_return_zero_or_more_resources_when_take_is_not_provided(WebContentFormat format)
        {
            // Arrange
            int expectedSkip = 5;
            var testHelper   = new HttpTestHelper <int, Resource>(ServiceUri);

            // Act
            var result = testHelper.GetResourceSet(expectedSkip, format: format);

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, result.Status);
            Assert.AreEqual(expectedSkip, result.ResourceSet.Skip);
            Assert.AreEqual(result.ResourceSet.Resources.Count(), result.ResourceSet.SetCount);
            Assert.IsTrue(result.ResourceSet.Resources.Count() > 0);
        }
Ejemplo n.º 32
0
        public ResourceSetResult <TResource> GetResourceSet(
            int?skip = null,
            int?take = null,
            WebContentFormat format = WebContentFormat.Xml)
        {
            var result = new ResourceSetResult <TResource>();

            using (HttpClient client = new HttpClient())
            {
                Uri requestUri = CreateSkipTakeQueryString(skip, take);
                using (HttpRequestMessage request = new HttpRequestMessage("GET", requestUri))
                {
                    Debug.WriteLine("Sending GET to {0}", requestUri);

                    request.Headers.Accept.Add(WebContentFormatString(format));

                    using (HttpResponseMessage response = client.Send(request))
                    {
                        Debug.WriteLine("Response: {0} ({1})", (int)response.StatusCode, response.StatusCode);

                        result.Status          = response.StatusCode;
                        result.ResponseHeaders = response.Headers;

                        if (response.Content.HasLength() && response.Content.GetLength() > 0)
                        {
                            switch (result.Status)
                            {
                            case HttpStatusCode.OK:
                                if (ReadResourceSetContent == null)
                                {
                                    result.ResponseContent = response.Content.ReadAsString();
                                }
                                else
                                {
                                    result.ResourceSet = ReadResourceSetContent(response.Content, format);
                                }
                                break;

                            case HttpStatusCode.BadRequest:
                                result.ErrorMessage = response.Content.ReadAsDataContract <string>();
                                break;
                            }
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 33
0
                public WriteMessageAsyncResult(Message message, Stream stream, WebMessageEncoder webMessageEncoder, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.message           = message;
                    this.stream            = stream;
                    this.webMessageEncoder = webMessageEncoder;

                    WebContentFormat messageFormat = webMessageEncoder.ExtractFormatFromMessage(message);
                    JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;

                    switch (messageFormat)
                    {
                    case WebContentFormat.Json:
                        this.encoder = webMessageEncoder.JsonMessageEncoder;
                        this.Schedule();
                        break;

                    case WebContentFormat.Xml:
                        if (message.Properties.TryGetValue <JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                            javascriptResponseMessageProperty != null &&
                            !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                        {
                            throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                        }
                        this.encoder = webMessageEncoder.TextMessageEncoder;
                        this.Schedule();
                        break;

                    case WebContentFormat.Raw:
                        if (message.Properties.TryGetValue <JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
                            javascriptResponseMessageProperty != null &&
                            !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
                        {
                            throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotsupported), message);
                        }

                        handleEndWriteMessage = new AsyncCompletion(HandleEndWriteMessage);
                        IAsyncResult result = webMessageEncoder.RawMessageEncoder.BeginWriteMessage(message, stream, PrepareAsyncCompletion(HandleEndWriteMessage), this);
                        if (SyncContinue(result))
                        {
                            this.Complete(true);
                        }
                        break;

                    default:
                        throw Fx.AssertAndThrow("This should never get hit because GetFormatForContentType shouldn't return a WebContentFormat other than Json, Xml, and Raw");
                    }
                }
Ejemplo n.º 34
0
        public void POST_MUST_return_400_Bad_Request_if_the_entity_is_invalid(WebContentFormat format)
        {
            // Arrange
            string expectedData     = string.Empty;
            var    expectedResource = new Resource()
            {
                Data = expectedData
            };
            var testHelper = new HttpTestHelper <int, Resource>(ServiceUri);

            // Act
            var result = testHelper.Post(expectedResource, format);

            // Assert
            Assert.AreEqual(HttpStatusCode.BadRequest, result.Status);
        }
Ejemplo n.º 35
0
			public WrappedBodyWriter (object value, XmlObjectSerializer serializer, string name, string ns, WebContentFormat fmt)
				: base (true)
			{
				this.name = name;
				this.ns = ns;
				this.value = value;
				this.serializer = serializer;
				this.fmt = fmt;
			}
Ejemplo n.º 36
0
		protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt)
		{
			switch (msgfmt) {
			case WebContentFormat.Xml:
				if (IsResponseBodyWrapped)
					return GetSerializer (ref xml_serializer, p => new DataContractSerializer (p.Type, p.Name, p.Namespace));
				else
					return GetSerializer (ref xml_serializer, p => new DataContractSerializer (p.Type));

			case WebContentFormat.Json:
				// FIXME: after name argument they are hack
#if !MOONLIGHT
				if (IsResponseBodyWrapped)
					return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type, BodyName ?? p.Name, null, 0x100000, false, null, true));
				else
#endif
					return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type));

			default:
				throw new NotImplementedException ();
			}
		}
            bool TryGetContentTypeMapping(string contentType, out WebContentFormat format)
            {
                if (contentTypeMapper == null)
                {
                    format = WebContentFormat.Default;
                    return false;
                }

                try
                {
                    format = contentTypeMapper.GetMessageFormatForContentType(contentType);
                    if (!WebContentFormatHelper.IsDefined(format))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR2.GetString(SR2.UnknownWebEncodingFormat, contentType, format)));
                    }
                    return true;
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                        SR2.GetString(SR2.ErrorEncounteredInContentTypeMapper), e));
                }
            }
Ejemplo n.º 38
0
		protected object DeserializeObject (XmlObjectSerializer serializer, Message message, MessageDescription md, bool isWrapped, WebContentFormat fmt)
		{
			// FIXME: handle ref/out parameters

			var reader = message.GetReaderAtBodyContents ();
			reader.MoveToContent ();

			bool wasEmptyElement = reader.IsEmptyElement;

			if (isWrapped) {
				if (fmt == WebContentFormat.Json)
					reader.ReadStartElement ("root", String.Empty); // note that the wrapper name is passed to the serializer.
				else
					reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
			}

			var ret = (serializer == null) ? null : ReadObjectBody (serializer, reader);

			if (isWrapped && !wasEmptyElement)
				reader.ReadEndElement ();

			return ret;
		}
Ejemplo n.º 39
0
		protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
		{
			if (part.Type == typeof (void))
				return null; // no serialization should be done.

			switch (msgfmt) {
			case WebContentFormat.Xml:
				if (xml_serializer == null)
					xml_serializer = isWrapped ? new DataContractSerializer (part.Type, part.Name, part.Namespace) : new DataContractSerializer (part.Type);
				return xml_serializer;
			case WebContentFormat.Json:
				// FIXME: after name argument they are hack
				if (json_serializer == null)
					json_serializer = isWrapped ? new DataContractJsonSerializer (part.Type, BodyName ?? part.Name, null, 0x100000, false, null, true) : new DataContractJsonSerializer (part.Type);
				return json_serializer;
			default:
				throw new NotImplementedException (msgfmt.ToString ());
			}
		}
Ejemplo n.º 40
0
		public WebBodyFormatMessageProperty (WebContentFormat format)
		{
			this.format = format;
		}
Ejemplo n.º 41
0
		protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
		{
			switch (msgfmt) {
			case WebContentFormat.Xml:
				if (xml_serializer == null)
					xml_serializer = isWrapped ? new DataContractSerializer (part.Type, part.Name, part.Namespace) : new DataContractSerializer (part.Type);
				return xml_serializer;
			case WebContentFormat.Json:
				// FIXME: after name argument they are hack
				if (json_serializer == null)
#if MOONLIGHT
					json_serializer = new DataContractJsonSerializer (part.Type);
#else
					json_serializer = isWrapped ? new DataContractJsonSerializer (part.Type, BodyName ?? part.Name, null, 0x100000, false, null, true) : new DataContractJsonSerializer (part.Type);
#endif
				return json_serializer;
			default:
				throw new NotImplementedException ();
			}
		}
Ejemplo n.º 42
0
		protected string GetMediaTypeString (WebContentFormat fmt)
		{
			switch (fmt) {
			case WebContentFormat.Raw:
				return "application/octet-stream";
			case WebContentFormat.Json:
				return "application/json";
			case WebContentFormat.Xml:
			default:
				return "application/xml";
			}
		}
 public WebHttpErrorHandler(WebMessageFormat format)
 {
     if (format == WebMessageFormat.Json)
     {
         this.format = WebContentFormat.Json;
     }
     else
     {
         this.format = WebContentFormat.Xml;
     }
 }